Files
Media-download-telegram-bot/internal/bot/live.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

406 lines
13 KiB
Go

package bot
import (
"context"
"errors"
"html"
"regexp"
"strings"
"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/widget"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// This file puts the live views on top of the ordinary messages: the
// status of a download and an invoice, each as an HTML widget (Bot API
// sendWidget) in private chats. Everything else in the bot keeps working
// on plain messages. A widget is tried once per message; if Telegram
// refuses it, the ordinary message is used and nothing else changes.
//
// The widget's buttons and texts come from its state, set by the bot, so
// the widgets need no translation of their own.
// widgetCancel is the request the status widget sends for its Cancel
// button.
const widgetCancel = "cx"
// States of a status widget attempt.
const (
liveSending = 1
liveRefused = 2
)
// liveJob remembers, per delivery, the widget that shows its status.
type liveJob struct {
messageID int64
buttons string // signature of the keyboard under the widget
}
// liveFor returns the status widget of a delivery, if it has one.
func (b *Bot) liveFor(ctx context.Context, d *db.Delivery) *liveJob {
b.liveMu.Lock()
lj := b.live[d.ID]
b.liveMu.Unlock()
if lj != nil {
return lj
}
// After a restart the memory is empty; the table still knows.
if d.StatusMessageID == 0 {
return nil
}
w, err := b.store.GetWidgetMessage(ctx, d.ChatID, d.StatusMessageID)
if err != nil || w.Kind != db.WidgetJob || w.RefID != d.ID {
return nil
}
lj = &liveJob{messageID: w.MessageID, buttons: "?"}
b.liveMu.Lock()
b.live[d.ID] = lj
b.liveMu.Unlock()
return lj
}
// widgetKeyboard keeps the buttons that still belong under a status
// widget: the widget has its own Cancel, but paying to skip the queue
// stays a normal button.
func widgetKeyboard(kb *telego.InlineKeyboardMarkup) *telego.InlineKeyboardMarkup {
if kb == nil {
return nil
}
var rows [][]telego.InlineKeyboardButton
for _, row := range kb.InlineKeyboard {
var keep []telego.InlineKeyboardButton
for _, btn := range row {
if strings.HasPrefix(btn.CallbackData, cbSkipQueue+":") {
keep = append(keep, btn)
}
}
if len(keep) > 0 {
rows = append(rows, keep)
}
}
if len(rows) == 0 {
return nil
}
return keyboard(rows...)
}
// jobState is what the status widget shows for a delivery now.
func (b *Bot) jobState(ctx context.Context, d *db.Delivery, job *db.Job) widget.Job {
lang := d.Lang
s := widget.Job{Kind: "running", Progress: -1, RTL: i18n.Dir(lang) == "rtl", Cancel: b.tr.T(lang, "btn.cancel", nil)}
switch job.Status {
case db.JobQueued:
pos, _ := b.sched.Position(ctx, job, b.slots())
if b.quietQueue(pos) {
s.Message = b.tr.T(lang, "status.downloading", nil)
break
}
s.Kind = "queued"
s.Message = b.tr.T(lang, "app.queue.waiting", i18n.Args{"Position": pos.Ahead + 1, "Wait": b.tr.Span(lang, pos.Wait)})
case db.JobRunning:
switch {
case job.Stage == ytdlp.StageProcessing:
s.Message = b.tr.T(lang, "status.processing", nil)
case job.Stage == ytdlp.StageUploading:
s.Message = b.tr.T(lang, "status.uploading", nil)
case job.TotalBytes > 0:
ratio := float64(job.ProgressBytes) / float64(job.TotalBytes)
s.Message = b.tr.T(lang, "status.downloading", nil)
s.Progress = float64(int(ratio*1000)) / 1000
s.Detail = b.tr.Percent(lang, ratio) + " · " + b.tr.T(lang, "app.home.used_of", i18n.Args{
"Used": b.tr.Size(lang, job.ProgressBytes), "Max": b.tr.Size(lang, job.TotalBytes),
})
case job.ProgressBytes > 0:
s.Message = b.tr.T(lang, "status.downloading", nil)
s.Detail = b.tr.Size(lang, job.ProgressBytes)
default:
s.Message = b.tr.T(lang, "status.downloading", nil)
}
default:
// Being sent to Telegram: too late to cancel.
s.Message = b.tr.T(lang, "status.uploading", nil)
s.Cancel = ""
}
return s
}
// liveStatus shows a status on the delivery's widget, or turns the status
// into a widget. It reports false when the caller should edit the
// ordinary message instead.
func (b *Bot) liveStatus(ctx context.Context, d *db.Delivery, kb *telego.InlineKeyboardMarkup) bool {
if !isPrivate(d.ChatType) {
return false
}
lj := b.liveFor(ctx, d)
if lj == nil && !b.widgets.Allow() {
return false
}
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
return lj != nil
}
data, err := widget.Encode(b.jobState(ctx, d, job))
if err != nil {
b.log.Warn("status widget state", "delivery_id", d.ID, "err", err)
return lj != nil
}
wkb := widgetKeyboard(kb)
if lj != nil {
b.editWidget(ctx, d.ChatID, lj.messageID, data)
if sig := keyboardSignature(wkb); sig != lj.buttons {
if b.edit(ctx, d.ChatID, lj.messageID, true, titleLine(job.Title), wkb) == nil {
lj.buttons = sig
}
}
return true
}
return b.startLiveJob(ctx, d, job, data, wkb)
}
// startLiveJob sends the status widget and retires the ordinary status
// message. It is tried once per delivery.
func (b *Bot) startLiveJob(ctx context.Context, d *db.Delivery, job *db.Job, data string, kb *telego.InlineKeyboardMarkup) bool {
b.liveMu.Lock()
switch b.liveTried[d.ID] {
case liveSending:
// Another update is sending the widget right now. Editing the old
// message meanwhile would be wasted: it is about to go.
b.liveMu.Unlock()
return true
case liveRefused:
b.liveMu.Unlock()
return false
}
b.liveTried[d.ID] = liveSending
b.liveMu.Unlock()
refused := true
defer func() {
if refused {
b.liveMu.Lock()
b.liveTried[d.ID] = liveRefused
b.liveMu.Unlock()
}
}()
params := &telego.SendWidgetParams{
ChatID: chatID(d.ChatID), HTML: widget.JobHTML(), ChatData: data,
Caption: clip(titleLine(job.Title), 1024), ParseMode: telego.ModeHTML,
AllowQueries: true, ReplyMarkup: kb,
}
// Widgets are for private chats, where nothing is quoted.
msg, err := b.api.SendWidget(ctx, params)
if err != nil {
b.widgetFailed("status", err)
return false
}
refused = false
b.widgets.Worked()
b.metrics.Widget("job", "sent")
id := int64(msg.MessageID)
// Recorded even while shutting down, or the widget could not be
// updated after a restart.
saveCtx := context.WithoutCancel(ctx)
if err := b.store.AddWidgetMessage(saveCtx, db.WidgetMessage{ChatID: d.ChatID, MessageID: id, Kind: db.WidgetJob, RefID: d.ID}); err != nil {
b.log.Error("save widget message", "delivery_id", d.ID, "err", err)
}
if err := b.store.SetDeliveryStatusMessage(saveCtx, d.ID, id, true); err != nil {
b.log.Error("save status message", "delivery_id", d.ID, "err", err)
}
b.liveMu.Lock()
b.live[d.ID] = &liveJob{messageID: id, buttons: keyboardSignature(kb)}
b.liveMu.Unlock()
// The card or the "getting ready" message has done its job.
if old := d.StatusMessageID; old != 0 && old != id {
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(d.ChatID), MessageID: int(old)}); err != nil {
_ = b.edit(ctx, d.ChatID, old, d.StatusIsPhoto, titleLine(job.Title), nil)
}
}
d.StatusMessageID, d.StatusIsPhoto = id, true
return true
}
// liveFinal shows the outcome of a delivery on its widget. It reports
// false when the delivery has no widget, or the widget is gone.
func (b *Bot) liveFinal(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup) bool {
lj := b.liveFor(ctx, d)
b.liveMu.Lock()
delete(b.live, d.ID)
delete(b.liveTried, d.ID)
b.liveMu.Unlock()
if lj == nil {
return false
}
title, rest, _ := strings.Cut(text, "\n")
data, err := widget.Encode(widget.Job{Kind: "end", Message: plainText(rest), RTL: i18n.Dir(d.Lang) == "rtl"})
if err != nil {
return false
}
if err := b.editWidget(ctx, d.ChatID, lj.messageID, data); err != nil && tg.IsMessageGone(err) {
return false
}
// The caption keeps the title; the live buttons under it go, and the
// next steps, if any, take their place.
if lj.buttons != "" || kb != nil {
_ = b.edit(ctx, d.ChatID, lj.messageID, true, title, kb)
}
return true
}
// editWidget changes the state of a widget. A flood wait is respected by
// the throttling of the caller.
func (b *Bot) editWidget(ctx context.Context, chat, messageID int64, data string) error {
err := b.api.EditMessageWidgetData(ctx, &telego.EditMessageWidgetDataParams{
ChatID: chatID(chat), MessageID: int(messageID), ChatData: data,
})
if err != nil && !tg.IsNotModified(err) {
if !tg.IsMessageGone(err) {
b.log.Warn("widget edit failed", "chat_id", chat, "message_id", messageID, "err", err)
}
return err
}
return nil
}
func (b *Bot) widgetFailed(what string, err error) {
unsupported := tg.ErrorCode(err) == 404 || strings.Contains(strings.ToLower(err.Error()), "method not found")
pause := b.widgets.Failed(unsupported)
b.metrics.Widget(what, "fallback")
b.log.Warn("widget refused, using an ordinary message", "widget", what, "err", err, "paused_for", pause.String())
}
var htmlTags = regexp.MustCompile(`<[^>]+>`)
// plainText turns a message in Telegram HTML into text for a widget.
func plainText(s string) string {
return strings.TrimSpace(html.UnescapeString(htmlTags.ReplaceAllString(s, "")))
}
// handleWidgetQuery answers a request from a widget. Only the status
// widget asks for anything: its Cancel button.
func (b *Bot) handleWidgetQuery(ctx context.Context, q *telego.WidgetQuery) {
answer := func(text string) {
var data string
if text != "" {
data = clip(text, 300)
}
if err := b.api.AnswerWidgetQuery(ctx, &telego.AnswerWidgetQueryParams{WidgetQueryID: q.ID, Data: data}); err != nil {
b.log.Debug("answer widget query", "err", err)
}
}
if q.Chat == nil || q.MessageID == 0 || q.Data != widgetCancel {
answer("")
return
}
w, err := b.store.GetWidgetMessage(ctx, q.Chat.ID, int64(q.MessageID))
if err != nil || w.Kind != db.WidgetJob {
answer("")
return
}
act, err := b.actorFor(ctx, &q.From)
if err != nil {
answer("")
return
}
if act.user.Banned {
answer("")
return
}
err = b.cancelDelivery(ctx, w.RefID, act.user.ID)
switch {
case err == nil:
answer(b.tr.T(act.lang, "notice.cancelled", nil))
case errors.Is(err, sched.ErrNotOwner):
answer(b.tr.T(act.lang, "notice.not_yours", nil))
default:
answer(b.tr.T(act.lang, "notice.too_late", nil))
}
}
// --- the invoice widget ------------------------------------------------------
// sendInvoiceWidget shows an invoice as a widget: a QR code drawn from the
// state, a countdown and the paid state. The caption carries the same
// text as the ordinary invoice message, with the BOLT11 string to copy,
// and the same buttons sit under it, so apps without widgets still work.
func (b *Bot) sendInvoiceWidget(ctx context.Context, chat int64, p *db.Purchase, caption string, kb *telego.InlineKeyboardMarkup) bool {
if chat <= 0 || !b.widgets.Allow() {
return false
}
lang := p.Lang
info := widget.InvoiceInfo{
Title: b.productTitle(lang, p.Product),
Amount: b.tr.Sats(lang, p.AmountSats),
Expires: p.ExpiresAt / 1000,
Waiting: b.tr.T(lang, "app.invoice.waiting", i18n.Args{"Time": "{T}"}),
Checking: b.tr.T(lang, "app.invoice.checking", nil),
RTL: i18n.Dir(lang) == "rtl",
}
if n, bits, err := widget.QRBits("LIGHTNING:" + strings.ToUpper(p.Bolt11)); err == nil {
info.N, info.QR = n, bits
}
public, err := widget.Encode(info)
if err != nil {
return false
}
state, _ := widget.Encode(widget.InvoiceState{Status: db.PurchasePending})
msg, err := b.api.SendWidget(ctx, &telego.SendWidgetParams{
ChatID: chatID(chat), HTML: widget.InvoiceHTML(), PublicData: public, ChatData: state,
Caption: clip(caption, 1024), ParseMode: telego.ModeHTML, ReplyMarkup: kb,
})
if err != nil {
b.widgetFailed("invoice", err)
return false
}
b.widgets.Worked()
b.metrics.Widget("invoice", "sent")
if err := b.store.AddWidgetMessage(context.WithoutCancel(ctx), db.WidgetMessage{
ChatID: chat, MessageID: int64(msg.MessageID), Kind: db.WidgetInvoice, RefID: p.ID,
}); err != nil {
b.log.Error("save widget message", "purchase_id", p.ID, "err", err)
}
// A widget message has a caption, so it is edited like a photo.
b.rememberInvoice(ctx, p, chat, int64(msg.MessageID), true)
return true
}
// liveInvoice moves an invoice widget to its final state. The caption is
// edited by the caller as for an ordinary invoice.
func (b *Bot) liveInvoice(ctx context.Context, p *db.Purchase, text string) {
if p.MessageID == 0 {
return
}
w, err := b.store.GetWidgetMessage(ctx, p.ChatID, p.MessageID)
if err != nil || w.Kind != db.WidgetInvoice {
return
}
state, err := widget.Encode(widget.InvoiceState{Status: p.Status, Message: plainText(text)})
if err == nil {
_ = b.editWidget(ctx, p.ChatID, p.MessageID, state)
}
}
// SweepWidgets forgets, every interval until ctx ends, the widget rows
// of messages nobody will edit again: a week after they were sent.
func (b *Bot) SweepWidgets(ctx context.Context, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
cut := time.Now().Add(-7 * 24 * time.Hour).UnixMilli()
if n, err := b.store.DeleteWidgetMessagesBefore(ctx, cut); err == nil && n > 0 {
b.log.Debug("forgot old widget messages", "count", n)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}