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>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f1f9c6156c
commit
3c153af97f
@@ -19,10 +19,12 @@ import (
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/groups"
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
"github.com/noderunners/dlbot/internal/metrics"
|
||||
"github.com/noderunners/dlbot/internal/sched"
|
||||
"github.com/noderunners/dlbot/internal/service"
|
||||
"github.com/noderunners/dlbot/internal/storage"
|
||||
"github.com/noderunners/dlbot/internal/tg"
|
||||
"github.com/noderunners/dlbot/internal/widget"
|
||||
)
|
||||
|
||||
// Deps are the collaborators of the bot.
|
||||
@@ -46,6 +48,8 @@ type Deps struct {
|
||||
Admins *groups.Admins
|
||||
// ReloadI18n reloads the catalogs from disk. Nil when they are built in.
|
||||
ReloadI18n func() error
|
||||
// Metrics records what happens. Nil records nothing.
|
||||
Metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// Bot handles Telegram updates and job events.
|
||||
@@ -74,6 +78,13 @@ type Bot struct {
|
||||
bg sync.WaitGroup
|
||||
baseCtx context.Context
|
||||
|
||||
metrics *metrics.Metrics
|
||||
// widgets decides whether HTML widgets are tried; nil turns them off.
|
||||
widgets *widget.Breaker
|
||||
liveMu sync.Mutex
|
||||
live map[string]*liveJob // status widgets by delivery ID
|
||||
liveTried map[string]int // deliveries a status widget was tried for
|
||||
|
||||
statusMu sync.Mutex
|
||||
statuses map[string]*statusState // by delivery ID
|
||||
sending map[string]bool // jobs being delivered right now
|
||||
@@ -130,6 +141,9 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
|
||||
rate: newRateLimiter(),
|
||||
baseCtx: ctx,
|
||||
statuses: map[string]*statusState{},
|
||||
metrics: d.Metrics,
|
||||
live: map[string]*liveJob{},
|
||||
liveTried: map[string]int{},
|
||||
sending: map[string]bool{},
|
||||
pumping: map[int64]bool{},
|
||||
cancelledAt: map[int64]time.Time{},
|
||||
@@ -144,6 +158,9 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
|
||||
if b.admins == nil {
|
||||
b.admins = groups.NewAdmins(d.API, 0)
|
||||
}
|
||||
if d.Config.Telegram.Widgets {
|
||||
b.widgets = widget.NewBreaker()
|
||||
}
|
||||
d.Service.SetAdmins(b.admins)
|
||||
d.Sched.Subscribe(func(ev sched.Event) {
|
||||
select {
|
||||
@@ -261,12 +278,18 @@ func updateChatID(u telego.Update) int64 {
|
||||
return u.CallbackQuery.From.ID
|
||||
case u.MyChatMember != nil:
|
||||
return u.MyChatMember.Chat.ID
|
||||
case u.WidgetQuery != nil:
|
||||
if u.WidgetQuery.Chat != nil {
|
||||
return u.WidgetQuery.Chat.ID
|
||||
}
|
||||
return u.WidgetQuery.From.ID
|
||||
}
|
||||
return int64(u.UpdateID)
|
||||
}
|
||||
|
||||
// HandleUpdate routes one update.
|
||||
func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
|
||||
b.metrics.Update(updateType(u))
|
||||
switch {
|
||||
case u.Message != nil:
|
||||
b.handleMessage(ctx, u.Message)
|
||||
@@ -274,9 +297,25 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) {
|
||||
b.handleCallback(ctx, u.CallbackQuery)
|
||||
case u.MyChatMember != nil:
|
||||
b.handleMyChatMember(ctx, u.MyChatMember)
|
||||
case u.WidgetQuery != nil:
|
||||
b.handleWidgetQuery(ctx, u.WidgetQuery)
|
||||
}
|
||||
}
|
||||
|
||||
func updateType(u telego.Update) string {
|
||||
switch {
|
||||
case u.Message != nil:
|
||||
return "message"
|
||||
case u.CallbackQuery != nil:
|
||||
return "callback_query"
|
||||
case u.MyChatMember != nil:
|
||||
return "my_chat_member"
|
||||
case u.WidgetQuery != nil:
|
||||
return "widget_query"
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
|
||||
// actor is the user behind an update, with the language to answer in.
|
||||
type actor struct {
|
||||
user *db.User
|
||||
|
||||
@@ -161,6 +161,11 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop
|
||||
log.Error("record usage", "err", err)
|
||||
}
|
||||
log.Info("file delivered", "size", job.FileSize, "profile", job.Profile, "cache_hit", job.CacheHit)
|
||||
via := "upload"
|
||||
if job.CacheHit {
|
||||
via = "cache"
|
||||
}
|
||||
b.metrics.Delivered(via)
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil))
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
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:
|
||||
s.Kind = "queued"
|
||||
pos, _ := b.sched.Position(ctx, job, b.slots())
|
||||
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,
|
||||
}
|
||||
if d.ReplyToMessageID != 0 {
|
||||
params.ReplyParameters = &telego.ReplyParameters{MessageID: int(d.ReplyToMessageID), AllowSendingWithoutReply: true}
|
||||
}
|
||||
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) 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 buttons under it go.
|
||||
if lj.buttons != "" {
|
||||
_ = b.edit(ctx, d.ChatID, lj.messageID, true, title, nil)
|
||||
}
|
||||
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:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,6 +404,9 @@ func (b *Bot) invoiceKeyboard(p *db.Purchase) *telego.InlineKeyboardMarkup {
|
||||
func (b *Bot) sendInvoice(ctx context.Context, chat int64, p *db.Purchase) {
|
||||
text := b.invoiceText(p)
|
||||
kb := b.invoiceKeyboard(p)
|
||||
if b.sendInvoiceWidget(ctx, chat, p, text, kb) {
|
||||
return
|
||||
}
|
||||
// Upper case BOLT11 lets the QR code use its compact alphanumeric mode.
|
||||
png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512)
|
||||
if err == nil {
|
||||
@@ -452,11 +455,13 @@ func (b *Bot) showPurchaseState(ctx context.Context, p *db.Purchase) {
|
||||
lang := p.Lang
|
||||
switch p.Status {
|
||||
case db.PurchasePaid:
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.paidText(ctx, p), nil)
|
||||
text := b.paidText(ctx, p)
|
||||
b.liveInvoice(ctx, p, text)
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, text, nil)
|
||||
case db.PurchaseExpired:
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.tr.HTML(lang, "invoice.expired", i18n.Args{
|
||||
"Title": b.productTitle(lang, p.Product),
|
||||
}), nil)
|
||||
text := b.tr.HTML(lang, "invoice.expired", i18n.Args{"Title": b.productTitle(lang, p.Product)})
|
||||
b.liveInvoice(ctx, p, text)
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, text, nil)
|
||||
case db.PurchaseCancelled:
|
||||
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(p.ChatID), MessageID: int(p.MessageID)}); err != nil {
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.tr.HTML(lang, "invoice.cancelled", nil), nil)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
"github.com/noderunners/dlbot/internal/links"
|
||||
"github.com/noderunners/dlbot/internal/sched"
|
||||
"github.com/noderunners/dlbot/internal/tg"
|
||||
"github.com/noderunners/dlbot/internal/ytdlp"
|
||||
@@ -63,6 +64,7 @@ func (b *Bot) eventLoop(ctx context.Context) {
|
||||
}
|
||||
|
||||
func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) {
|
||||
b.observe(ctx, ev)
|
||||
switch ev.Type {
|
||||
case sched.EventStarted, sched.EventProgress, sched.EventRequeued:
|
||||
b.refreshStatus(ctx, ev.JobID)
|
||||
@@ -234,6 +236,9 @@ func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *te
|
||||
b.statuses[d.ID] = &statusState{text: shown, buttons: keyboardSignature(kb), phase: phase, at: now}
|
||||
b.statusMu.Unlock()
|
||||
|
||||
if b.liveStatus(ctx, d, kb) {
|
||||
return
|
||||
}
|
||||
if err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb); err != nil {
|
||||
if wait := tg.RetryAfter(err); wait > 0 {
|
||||
// Back off this message for as long as Telegram asked.
|
||||
@@ -254,6 +259,9 @@ func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) {
|
||||
b.statusMu.Lock()
|
||||
delete(b.statuses, d.ID)
|
||||
b.statusMu.Unlock()
|
||||
if b.liveFinal(ctx, d, text) {
|
||||
return
|
||||
}
|
||||
if d.StatusMessageID != 0 {
|
||||
err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, nil)
|
||||
if err == nil || !tg.IsMessageGone(err) {
|
||||
@@ -262,3 +270,32 @@ func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) {
|
||||
}
|
||||
_, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, nil)
|
||||
}
|
||||
|
||||
// observe feeds the metrics from job events.
|
||||
func (b *Bot) observe(ctx context.Context, ev sched.Event) {
|
||||
if b.metrics == nil {
|
||||
return
|
||||
}
|
||||
switch ev.Type {
|
||||
case sched.EventStarted, sched.EventStored, sched.EventFailed, sched.EventCancelled:
|
||||
default:
|
||||
return
|
||||
}
|
||||
job, err := b.store.GetJob(ctx, ev.JobID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch ev.Type {
|
||||
case sched.EventStarted:
|
||||
if job.QueuedAt > 0 && job.StartedAt >= job.QueuedAt {
|
||||
b.metrics.QueueWait(time.Duration(job.StartedAt-job.QueuedAt) * time.Millisecond)
|
||||
}
|
||||
case sched.EventStored:
|
||||
b.metrics.JobFinished("done", job.Lane)
|
||||
case sched.EventFailed:
|
||||
b.metrics.JobFinished("failed", job.Lane)
|
||||
b.metrics.DownloadError(links.Site(job.URL), job.ErrorCode)
|
||||
case sched.EventCancelled:
|
||||
b.metrics.JobFinished("cancelled", job.Lane)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user