Lightning payments through LNbits, wallets, passes, credits, the entitlement resolver and priority lanes. - internal/entitle: pure resolver (one-off, own pass, group pass, group credits, own credits, free) with a table-driven suite and an invariant check over every input combination - internal/billing: wallets, append-only ledger with dedupe keys, stacking passes, purchases, gift codes, referral reward - LNbits client verified against v0.12.12 and v1.7.1 source - Settlement by one conditional UPDATE: idempotent under any mix of webhooks, polls and the check button. Webhooks are unsigned, so every payment is confirmed with LNbits before it is credited - Polling fallback, reconciliation of all unsettled invoices at startup, late payments still honored, no expiry while LNbits is unreachable - Charge, quota and job are written in one transaction; failed, cancelled and undeliverable downloads are refunded exactly once - Paid lane first with one slot of the fleet reserved for free users - Daily download quota and daily volume cap, per-user and per-group rate limits - Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice message that flips to paid, over-limit offer (passes or this file only), deep links from groups, skip the queue - Fake LNbits server for tests; end-to-end money flows including a payment made while the core was down Cashu redemption is behind an interface and not implemented. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
260 lines
8.4 KiB
Go
260 lines
8.4 KiB
Go
package bot
|
|
|
|
import (
|
|
"context"
|
|
"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/ytdlp"
|
|
)
|
|
|
|
// statusState remembers what a status message shows, so edits that would
|
|
// change nothing or come too fast are skipped.
|
|
type statusState struct {
|
|
text string
|
|
buttons string
|
|
phase string
|
|
at time.Time
|
|
}
|
|
|
|
// keyboardSignature identifies a keyboard by the callback data and links
|
|
// of its buttons.
|
|
func keyboardSignature(kb *telego.InlineKeyboardMarkup) string {
|
|
if kb == nil {
|
|
return ""
|
|
}
|
|
var sb strings.Builder
|
|
for _, row := range kb.InlineKeyboard {
|
|
for _, btn := range row {
|
|
sb.WriteString(btn.CallbackData)
|
|
sb.WriteString(btn.URL)
|
|
sb.WriteByte('|')
|
|
}
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
// eventLoop reacts to job events and periodically reconciles, which covers
|
|
// dropped events and work left over from before a restart.
|
|
func (b *Bot) eventLoop(ctx context.Context) {
|
|
b.safely("reconcile", func() { b.reconcile(ctx) })
|
|
t := time.NewTicker(b.reconcileEvery)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case ev := <-b.events:
|
|
b.safely("event", func() { b.handleEvent(ctx, ev) })
|
|
case ev := <-b.payEvents:
|
|
b.safely("payment", func() { b.handlePayEvent(ctx, ev) })
|
|
case <-t.C:
|
|
b.safely("reconcile", func() { b.reconcile(ctx) })
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) {
|
|
switch ev.Type {
|
|
case sched.EventStarted, sched.EventProgress, sched.EventRequeued:
|
|
b.refreshStatus(ctx, ev.JobID)
|
|
case sched.EventStored:
|
|
b.goBG("deliver", func() { b.deliverJob(ctx, ev.JobID) })
|
|
case sched.EventFailed:
|
|
b.failJob(ctx, ev.JobID)
|
|
case sched.EventCancelled:
|
|
b.cleanupCancelled(ctx, ev.JobID)
|
|
}
|
|
}
|
|
|
|
// reconcile brings Telegram in line with the database: it resumes
|
|
// deliveries, reports failures, frees stuck uploads and refreshes the
|
|
// position shown on queued jobs.
|
|
func (b *Bot) reconcile(ctx context.Context) {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
stale, err := b.store.StaleSendingDeliveries(ctx, db.NowMilli()-staleSending.Milliseconds())
|
|
if err != nil {
|
|
b.log.Error("reconcile: stale deliveries", "err", err)
|
|
}
|
|
for _, d := range stale {
|
|
if _, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliverySending, db.DeliveryPending, ""); err != nil {
|
|
b.log.Error("reconcile: reset delivery", "delivery_id", d.ID, "err", err)
|
|
}
|
|
}
|
|
each := func(status string, fn func(jobID string)) {
|
|
jobIDs, err := b.store.PendingDeliveryJobIDs(ctx, status, 200)
|
|
if err != nil {
|
|
b.log.Error("reconcile: list jobs", "status", status, "err", err)
|
|
return
|
|
}
|
|
for _, id := range jobIDs {
|
|
fn(id)
|
|
}
|
|
}
|
|
each(db.JobDelivering, func(id string) { b.goBG("deliver", func() { b.deliverJob(ctx, id) }) })
|
|
each(db.JobFailed, func(id string) { b.failJob(ctx, id) })
|
|
each(db.JobCancelled, func(id string) { b.cleanupCancelled(ctx, id) })
|
|
each(db.JobQueued, func(id string) { b.refreshStatus(ctx, id) })
|
|
each(db.JobRunning, func(id string) { b.refreshStatus(ctx, id) })
|
|
|
|
// Refunds and paid follow-ups that an interruption left undone.
|
|
b.svc.ReleasePending(ctx)
|
|
b.fulfilPending(ctx)
|
|
|
|
// Jobs whose requesters were all served but that were never closed.
|
|
delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200)
|
|
if err != nil {
|
|
b.log.Error("reconcile: delivering jobs", "err", err)
|
|
return
|
|
}
|
|
for _, j := range delivering {
|
|
b.finishIfServed(ctx, j)
|
|
}
|
|
}
|
|
|
|
// staleSending is how long a delivery may sit in "sending" before it is
|
|
// assumed to be left over from a crash.
|
|
const staleSending = 20 * time.Minute
|
|
|
|
// refreshStatus updates the status message of every waiting requester of
|
|
// a job.
|
|
func (b *Bot) refreshStatus(ctx context.Context, jobID string) {
|
|
job, err := b.store.GetJob(ctx, jobID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if job.Status != db.JobQueued && job.Status != db.JobRunning {
|
|
return
|
|
}
|
|
dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending)
|
|
if err != nil {
|
|
b.log.Error("list deliveries", "job_id", jobID, "err", err)
|
|
return
|
|
}
|
|
for _, d := range dels {
|
|
text, kb, phase := b.renderStatus(ctx, d, job)
|
|
b.setStatus(ctx, d, text, kb, phase, false)
|
|
}
|
|
}
|
|
|
|
// renderStatus builds the live status text of a delivery. phase groups
|
|
// states that only differ in numbers, which is what throttling keys on.
|
|
func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (text string, kb *telego.InlineKeyboardMarkup, phase string) {
|
|
lang := d.Lang
|
|
head := titleLine(job.Title) + "\n"
|
|
cancel := b.cancelJobKeyboard(lang, d.ID)
|
|
switch job.Status {
|
|
case db.JobQueued:
|
|
kb := cancel
|
|
if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 {
|
|
kb = b.queuedKeyboard(lang, d.ID)
|
|
}
|
|
pos, err := b.sched.Position(ctx, job, b.slots())
|
|
if err != nil {
|
|
b.log.Error("queue position", "job_id", job.ID, "err", err)
|
|
}
|
|
return head + b.tr.HTML(lang, "status.queued", i18n.Args{
|
|
"Position": pos.Ahead + 1,
|
|
"Wait": b.tr.Span(lang, pos.Wait),
|
|
}), kb, "queued"
|
|
case db.JobRunning:
|
|
switch job.Stage {
|
|
case ytdlp.StageProcessing:
|
|
return head + b.tr.HTML(lang, "status.processing", nil), cancel, "processing"
|
|
case ytdlp.StageUploading:
|
|
return head + b.tr.HTML(lang, "status.uploading", nil), cancel, "uploading"
|
|
}
|
|
switch {
|
|
case job.TotalBytes > 0:
|
|
ratio := float64(job.ProgressBytes) / float64(job.TotalBytes)
|
|
return head + b.tr.HTML(lang, "status.downloading_progress", i18n.Args{
|
|
"Bar": bar(ratio),
|
|
"Percent": b.tr.Percent(lang, ratio),
|
|
"Done": b.tr.Size(lang, job.ProgressBytes),
|
|
"Total": b.tr.Size(lang, job.TotalBytes),
|
|
}), cancel, "downloading"
|
|
case job.ProgressBytes > 0:
|
|
return head + b.tr.HTML(lang, "status.downloading_bytes", i18n.Args{
|
|
"Done": b.tr.Size(lang, job.ProgressBytes),
|
|
}), cancel, "downloading"
|
|
}
|
|
return head + b.tr.HTML(lang, "status.downloading", nil), cancel, "downloading"
|
|
case db.JobDelivering:
|
|
return head + b.tr.HTML(lang, "status.uploading", nil), nil, "uploading"
|
|
case db.JobDone:
|
|
return head + b.tr.HTML(lang, "status.done", nil), nil, "done"
|
|
case db.JobCancelled:
|
|
return head + b.tr.HTML(lang, "status.cancelled", nil), nil, "cancelled"
|
|
default:
|
|
return head + b.failureText(lang, job.ErrorCode), nil, "failed"
|
|
}
|
|
}
|
|
|
|
// failureText is the user-facing explanation of a failed job.
|
|
func (b *Bot) failureText(lang, code string) string {
|
|
if code == "" {
|
|
code = string(ytdlp.CodeUnknown)
|
|
}
|
|
return b.tr.HTML(lang, "status.failed", i18n.Args{"Reason": b.tr.T(lang, "error."+code, nil)})
|
|
}
|
|
|
|
// setStatus edits the status message unless nothing changed or the last
|
|
// edit of the same phase was too recent. Telegram limits how often a
|
|
// message may be edited, and progress numbers are not worth a flood wait.
|
|
func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup, phase string, force bool) {
|
|
if d.StatusMessageID == 0 {
|
|
return
|
|
}
|
|
now := time.Now()
|
|
// What the message shows is its text and its buttons. A change in
|
|
// either is worth an edit, for example "Skip the queue" disappearing.
|
|
shown := text + "\x00" + keyboardSignature(kb)
|
|
b.statusMu.Lock()
|
|
st := b.statuses[d.ID]
|
|
if st != nil {
|
|
sameButtons := keyboardSignature(kb) == st.buttons
|
|
if st.text == shown || (!force && sameButtons && st.phase == phase && now.Sub(st.at) < b.statusMinGap) {
|
|
b.statusMu.Unlock()
|
|
return
|
|
}
|
|
}
|
|
b.statuses[d.ID] = &statusState{text: shown, buttons: keyboardSignature(kb), phase: phase, at: now}
|
|
b.statusMu.Unlock()
|
|
|
|
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.
|
|
b.statusMu.Lock()
|
|
if cur := b.statuses[d.ID]; cur != nil {
|
|
cur.text = ""
|
|
cur.at = now.Add(wait)
|
|
}
|
|
b.statusMu.Unlock()
|
|
}
|
|
}
|
|
}
|
|
|
|
// finalStatus writes the last state of a delivery and forgets its
|
|
// throttling state. When the status message is gone a new one is sent, so
|
|
// the requester always learns the outcome.
|
|
func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) {
|
|
b.statusMu.Lock()
|
|
delete(b.statuses, d.ID)
|
|
b.statusMu.Unlock()
|
|
if d.StatusMessageID != 0 {
|
|
err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, nil)
|
|
if err == nil || !tg.IsMessageGone(err) {
|
|
return
|
|
}
|
|
}
|
|
_, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, nil)
|
|
}
|