Files
Media-download-telegram-bot/internal/widget/widget.go
T
MichilisandClaude Opus 5.5 3c153af97f Phase 8: widgets and polish
- Live job card widget (progress bar, in-widget cancel via widget_query)
  and live invoice widget (QR drawn from a bitmap, countdown, paid state),
  Bot API 10.4 sendWidget, private chats only
- Automatic fallback to the ordinary message when sendWidget fails, with
  a breaker that pauses widgets after repeated failures or on servers
  without the method; TELEGRAM_WIDGETS
- Prometheus metrics on the core (/metrics) and on every worker: queue
  depth and wait, slots, heartbeats, job outcomes, errors per site,
  deliveries, cache, invoices, Lightning, ledger check, widgets
- Example Prometheus config and alert rules, Caddyfile, dashboard notes
- Load test: cmd/loadtest and deploy/loadtest (make loadtest)
- Browser check of the widgets' HTML, including decoding a drawn QR
- docs/DEPLOY.md (production in under an hour) and docs/MONITORING.md

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

230 lines
6.1 KiB
Go

// Package widget holds the bot's HTML widgets (Bot API 10.4, sendWidget):
// small documents Telegram draws inside a message and runs in a sandbox
// without network access. The bot changes what they show by editing their
// state with editMessageWidgetData.
//
// There are two: the live status of a download (progress bar, cancel) and
// a Lightning invoice (QR code, countdown, paid state). Their HTML does not
// depend on the language: every text they show arrives in their state,
// already translated by the bot.
//
// Widgets are optional. Whatever goes wrong with one, the bot falls back
// to the ordinary message it would have sent anyway; Breaker decides when
// to stop trying for a while.
package widget
import (
"bytes"
"compress/zlib"
_ "embed"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"unicode/utf8"
qrcode "github.com/skip2/go-qrcode"
)
// Limits from the Bot API.
const (
MaxHTML = 32768 // bytes of UTF-8
MaxCompressedHTML = 4096 // bytes after zlib at level 9
MaxData = 1024 // bytes of chat_data or public_data
)
var (
//go:embed job.html
jobHTML string
//go:embed invoice.html
invoiceHTML string
)
// JobHTML is the download status widget.
func JobHTML() string { return jobHTML }
// InvoiceHTML is the invoice widget.
func InvoiceHTML() string { return invoiceHTML }
// CheckHTML reports whether a widget document is within Telegram's limits.
func CheckHTML(html string) error {
if len(html) == 0 || len(html) > MaxHTML || !utf8.ValidString(html) || strings.ContainsRune(html, 0) {
return fmt.Errorf("widget: html is %d bytes, or not valid UTF-8", len(html))
}
if n := CompressedSize(html); n > MaxCompressedHTML {
return fmt.Errorf("widget: html is %d bytes compressed, the limit is %d", n, MaxCompressedHTML)
}
return nil
}
// CompressedSize is the size of html after zlib at level 9, which is how
// Telegram counts.
func CompressedSize(html string) int {
var buf bytes.Buffer
w, _ := zlib.NewWriterLevel(&buf, zlib.BestCompression)
_, _ = w.Write([]byte(html))
_ = w.Close()
return buf.Len()
}
// Job is the state of the status widget.
type Job struct {
// Kind is "queued", "running" or "end".
Kind string `json:"k"`
// Message is the main line, Detail the smaller one under it.
Message string `json:"m,omitempty"`
Detail string `json:"d,omitempty"`
// Progress is 0 to 1, or below 0 when the amount is unknown, which
// shows a moving bar.
Progress float64 `json:"p"`
// Cancel is the label of the cancel button. Empty hides it.
Cancel string `json:"x,omitempty"`
RTL bool `json:"r,omitempty"`
}
// InvoiceInfo is the fixed part of the invoice widget, its public data.
type InvoiceInfo struct {
Title string `json:"t"`
Amount string `json:"a"`
// Expires is a Unix time in seconds.
Expires int64 `json:"e"`
// Waiting is the countdown text, with {T} where the time goes.
Waiting string `json:"w"`
Checking string `json:"c"`
// QR is the code's modules, row by row, one bit each, in base64. N is
// the number of modules per side. Both are empty when the code does
// not fit.
QR string `json:"q,omitempty"`
N int `json:"n,omitempty"`
RTL bool `json:"r,omitempty"`
}
// InvoiceState is the changing part of the invoice widget.
type InvoiceState struct {
// Status is "pending", "paid", "expired" or "cancelled".
Status string `json:"s"`
Message string `json:"m,omitempty"`
}
// Encode turns a state into widget data. A text field too long for the
// limit is shortened rather than the update dropped.
func Encode(v any) (string, error) {
data, err := json.Marshal(v)
if err != nil {
return "", err
}
if len(data) <= MaxData {
return string(data), nil
}
switch s := v.(type) {
case Job:
s.Detail = ""
s.Message = clip(s.Message, 400)
return Encode(s)
case InvoiceState:
s.Message = clip(s.Message, 400)
return Encode(s)
case InvoiceInfo:
if s.QR != "" {
s.QR, s.N = "", 0
return Encode(s)
}
}
return "", fmt.Errorf("widget: data is %d bytes, the limit is %d", len(data), MaxData)
}
func clip(s string, max int) string {
if len(s) <= max {
return s
}
for max > 0 && !utf8.RuneStart(s[max]) {
max--
}
return s[:max] + "…"
}
// QRBits encodes text as a QR code and packs its modules for the invoice
// widget, which draws them on a canvas. Low error correction keeps the
// code small enough to fit the widget's data.
func QRBits(text string) (n int, b64 string, err error) {
q, err := qrcode.New(text, qrcode.Low)
if err != nil {
return 0, "", err
}
q.DisableBorder = true
bm := q.Bitmap()
n = len(bm)
packed := make([]byte, (n*n+7)/8)
for r, row := range bm {
for c, on := range row {
if on {
i := r*n + c
packed[i/8] |= 0x80 >> (i % 8)
}
}
}
return n, base64.StdEncoding.EncodeToString(packed), nil
}
// Breaker stops widget attempts for a while after they keep failing, so a
// client or Bot API server without widgets does not cost a failed call in
// front of every message.
type Breaker struct {
mu sync.Mutex
failures int
until time.Time
now func() time.Time
}
// NewBreaker returns a breaker that is closed (widgets allowed).
func NewBreaker() *Breaker { return &Breaker{now: time.Now} }
// Allow reports whether a widget may be tried now. A nil breaker means
// widgets are turned off.
func (b *Breaker) Allow() bool {
if b == nil {
return false
}
b.mu.Lock()
defer b.mu.Unlock()
return !b.now().Before(b.until)
}
// ErrUnsupported marks errors that mean the Bot API has no widgets at all.
var ErrUnsupported = errors.New("widget: not supported by this Bot API server")
// Failed records a failed attempt. Unsupported switches widgets off for an
// hour; three failures in a row for ten minutes.
func (b *Breaker) Failed(unsupported bool) (pause time.Duration) {
if b == nil {
return 0
}
b.mu.Lock()
defer b.mu.Unlock()
b.failures++
switch {
case unsupported:
pause = time.Hour
case b.failures >= 3:
pause = 10 * time.Minute
default:
return 0
}
b.failures = 0
b.until = b.now().Add(pause)
return pause
}
// Worked records a successful attempt.
func (b *Breaker) Worked() {
if b == nil {
return
}
b.mu.Lock()
b.failures = 0
b.mu.Unlock()
}