Phase 2: money
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>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
3b361c17a1
commit
0d50f453a0
+28
-4
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/billing"
|
||||
"github.com/noderunners/dlbot/internal/config"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
@@ -29,6 +30,9 @@ type Deps struct {
|
||||
Store *db.Store
|
||||
Sched *sched.Scheduler
|
||||
Service *service.Service
|
||||
Billing *billing.Billing
|
||||
// Cashu redeems ecash tokens. Nil turns that part of /redeem off.
|
||||
Cashu billing.Cashu
|
||||
Storage storage.Storage
|
||||
I18n *i18n.Bundle
|
||||
Log *slog.Logger
|
||||
@@ -44,6 +48,8 @@ type Bot struct {
|
||||
store *db.Store
|
||||
sched *sched.Scheduler
|
||||
svc *service.Service
|
||||
bill *billing.Billing
|
||||
cashu billing.Cashu
|
||||
storage storage.Storage
|
||||
tr *i18n.Bundle
|
||||
log *slog.Logger
|
||||
@@ -51,10 +57,12 @@ type Bot struct {
|
||||
id int64
|
||||
username string
|
||||
|
||||
events chan sched.Event
|
||||
uploads chan struct{} // limits concurrent uploads to Telegram
|
||||
bg sync.WaitGroup
|
||||
baseCtx context.Context
|
||||
events chan sched.Event
|
||||
payEvents chan billing.Event
|
||||
uploads chan struct{} // limits concurrent uploads to Telegram
|
||||
rate *rateLimiter
|
||||
bg sync.WaitGroup
|
||||
baseCtx context.Context
|
||||
|
||||
statusMu sync.Mutex
|
||||
statuses map[string]*statusState // by delivery ID
|
||||
@@ -63,6 +71,9 @@ type Bot struct {
|
||||
// Tunables, shortened in tests.
|
||||
reconcileEvery time.Duration
|
||||
statusMinGap time.Duration
|
||||
// invoiceGrace is how long a paid purchase may lack an invoice message
|
||||
// before the payer is told in a new message.
|
||||
invoiceGrace time.Duration
|
||||
}
|
||||
|
||||
// New creates the bot and learns its own username, which is needed to
|
||||
@@ -84,6 +95,8 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
|
||||
store: d.Store,
|
||||
sched: d.Sched,
|
||||
svc: d.Service,
|
||||
bill: d.Billing,
|
||||
cashu: d.Cashu,
|
||||
storage: d.Storage,
|
||||
tr: d.I18n,
|
||||
log: d.Log,
|
||||
@@ -91,12 +104,15 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
|
||||
id: me.ID,
|
||||
username: me.Username,
|
||||
events: make(chan sched.Event, 1024),
|
||||
payEvents: make(chan billing.Event, 256),
|
||||
uploads: make(chan struct{}, 4),
|
||||
rate: newRateLimiter(),
|
||||
baseCtx: ctx,
|
||||
statuses: map[string]*statusState{},
|
||||
sending: map[string]bool{},
|
||||
reconcileEvery: 5 * time.Second,
|
||||
statusMinGap: 3 * time.Second,
|
||||
invoiceGrace: 5 * time.Second,
|
||||
}
|
||||
d.Sched.Subscribe(func(ev sched.Event) {
|
||||
select {
|
||||
@@ -105,6 +121,13 @@ func New(ctx context.Context, d Deps) (*Bot, error) {
|
||||
// The reconcile loop picks up anything dropped here.
|
||||
}
|
||||
})
|
||||
d.Billing.Subscribe(func(ev billing.Event) {
|
||||
select {
|
||||
case b.payEvents <- ev:
|
||||
default:
|
||||
// The reconcile loop picks up unfulfilled purchases.
|
||||
}
|
||||
})
|
||||
return b, nil
|
||||
}
|
||||
|
||||
@@ -116,6 +139,7 @@ func (b *Bot) Username() string { return b.username }
|
||||
func (b *Bot) SetTimings(reconcile, statusGap time.Duration) {
|
||||
b.reconcileEvery = reconcile
|
||||
b.statusMinGap = statusGap
|
||||
b.invoiceGrace = 4 * reconcile
|
||||
}
|
||||
|
||||
// Run processes updates and job events until ctx ends, then waits for
|
||||
|
||||
+20
-1
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"html"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -36,6 +37,16 @@ type linkRequest struct {
|
||||
// startLink runs the link flow in the background so a slow metadata lookup
|
||||
// never blocks other updates of the chat.
|
||||
func (b *Bot) startLink(ctx context.Context, lr linkRequest) {
|
||||
userOK := b.rate.allow("u:"+strconv.FormatInt(lr.act.user.ID, 10), b.cfg.Rate.UserPerMinute, time.Minute)
|
||||
groupOK := isPrivate(lr.chatType) ||
|
||||
b.rate.allow("g:"+strconv.FormatInt(lr.chatID, 10), b.cfg.Rate.GroupPerMinute, time.Minute)
|
||||
if !userOK || !groupOK {
|
||||
// One notice per minute is enough; more would be its own flood.
|
||||
if b.rate.allow("n:"+strconv.FormatInt(lr.chatID, 10)+":"+strconv.FormatInt(lr.act.user.ID, 10), 1, time.Minute) {
|
||||
_, _ = b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lr.act.lang, "notice.rate_limited", nil), nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
b.goBG("link", func() { b.linkFlow(ctx, lr) })
|
||||
}
|
||||
|
||||
@@ -104,7 +115,7 @@ func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) {
|
||||
ReplyMarkup: kb,
|
||||
})
|
||||
if err == nil {
|
||||
if err := b.store.SetRequestCard(ctx, req.ID, int64(msg.MessageID), true); err != nil {
|
||||
if err := b.store.SetRequestCard(context.WithoutCancel(ctx), req.ID, int64(msg.MessageID), true); err != nil {
|
||||
log.Error("save card", "err", err)
|
||||
}
|
||||
b.deleteMessage(ctx, lr.chatID, phID)
|
||||
@@ -200,6 +211,14 @@ func (b *Bot) cbDownload(ctx context.Context, q *telego.CallbackQuery, act actor
|
||||
if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil {
|
||||
b.log.Error("release request", "request_id", req.ID, "err", rerr)
|
||||
}
|
||||
var le *service.LimitError
|
||||
if errors.As(err, &le) && le.Upgradable {
|
||||
// Over the limit, but a pass or a one-off payment would cover
|
||||
// it: offer those instead of a dead end.
|
||||
b.answer(ctx, q, "", false)
|
||||
b.offerUpgrade(ctx, req.ChatID, cardID, act.lang, req, profile, le, isPrivate(req.ChatType))
|
||||
return
|
||||
}
|
||||
b.answer(ctx, q, b.startErrorText(act.lang, err), true)
|
||||
return
|
||||
}
|
||||
|
||||
+91
-11
@@ -3,6 +3,7 @@ package bot
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
@@ -53,6 +54,20 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
|
||||
b.cmdQueue(ctx, m, act)
|
||||
case "cancel":
|
||||
b.cmdCancel(ctx, m, act)
|
||||
case "buy":
|
||||
b.cmdBuy(ctx, m, act)
|
||||
case "account":
|
||||
b.cmdAccount(ctx, m, act)
|
||||
case "limits":
|
||||
b.cmdLimits(ctx, m, act)
|
||||
case "credits":
|
||||
b.cmdCredits(ctx, m, act)
|
||||
case "donate":
|
||||
b.cmdDonate(ctx, m, act)
|
||||
case "redeem":
|
||||
b.cmdRedeem(ctx, m, act, commandArgs(m))
|
||||
case "referral":
|
||||
b.cmdReferral(ctx, m, act)
|
||||
default:
|
||||
if private {
|
||||
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil)
|
||||
@@ -78,6 +93,16 @@ func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) {
|
||||
}
|
||||
}
|
||||
|
||||
// commandArgs returns the text after the command of a message.
|
||||
func commandArgs(m *telego.Message) string {
|
||||
for _, e := range m.Entities {
|
||||
if e.Type == telego.EntityTypeBotCommand && e.Offset == 0 && e.Length <= len(m.Text) {
|
||||
return strings.TrimSpace(m.Text[e.Length:])
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseCommand finds a bot command at the start of the message. forUs is
|
||||
// false when the command names a different bot (/dl@otherbot).
|
||||
func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) {
|
||||
@@ -119,18 +144,42 @@ func messageLinks(m *telego.Message) []string {
|
||||
}
|
||||
|
||||
func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
|
||||
key := "start.private"
|
||||
if !isPrivate(m.Chat.Type) {
|
||||
key = "start.group"
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.group", nil), nil)
|
||||
return
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Name": act.user.FirstName}), nil)
|
||||
// Deep links arrive as "/start <payload>".
|
||||
payload := commandArgs(m)
|
||||
switch {
|
||||
case strings.HasPrefix(payload, "buy_"):
|
||||
b.startBuyLink(ctx, m, act, strings.TrimPrefix(payload, "buy_"))
|
||||
return
|
||||
case strings.HasPrefix(payload, "skip_"):
|
||||
b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_"))
|
||||
return
|
||||
case payload == "buy":
|
||||
b.showBuy(ctx, m.Chat.ID, act)
|
||||
return
|
||||
case strings.HasPrefix(payload, "ref_"):
|
||||
// Only somebody who is new to the bot can be referred.
|
||||
if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew {
|
||||
if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil {
|
||||
b.log.Error("set referrer", "user_id", act.user.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), nil)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
|
||||
lim := b.svc.LimitsFor(ctx, act.user.ID)
|
||||
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}, false)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{
|
||||
"MaxSize": b.tr.Size(act.lang, lim.MaxSize),
|
||||
"MaxDuration": b.tr.Span(act.lang, secondsDuration(lim.MaxDuration)),
|
||||
"MaxSize": b.tr.Size(act.lang, dec.Limits.MaxSize),
|
||||
"MaxDuration": b.tr.Span(act.lang, secondsDuration(dec.Limits.MaxDuration)),
|
||||
}), nil)
|
||||
}
|
||||
|
||||
@@ -241,14 +290,29 @@ func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int6
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
note := b.release(ctx, d)
|
||||
job, err := b.store.GetJob(ctx, d.JobID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil))
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+note)
|
||||
return nil
|
||||
}
|
||||
|
||||
// release gives back what an undelivered download took and returns a line
|
||||
// to append to the status when sats were refunded.
|
||||
func (b *Bot) release(ctx context.Context, d *db.Delivery) string {
|
||||
refunded, err := b.svc.Release(context.WithoutCancel(ctx), d.ID)
|
||||
if err != nil {
|
||||
b.log.Error("release delivery", "delivery_id", d.ID, "err", err)
|
||||
return ""
|
||||
}
|
||||
if refunded <= 0 {
|
||||
return ""
|
||||
}
|
||||
return "\n" + b.tr.HTML(d.Lang, "status.refunded", i18n.Args{"Amount": b.tr.Sats(d.Lang, refunded)})
|
||||
}
|
||||
|
||||
func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
|
||||
act, err := b.actorFor(ctx, &q.From)
|
||||
if err != nil {
|
||||
@@ -265,6 +329,16 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
|
||||
b.cbDownload(ctx, q, act, id, arg)
|
||||
case cbCancelCard:
|
||||
b.cbCancelCard(ctx, q, act, id)
|
||||
case cbSkipQueue:
|
||||
b.cbSkip(ctx, q, act, id)
|
||||
case cbBuy:
|
||||
b.cbBuyProduct(ctx, q, act, id, arg)
|
||||
case cbOfferBuy:
|
||||
b.cbOffer(ctx, q, act, id, arg)
|
||||
case cbPayCheck:
|
||||
b.cbPayCheck(ctx, q, act, id)
|
||||
case cbPayCancel:
|
||||
b.cbPayCancel(ctx, q, act, id)
|
||||
case cbCancelJob:
|
||||
err := b.cancelDelivery(ctx, id, act.user.ID)
|
||||
switch {
|
||||
@@ -283,11 +357,17 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
|
||||
}
|
||||
}
|
||||
|
||||
// limitText renders a limit refusal for the user.
|
||||
// limitText renders a limit refusal for the user as plain text.
|
||||
func (b *Bot) limitText(lang string, le *service.LimitError) string {
|
||||
l := le.Decision.Limits
|
||||
count := l.ActiveJobs
|
||||
if le.Code == service.LimitDailyDownloads {
|
||||
count = l.DailyDownloads
|
||||
}
|
||||
return b.tr.T(lang, "limit."+le.Code, i18n.Args{
|
||||
"MaxSize": b.tr.Size(lang, le.Limits.MaxSize),
|
||||
"MaxDuration": b.tr.Span(lang, secondsDuration(le.Limits.MaxDuration)),
|
||||
"Count": le.Limits.ActiveJobs,
|
||||
"MaxSize": b.tr.Size(lang, l.MaxSize),
|
||||
"MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)),
|
||||
"MaxVolume": b.tr.Size(lang, l.DailyBytes),
|
||||
"Count": count,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -103,10 +103,11 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse
|
||||
case tg.IsBlocked(err):
|
||||
log.Info("requester unreachable", "err", err)
|
||||
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "blocked")
|
||||
b.release(ctx, d)
|
||||
case tg.IsFileTooBig(err):
|
||||
log.Warn("telegram refused file size", "size", job.FileSize, "err", err)
|
||||
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "too_large")
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large"))
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")+b.release(ctx, d))
|
||||
case d.Attempts+1 < maxSendAttempts:
|
||||
log.Warn("send failed, will retry", "attempt", d.Attempts+1, "err", err)
|
||||
if wait := tg.RetryAfter(err); wait > 0 && wait <= time.Minute {
|
||||
@@ -116,13 +117,16 @@ func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuse
|
||||
default:
|
||||
log.Error("send failed, giving up", "err", err)
|
||||
_, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed")
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed"))
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")+b.release(ctx, d))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil {
|
||||
log.Error("mark delivery sent", "err", err)
|
||||
}
|
||||
if err := b.svc.RecordDelivered(context.WithoutCancel(ctx), d, job.FileSize); err != nil {
|
||||
log.Error("record usage", "err", err)
|
||||
}
|
||||
log.Info("file delivered", "size", job.FileSize, "profile", job.Profile)
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil))
|
||||
return fileID
|
||||
@@ -311,7 +315,8 @@ func (b *Bot) failJob(ctx context.Context, jobID string) {
|
||||
if err != nil || !took {
|
||||
continue
|
||||
}
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode))
|
||||
// The automatic retry is spent: give back what the download cost.
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d))
|
||||
}
|
||||
b.removeStored(ctx, job)
|
||||
}
|
||||
@@ -330,7 +335,7 @@ func (b *Bot) cleanupCancelled(ctx context.Context, jobID string) {
|
||||
if err != nil || !took {
|
||||
continue
|
||||
}
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil))
|
||||
b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+b.release(ctx, d))
|
||||
}
|
||||
}
|
||||
// The worker may have uploaded before it noticed the cancel.
|
||||
|
||||
@@ -16,6 +16,11 @@ const (
|
||||
cbDownload = "dl" // dl:<request id>:<profile>
|
||||
cbCancelCard = "cx" // cx:<request id>
|
||||
cbCancelJob = "jc" // jc:<delivery id>
|
||||
cbSkipQueue = "sq" // sq:<delivery id>
|
||||
cbBuy = "by" // by:<product>[:<amount>]
|
||||
cbOfferBuy = "ob" // ob:<product>:<request id>:<profile>
|
||||
cbPayCheck = "pc" // pc:<purchase id>
|
||||
cbPayCancel = "px" // px:<purchase id>
|
||||
)
|
||||
|
||||
func cbData(parts ...string) string { return strings.Join(parts, ":") }
|
||||
@@ -88,3 +93,20 @@ func (b *Bot) cancelJobKeyboard(lang, deliveryID string) *telego.InlineKeyboardM
|
||||
button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID)),
|
||||
})
|
||||
}
|
||||
|
||||
// queuedKeyboard adds "Skip the queue" to the Cancel button of a job that
|
||||
// waits in the free lane.
|
||||
func (b *Bot) queuedKeyboard(lang, deliveryID string) *telego.InlineKeyboardMarkup {
|
||||
skip := b.tr.T(lang, "btn.with_size", i18n.Args{
|
||||
"Label": b.tr.T(lang, "btn.skip_queue", nil),
|
||||
"Size": b.tr.Sats(lang, b.cfg.Prices.SkipQueue),
|
||||
})
|
||||
return keyboard(
|
||||
[]telego.InlineKeyboardButton{button(skip, cbData(cbSkipQueue, deliveryID))},
|
||||
[]telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID))},
|
||||
)
|
||||
}
|
||||
|
||||
func urlButton(text, url string) telego.InlineKeyboardButton {
|
||||
return telego.InlineKeyboardButton{Text: text, URL: url}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
// menuCommands are the commands shown in Telegram's command menu, in
|
||||
// order. Names are lowercase ASCII in every language; only descriptions
|
||||
// are translated, under "menu.<name>".
|
||||
var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "help"}
|
||||
var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "account", "buy", "help"}
|
||||
|
||||
// RegisterCommands publishes the command menu. A failure is logged and
|
||||
// otherwise ignored: the bot works without a menu.
|
||||
|
||||
@@ -0,0 +1,860 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
qrcode "github.com/skip2/go-qrcode"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/billing"
|
||||
"github.com/noderunners/dlbot/internal/db"
|
||||
"github.com/noderunners/dlbot/internal/entitle"
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
"github.com/noderunners/dlbot/internal/media"
|
||||
"github.com/noderunners/dlbot/internal/service"
|
||||
)
|
||||
|
||||
// privateOnly answers a money command sent in a group with a pointer to
|
||||
// the private chat, and reports whether the command may continue.
|
||||
func (b *Bot) privateOnly(ctx context.Context, m *telego.Message, act actor) bool {
|
||||
if isPrivate(m.Chat.Type) {
|
||||
return true
|
||||
}
|
||||
kb := keyboard([]telego.InlineKeyboardButton{
|
||||
urlButton(b.tr.T(act.lang, "btn.open_private", nil), "https://t.me/"+b.username),
|
||||
})
|
||||
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "notice.private_only", nil), kb)
|
||||
return false
|
||||
}
|
||||
|
||||
// productTitle is the display name of a product.
|
||||
func (b *Bot) productTitle(lang, product string) string {
|
||||
return b.tr.T(lang, "product."+product, nil)
|
||||
}
|
||||
|
||||
// priced renders "Label · 700 sats" for a button.
|
||||
func (b *Bot) priced(lang, label string, sats int64) string {
|
||||
return b.tr.T(lang, "btn.with_size", i18n.Args{"Label": label, "Size": b.tr.Sats(lang, sats)})
|
||||
}
|
||||
|
||||
// passButtons are the three pass buttons. data builds the callback data
|
||||
// for a product.
|
||||
func (b *Bot) passButtons(lang string, data func(product string) string) [][]telego.InlineKeyboardButton {
|
||||
p := b.cfg.Prices
|
||||
return [][]telego.InlineKeyboardButton{
|
||||
{
|
||||
button(b.priced(lang, b.productTitle(lang, billing.ProductPassDay), p.PassDay), data(billing.ProductPassDay)),
|
||||
button(b.priced(lang, b.productTitle(lang, billing.ProductPassWeek), p.PassWeek), data(billing.ProductPassWeek)),
|
||||
},
|
||||
{
|
||||
button(b.priced(lang, b.productTitle(lang, billing.ProductPassMonth), p.PassMonth), data(billing.ProductPassMonth)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// amountButtons renders one button per amount for a product.
|
||||
func (b *Bot) amountButtons(lang, product string, amounts []int64) []telego.InlineKeyboardButton {
|
||||
var row []telego.InlineKeyboardButton
|
||||
for _, a := range amounts {
|
||||
row = append(row, button(b.tr.Sats(lang, a), cbData(cbBuy, product, strconv.FormatInt(a, 10))))
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
// --- commands ----------------------------------------------------------------
|
||||
|
||||
func (b *Bot) cmdBuy(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
b.showBuy(ctx, m.Chat.ID, act)
|
||||
}
|
||||
|
||||
func (b *Bot) showBuy(ctx context.Context, chat int64, act actor) {
|
||||
if !b.bill.Enabled() {
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil)
|
||||
return
|
||||
}
|
||||
paid := b.cfg.Limits.Paid
|
||||
rows := b.passButtons(act.lang, func(product string) string { return cbData(cbBuy, product) })
|
||||
rows = append(rows, b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks))
|
||||
text := b.tr.HTML(act.lang, "buy.intro", i18n.Args{
|
||||
"MaxSize": b.tr.Size(act.lang, min64(paid.MaxSizeMB<<20, b.cfg.MaxUploadBytes())),
|
||||
"MaxDuration": b.tr.Span(act.lang, paid.MaxDuration.D()),
|
||||
"PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload),
|
||||
})
|
||||
_, _ = b.send(ctx, chat, 0, text, keyboard(rows...))
|
||||
}
|
||||
|
||||
func min64(a, b int64) int64 {
|
||||
if b > 0 && (a == 0 || b < a) {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func (b *Bot) cmdCredits(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
text := b.tr.HTML(act.lang, "credits.text", i18n.Args{
|
||||
"Balance": b.tr.Sats(act.lang, st.Credits),
|
||||
"PerDownload": b.tr.Sats(act.lang, b.cfg.Prices.CreditPerDownload),
|
||||
})
|
||||
var kb *telego.InlineKeyboardMarkup
|
||||
if b.bill.Enabled() {
|
||||
kb = keyboard(b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks))
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, text, kb)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdDonate(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
if !b.bill.Enabled() {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil)
|
||||
return
|
||||
}
|
||||
kb := keyboard(b.amountButtons(act.lang, billing.ProductDonation, b.cfg.Prices.DonationAmounts))
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "donate.intro", nil), kb)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdAccount(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
who := service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}
|
||||
st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
dec, err := b.svc.Entitlement(ctx, who, false)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
usage, err := b.svc.Usage(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
lang := act.lang
|
||||
var sb strings.Builder
|
||||
sb.WriteString(b.tr.HTML(lang, "account.title", nil))
|
||||
sb.WriteString("\n")
|
||||
if st.PassUntil > 0 {
|
||||
sb.WriteString(b.tr.HTML(lang, "account.pass_active", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(st.PassUntil))}))
|
||||
} else {
|
||||
sb.WriteString(b.tr.HTML(lang, "account.pass_none", nil))
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(b.tr.HTML(lang, "account.balance", i18n.Args{"Balance": b.tr.Sats(lang, st.Credits)}))
|
||||
sb.WriteString("\n\n")
|
||||
sb.WriteString(b.tr.HTML(lang, "account.today", nil))
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(b.tr.HTML(lang, "account.usage_downloads", i18n.Args{
|
||||
"Used": b.tr.Number(lang, int64(usage.Downloads)), "Max": b.capNumber(lang, int64(dec.Limits.DailyDownloads)),
|
||||
}))
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(b.tr.HTML(lang, "account.usage_volume", i18n.Args{
|
||||
"Used": b.tr.Size(lang, usage.Bytes), "Max": b.capSize(lang, dec.Limits.DailyBytes),
|
||||
}))
|
||||
var kb *telego.InlineKeyboardMarkup
|
||||
if b.bill.Enabled() {
|
||||
kb = keyboard(b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })...)
|
||||
}
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), kb)
|
||||
}
|
||||
|
||||
func (b *Bot) capNumber(lang string, n int64) string {
|
||||
if n <= 0 {
|
||||
return b.tr.T(lang, "account.unlimited", nil)
|
||||
}
|
||||
return b.tr.Number(lang, n)
|
||||
}
|
||||
|
||||
func (b *Bot) capSize(lang string, n int64) string {
|
||||
if n <= 0 {
|
||||
return b.tr.T(lang, "account.unlimited", nil)
|
||||
}
|
||||
return b.tr.Size(lang, n)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdLimits(ctx context.Context, m *telego.Message, act actor) {
|
||||
who := service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}
|
||||
dec, err := b.svc.Entitlement(ctx, who, false)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
lang := act.lang
|
||||
l := dec.Limits
|
||||
text := b.tr.HTML(lang, "limits.text", i18n.Args{
|
||||
"Tier": b.tr.T(lang, "source."+string(dec.Source), nil),
|
||||
"MaxSize": b.capSize(lang, l.MaxSize),
|
||||
"MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)),
|
||||
"ActiveJobs": b.capNumber(lang, int64(l.ActiveJobs)),
|
||||
"DailyDownloads": b.capNumber(lang, int64(l.DailyDownloads)),
|
||||
"DailyVolume": b.capSize(lang, l.DailyBytes),
|
||||
})
|
||||
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, nil)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdReferral(ctx context.Context, m *telego.Message, act actor) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
n, err := b.store.CountReferrals(ctx, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
return
|
||||
}
|
||||
link := "https://t.me/" + b.username + "?start=ref_" + strconv.FormatInt(act.user.ID, 10)
|
||||
text := b.tr.HTML(act.lang, "referral.text", i18n.Args{
|
||||
"Link": link,
|
||||
"Reward": b.tr.Sats(act.lang, b.cfg.Prices.ReferralReward),
|
||||
"Count": n,
|
||||
})
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, text, nil)
|
||||
}
|
||||
|
||||
func (b *Bot) cmdRedeem(ctx context.Context, m *telego.Message, act actor, arg string) {
|
||||
if !b.privateOnly(ctx, m, act) {
|
||||
return
|
||||
}
|
||||
lang := act.lang
|
||||
arg = strings.TrimSpace(arg)
|
||||
if arg == "" {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.usage", nil), nil)
|
||||
return
|
||||
}
|
||||
if billing.IsCashuToken(arg) {
|
||||
b.redeemCashu(ctx, m.Chat.ID, act, arg)
|
||||
return
|
||||
}
|
||||
res, err := b.bill.RedeemGift(ctx, act.user.ID, arg)
|
||||
switch {
|
||||
case errors.Is(err, billing.ErrGiftInvalid):
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.invalid", nil), nil)
|
||||
case errors.Is(err, billing.ErrGiftUsed):
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.used", nil), nil)
|
||||
case err != nil:
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
case res.Kind == billing.GiftCredits:
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.credits", i18n.Args{"Amount": b.tr.Sats(lang, res.Sats)}), nil)
|
||||
default:
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "redeem.pass", i18n.Args{
|
||||
"Until": b.tr.DateTime(lang, time.UnixMilli(res.PassUntil)),
|
||||
}), nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) redeemCashu(ctx context.Context, chat int64, act actor, token string) {
|
||||
lang := act.lang
|
||||
if b.cashu == nil {
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.cashu_off", nil), nil)
|
||||
return
|
||||
}
|
||||
sats, err := b.cashu.Redeem(ctx, token)
|
||||
switch {
|
||||
case errors.Is(err, billing.ErrCashuMint):
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.cashu_mint", nil), nil)
|
||||
return
|
||||
case errors.Is(err, billing.ErrCashuSpent):
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.used", nil), nil)
|
||||
return
|
||||
case err != nil:
|
||||
b.log.Warn("cashu redeem failed", "user_id", act.user.ID, "err", err)
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.invalid", nil), nil)
|
||||
return
|
||||
}
|
||||
w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, chat, act, err)
|
||||
return
|
||||
}
|
||||
// The mint already paid us, so this credit must not be lost: the dedupe
|
||||
// key is derived from the token and survives a retry.
|
||||
if _, err := b.bill.Credit(ctx, w.ID, sats, "cashu", "", "cashu:"+tokenDigest(token), act.user.ID); err != nil {
|
||||
b.internalError(ctx, chat, act, err)
|
||||
return
|
||||
}
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "redeem.credits", i18n.Args{"Amount": b.tr.Sats(lang, sats)}), nil)
|
||||
}
|
||||
|
||||
func (b *Bot) internalError(ctx context.Context, chat int64, act actor, err error) {
|
||||
b.log.Error("handler failed", "user_id", act.user.ID, "err", err)
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "error.internal", nil), nil)
|
||||
}
|
||||
|
||||
// --- buying ----------------------------------------------------------------
|
||||
|
||||
// purchaseContext ties a purchase to something that starts once it is paid.
|
||||
type purchaseContext struct {
|
||||
requestID string
|
||||
profile string
|
||||
deliveryID string
|
||||
}
|
||||
|
||||
// startPurchase creates the invoice and shows it in the private chat.
|
||||
func (b *Bot) startPurchase(ctx context.Context, chat int64, act actor, product string, amount int64, pc purchaseContext) {
|
||||
lang := act.lang
|
||||
// Callback data comes from the client. Check the product before it is
|
||||
// used for anything, including a catalog lookup.
|
||||
if !billing.ValidProduct(product) {
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil)
|
||||
return
|
||||
}
|
||||
w, err := b.bill.Wallet(ctx, db.OwnerUser, act.user.ID)
|
||||
if err != nil {
|
||||
b.internalError(ctx, chat, act, err)
|
||||
return
|
||||
}
|
||||
p, err := b.bill.CreatePurchase(ctx, billing.NewPurchase{
|
||||
UserID: act.user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang,
|
||||
Memo: b.tr.T(lang, "invoice.memo", i18n.Args{"Title": b.productTitle(lang, product)}),
|
||||
RequestID: pc.requestID, Profile: pc.profile, DeliveryID: pc.deliveryID,
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, billing.ErrDisabled):
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.unavailable", nil), nil)
|
||||
return
|
||||
case errors.Is(err, billing.ErrLightningDown):
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.backend_down", nil), nil)
|
||||
return
|
||||
case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct):
|
||||
_, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil)
|
||||
return
|
||||
case err != nil:
|
||||
b.internalError(ctx, chat, act, err)
|
||||
return
|
||||
}
|
||||
b.sendInvoice(ctx, chat, p)
|
||||
}
|
||||
|
||||
// invoiceText is the caption of the invoice message.
|
||||
func (b *Bot) invoiceText(p *db.Purchase) string {
|
||||
lang := p.Lang
|
||||
minutes := b.cfg.LNbits.InvoiceExpiry.D()
|
||||
return b.tr.HTML(lang, "invoice.caption", i18n.Args{
|
||||
"Title": b.productTitle(lang, p.Product),
|
||||
"Amount": b.tr.Sats(lang, p.AmountSats),
|
||||
"Invoice": p.Bolt11,
|
||||
"Valid": b.tr.Span(lang, minutes),
|
||||
})
|
||||
}
|
||||
|
||||
func (b *Bot) invoiceKeyboard(p *db.Purchase) *telego.InlineKeyboardMarkup {
|
||||
lang := p.Lang
|
||||
var rows [][]telego.InlineKeyboardButton
|
||||
// Telegram only accepts http and https in URL buttons, so "open in
|
||||
// wallet" goes through a small page of ours that forwards to the
|
||||
// lightning: link.
|
||||
if b.cfg.PublicURL != "" {
|
||||
rows = append(rows, []telego.InlineKeyboardButton{
|
||||
urlButton(b.tr.T(lang, "btn.open_wallet", nil), b.cfg.PublicURL+"/pay/"+p.ID),
|
||||
})
|
||||
}
|
||||
rows = append(rows, []telego.InlineKeyboardButton{
|
||||
button(b.tr.T(lang, "btn.check_payment", nil), cbData(cbPayCheck, p.ID)),
|
||||
button(b.tr.T(lang, "btn.cancel", nil), cbData(cbPayCancel, p.ID)),
|
||||
})
|
||||
return keyboard(rows...)
|
||||
}
|
||||
|
||||
// sendInvoice shows the invoice: a QR code with the BOLT11 string in the
|
||||
// caption, where a tap copies it. Without a QR (it should not fail) the
|
||||
// same content goes out as text.
|
||||
func (b *Bot) sendInvoice(ctx context.Context, chat int64, p *db.Purchase) {
|
||||
text := b.invoiceText(p)
|
||||
kb := b.invoiceKeyboard(p)
|
||||
// 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 {
|
||||
msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{
|
||||
ChatID: chatID(chat),
|
||||
Photo: telego.InputFile{File: namedReader{Reader: strings.NewReader(string(png)), name: "invoice.png"}},
|
||||
Caption: clip(text, 1024),
|
||||
ParseMode: telego.ModeHTML,
|
||||
ReplyMarkup: kb,
|
||||
})
|
||||
if err == nil {
|
||||
b.rememberInvoice(ctx, p, chat, int64(msg.MessageID), true)
|
||||
return
|
||||
}
|
||||
b.log.Warn("invoice photo failed, sending text", "purchase_id", p.ID, "err", err)
|
||||
}
|
||||
msg, err := b.send(ctx, chat, 0, text, kb)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
b.rememberInvoice(ctx, p, chat, int64(msg.MessageID), false)
|
||||
}
|
||||
|
||||
// rememberInvoice saves which message shows an invoice. The invoice can be
|
||||
// settled, expired or cancelled in the moment between Telegram showing it
|
||||
// and this save, and the event for that had no message to edit. So after
|
||||
// saving, the message is brought in line with the purchase once more.
|
||||
func (b *Bot) rememberInvoice(ctx context.Context, p *db.Purchase, chat, messageID int64, isPhoto bool) {
|
||||
// Saved even during shutdown, or a restart could never edit it.
|
||||
if err := b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, chat, messageID, isPhoto); err != nil {
|
||||
b.log.Error("save invoice message", "purchase_id", p.ID, "err", err)
|
||||
return
|
||||
}
|
||||
cur, err := b.store.GetPurchase(ctx, p.ID)
|
||||
if err != nil || cur.Status == db.PurchasePending {
|
||||
return
|
||||
}
|
||||
b.showPurchaseState(ctx, cur)
|
||||
}
|
||||
|
||||
// showPurchaseState makes the invoice message reflect a closed purchase.
|
||||
func (b *Bot) showPurchaseState(ctx context.Context, p *db.Purchase) {
|
||||
if p.MessageID == 0 {
|
||||
return // not shown yet; rememberInvoice catches up
|
||||
}
|
||||
lang := p.Lang
|
||||
switch p.Status {
|
||||
case db.PurchasePaid:
|
||||
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.paidText(ctx, p), 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cbBuyProduct handles the product buttons of /buy, /credits and /donate.
|
||||
func (b *Bot) cbBuyProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, amountArg string) {
|
||||
b.answer(ctx, q, "", false)
|
||||
amount, _ := strconv.ParseInt(amountArg, 10, 64)
|
||||
b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{})
|
||||
}
|
||||
|
||||
// cbOffer handles the buttons of an over-limit offer: buy something and
|
||||
// then start the download it was offered for.
|
||||
func (b *Bot) cbOffer(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) {
|
||||
requestID, profileArg, _ := strings.Cut(rest, ":")
|
||||
req, err := b.store.GetRequest(ctx, requestID)
|
||||
if err != nil || req.UserID != act.user.ID {
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
||||
return
|
||||
}
|
||||
profile, perr := media.Parse(profileArg)
|
||||
info, ierr := service.ParseCardInfo(req.Info)
|
||||
if perr != nil || ierr != nil || req.Status != db.RequestReady {
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
||||
return
|
||||
}
|
||||
b.answer(ctx, q, "", false)
|
||||
var amount int64
|
||||
if product == billing.ProductOneOff {
|
||||
amount = b.cfg.Prices.OneOffPrice(info.Sizes[string(profile)])
|
||||
}
|
||||
b.startPurchase(ctx, act.user.ID, act, product, amount, purchaseContext{requestID: req.ID, profile: string(profile)})
|
||||
}
|
||||
|
||||
func (b *Bot) cbPayCheck(ctx context.Context, q *telego.CallbackQuery, act actor, purchaseID string) {
|
||||
p, err := b.bill.Check(ctx, purchaseID, act.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, billing.ErrLightningDown):
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "buy.backend_down_short", nil), true)
|
||||
case err != nil:
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
||||
case p.Status == db.PurchasePaid:
|
||||
// The paid event edits the message; this only closes the spinner.
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.paid", nil), false)
|
||||
case p.Status == db.PurchasePending:
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.not_paid_yet", nil), false)
|
||||
default:
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.invoice_closed", nil), false)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) cbPayCancel(ctx context.Context, q *telego.CallbackQuery, act actor, purchaseID string) {
|
||||
if _, err := b.bill.Cancel(ctx, purchaseID, act.user.ID); err != nil {
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
||||
return
|
||||
}
|
||||
b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false)
|
||||
}
|
||||
|
||||
// --- payment events --------------------------------------------------------
|
||||
|
||||
func (b *Bot) handlePayEvent(ctx context.Context, ev billing.Event) {
|
||||
// The event carries the purchase as it was inside the transaction.
|
||||
// Read it again: the invoice message may have been saved since.
|
||||
p, err := b.store.GetPurchase(ctx, ev.Purchase.ID)
|
||||
if err != nil {
|
||||
b.log.Error("load purchase for event", "purchase_id", ev.Purchase.ID, "err", err)
|
||||
return
|
||||
}
|
||||
b.showPurchaseState(ctx, p)
|
||||
if ev.Type == billing.EventPaid {
|
||||
if p.MessageID == 0 {
|
||||
b.goBG("confirm-payment", func() { b.confirmWithoutInvoice(ctx, p.ID) })
|
||||
}
|
||||
b.fulfil(ctx, p)
|
||||
}
|
||||
}
|
||||
|
||||
// confirmWithoutInvoice tells a payer that their payment arrived when the
|
||||
// invoice message is unknown. Normally the message is saved a moment after
|
||||
// it is sent and rememberInvoice updates it. If the core stopped exactly in
|
||||
// between, nothing would ever confirm the payment, so after a short wait a
|
||||
// new message does.
|
||||
func (b *Bot) confirmWithoutInvoice(ctx context.Context, purchaseID string) {
|
||||
sleepCtx(ctx, b.invoiceGrace)
|
||||
p, err := b.store.GetPurchase(ctx, purchaseID)
|
||||
if err != nil || p.MessageID != 0 || p.Status != db.PurchasePaid {
|
||||
return
|
||||
}
|
||||
msg, err := b.send(ctx, p.UserID, 0, b.paidText(ctx, p), nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err := b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, p.UserID, int64(msg.MessageID), false); err != nil {
|
||||
b.log.Error("save payment confirmation", "purchase_id", p.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// paidText is what the invoice message becomes once it is settled.
|
||||
func (b *Bot) paidText(ctx context.Context, p *db.Purchase) string {
|
||||
lang := p.Lang
|
||||
text := b.tr.HTML(lang, "invoice.paid", i18n.Args{
|
||||
"Title": b.productTitle(lang, p.Product),
|
||||
"Amount": b.tr.Sats(lang, p.AmountSats),
|
||||
})
|
||||
w, err := b.store.GetWallet(ctx, p.WalletID)
|
||||
if err != nil {
|
||||
return text
|
||||
}
|
||||
switch p.Product {
|
||||
case billing.ProductCredits:
|
||||
text += "\n" + b.tr.HTML(lang, "invoice.balance", i18n.Args{"Balance": b.tr.Sats(lang, w.Balance)})
|
||||
case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth:
|
||||
if until, err := b.store.PassUntil(ctx, w.ID, db.NowMilli()); err == nil && until > 0 {
|
||||
text += "\n" + b.tr.HTML(lang, "invoice.pass_until", i18n.Args{"Until": b.tr.DateTime(lang, time.UnixMilli(until))})
|
||||
}
|
||||
case billing.ProductDonation:
|
||||
text += "\n" + b.tr.HTML(lang, "invoice.thanks", nil)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// fulfilPending runs the follow-up of paid purchases that never got one,
|
||||
// for example because the core stopped right after the payment arrived.
|
||||
func (b *Bot) fulfilPending(ctx context.Context) {
|
||||
list, err := b.store.UnfulfilledPaidPurchases(ctx, 100)
|
||||
if err != nil {
|
||||
b.log.Error("list unfulfilled purchases", "err", err)
|
||||
return
|
||||
}
|
||||
for _, p := range list {
|
||||
b.fulfil(ctx, p)
|
||||
}
|
||||
}
|
||||
|
||||
// fulfil starts what a paid purchase was for: the download behind an
|
||||
// over-limit offer, or the promotion of a waiting job. Every step is
|
||||
// idempotent, and the purchase is marked fulfilled only at the end, so an
|
||||
// interruption repeats the follow-up instead of losing it. When the thing
|
||||
// that was paid for is no longer possible, the payment becomes credits.
|
||||
func (b *Bot) fulfil(ctx context.Context, p *db.Purchase) {
|
||||
cur, err := b.store.GetPurchase(ctx, p.ID)
|
||||
if err != nil || cur.Fulfilled || cur.Status != db.PurchasePaid {
|
||||
return
|
||||
}
|
||||
p = cur
|
||||
done := true
|
||||
switch {
|
||||
case p.DeliveryID != "":
|
||||
done = b.fulfilSkip(ctx, p)
|
||||
case p.RequestID != "":
|
||||
done = b.fulfilDownload(ctx, p)
|
||||
}
|
||||
if !done {
|
||||
return // a transient error; the reconcile loop tries again
|
||||
}
|
||||
if _, err := b.store.MarkPurchaseFulfilled(ctx, p.ID); err != nil {
|
||||
b.log.Error("mark purchase fulfilled", "purchase_id", p.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) fulfilSkip(ctx context.Context, p *db.Purchase) bool {
|
||||
d, err := b.store.GetDelivery(ctx, p.DeliveryID)
|
||||
if err == nil {
|
||||
job, jerr := b.store.GetJob(ctx, d.JobID)
|
||||
if jerr == nil {
|
||||
if job.Lane == db.LanePaid && job.Active() {
|
||||
return true // already promoted by an earlier attempt
|
||||
}
|
||||
promoted, perr := b.sched.Promote(ctx, job.ID)
|
||||
if perr != nil {
|
||||
b.log.Error("promote job", "job_id", job.ID, "err", perr)
|
||||
return false
|
||||
}
|
||||
if promoted {
|
||||
b.refreshStatus(ctx, job.ID)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
// The job started or finished before the payment arrived.
|
||||
return b.convertToCredits(ctx, p, "pay.too_late_skip")
|
||||
}
|
||||
|
||||
func (b *Bot) fulfilDownload(ctx context.Context, p *db.Purchase) bool {
|
||||
oneOff := p.Product == billing.ProductOneOff
|
||||
fallback := func() bool {
|
||||
if oneOff {
|
||||
return b.convertToCredits(ctx, p, "pay.too_late_file")
|
||||
}
|
||||
return true // a pass or credits were granted, nothing is owed
|
||||
}
|
||||
req, err := b.store.GetRequest(ctx, p.RequestID)
|
||||
if err != nil {
|
||||
return fallback()
|
||||
}
|
||||
// An earlier attempt may have started the job already.
|
||||
if n, err := b.store.CountDeliveriesForRequest(ctx, req.ID); err != nil {
|
||||
return false
|
||||
} else if n > 0 {
|
||||
return true
|
||||
}
|
||||
profile, perr := media.Parse(p.Profile)
|
||||
info, ierr := service.ParseCardInfo(req.Info)
|
||||
if perr != nil || ierr != nil {
|
||||
return fallback()
|
||||
}
|
||||
took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !took {
|
||||
return fallback()
|
||||
}
|
||||
sp := service.StartParams{
|
||||
Request: req, Info: info, Profile: profile,
|
||||
StatusMessageID: req.CardMessageID, StatusIsPhoto: req.CardIsPhoto,
|
||||
ReplyToMessageID: req.SourceMessageID,
|
||||
}
|
||||
if oneOff {
|
||||
sp.OneOff = p
|
||||
}
|
||||
job, _, err := b.svc.Start(ctx, sp)
|
||||
if err != nil {
|
||||
if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil {
|
||||
b.log.Error("release request", "request_id", req.ID, "err", rerr)
|
||||
}
|
||||
var le *service.LimitError
|
||||
if !errors.As(err, &le) {
|
||||
b.log.Error("start paid download", "purchase_id", p.ID, "err", err)
|
||||
return false
|
||||
}
|
||||
// Even paid limits refuse it (for example one job too many).
|
||||
_, _ = b.send(ctx, p.ChatID, 0, b.tr.HTML(p.Lang, "pay.not_started", i18n.Args{"Reason": b.limitText(p.Lang, le)}), nil)
|
||||
return fallback()
|
||||
}
|
||||
b.refreshStatus(ctx, job.ID)
|
||||
return true
|
||||
}
|
||||
|
||||
// convertToCredits turns a payment whose purpose is gone into credits and
|
||||
// tells the payer.
|
||||
func (b *Bot) convertToCredits(ctx context.Context, p *db.Purchase, key string) bool {
|
||||
if _, err := b.bill.ConvertToCredits(ctx, p); err != nil {
|
||||
b.log.Error("convert purchase to credits", "purchase_id", p.ID, "err", err)
|
||||
return false
|
||||
}
|
||||
_, _ = b.send(ctx, p.ChatID, 0, b.tr.HTML(p.Lang, key, i18n.Args{"Amount": b.tr.Sats(p.Lang, p.AmountSats)}), nil)
|
||||
return true
|
||||
}
|
||||
|
||||
// --- over-limit offer --------------------------------------------------------
|
||||
|
||||
// encodeProfile makes a profile safe for a /start parameter, which only
|
||||
// allows letters, digits, "_" and "-".
|
||||
func encodeProfile(p string) string { return strings.ReplaceAll(p, ":", "--") }
|
||||
|
||||
func decodeProfile(s string) string { return strings.Replace(s, "--", ":", 1) }
|
||||
|
||||
// offerUpgrade shows what the requester can buy to get a refused download.
|
||||
// In a private chat the buttons create invoices. In a group they are deep
|
||||
// links into the private chat, because invoices are personal.
|
||||
func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string, req *db.Request, profile media.Profile, le *service.LimitError, private bool) {
|
||||
text := b.limitText(lang, le) + "\n\n" + b.tr.HTML(lang, "over.options", nil)
|
||||
var rows [][]telego.InlineKeyboardButton
|
||||
if private {
|
||||
rows = b.passButtons(lang, func(product string) string {
|
||||
return cbData(cbOfferBuy, product, req.ID, string(profile))
|
||||
})
|
||||
if le.Code == service.LimitTooLarge || le.Code == service.LimitTooLong {
|
||||
price := b.cfg.Prices.OneOffPrice(le.Size)
|
||||
rows = append(rows, []telego.InlineKeyboardButton{
|
||||
button(b.priced(lang, b.tr.T(lang, "btn.this_file", nil), price),
|
||||
cbData(cbOfferBuy, billing.ProductOneOff, req.ID, string(profile))),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
link := "https://t.me/" + b.username + "?start=buy_" + req.ID + "_" + encodeProfile(string(profile))
|
||||
rows = append(rows, []telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.buy_for_me", nil), link)})
|
||||
}
|
||||
_, _ = b.send(ctx, chat, replyTo, text, keyboard(rows...))
|
||||
}
|
||||
|
||||
// startBuyLink handles /start buy_<request>_<profile>, the deep link from
|
||||
// a group offer. It shows the same offer in private, or starts the
|
||||
// download right away when the requester's limits now allow it.
|
||||
func (b *Bot) startBuyLink(ctx context.Context, m *telego.Message, act actor, payload string) {
|
||||
requestID, profileArg, _ := strings.Cut(payload, "_")
|
||||
req, err := b.store.GetRequest(ctx, requestID)
|
||||
profile, perr := media.Parse(decodeProfile(profileArg))
|
||||
if err != nil || perr != nil || req.UserID != act.user.ID || req.Status != db.RequestReady {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil)
|
||||
return
|
||||
}
|
||||
info, err := service.ParseCardInfo(req.Info)
|
||||
if err != nil {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil)
|
||||
return
|
||||
}
|
||||
who := service.Who{UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType}
|
||||
err = b.svc.Preview(ctx, who, info, profile)
|
||||
var le *service.LimitError
|
||||
switch {
|
||||
case err == nil:
|
||||
// They bought something in the meantime: just start it.
|
||||
if b.startFromRequest(ctx, req, info, profile, nil) == nil {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "over.started", nil), nil)
|
||||
}
|
||||
case errors.As(err, &le) && le.Upgradable:
|
||||
b.offerUpgrade(ctx, m.Chat.ID, 0, act.lang, req, profile, le, true)
|
||||
case errors.As(err, &le):
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.limitText(act.lang, le), nil)
|
||||
default:
|
||||
b.internalError(ctx, m.Chat.ID, act, err)
|
||||
}
|
||||
}
|
||||
|
||||
// startFromRequest takes a ready request and starts its download, using
|
||||
// the card as the status message.
|
||||
func (b *Bot) startFromRequest(ctx context.Context, req *db.Request, info *service.CardInfo, profile media.Profile, oneOff *db.Purchase) error {
|
||||
took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !took {
|
||||
return errors.New("bot: request is no longer ready")
|
||||
}
|
||||
job, _, err := b.svc.Start(ctx, service.StartParams{
|
||||
Request: req, Info: info, Profile: profile,
|
||||
StatusMessageID: req.CardMessageID, StatusIsPhoto: req.CardIsPhoto,
|
||||
ReplyToMessageID: req.SourceMessageID, OneOff: oneOff,
|
||||
})
|
||||
if err != nil {
|
||||
if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil {
|
||||
b.log.Error("release request", "request_id", req.ID, "err", rerr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
b.refreshStatus(ctx, job.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- skip the queue --------------------------------------------------------
|
||||
|
||||
// cbSkip handles "Skip the queue" on a waiting job. Credits pay at once.
|
||||
// Without enough credits an invoice is created, in the private chat.
|
||||
func (b *Bot) cbSkip(ctx context.Context, q *telego.CallbackQuery, act actor, deliveryID string) {
|
||||
lang := act.lang
|
||||
d, err := b.store.GetDelivery(ctx, deliveryID)
|
||||
if err != nil {
|
||||
b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false)
|
||||
return
|
||||
}
|
||||
if d.UserID != act.user.ID {
|
||||
b.answer(ctx, q, b.tr.T(lang, "notice.not_yours", nil), false)
|
||||
return
|
||||
}
|
||||
job, err := b.store.GetJob(ctx, d.JobID)
|
||||
if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree {
|
||||
b.answer(ctx, q, b.tr.T(lang, "notice.skip_too_late", nil), false)
|
||||
return
|
||||
}
|
||||
price := b.cfg.Prices.SkipQueue
|
||||
if b.skipWithCredits(ctx, act, d, job, price) {
|
||||
b.answer(ctx, q, b.tr.T(lang, "notice.skipped", nil), false)
|
||||
b.refreshStatus(ctx, job.ID)
|
||||
return
|
||||
}
|
||||
if q.Message != nil && !isPrivate(q.Message.GetChat().Type) {
|
||||
// Send the requester to the private chat, where the invoice goes.
|
||||
err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{
|
||||
CallbackQueryID: q.ID, URL: "https://t.me/" + b.username + "?start=skip_" + d.ID,
|
||||
})
|
||||
if err != nil {
|
||||
b.answer(ctx, q, b.tr.T(lang, "notice.skip_private", nil), true)
|
||||
}
|
||||
return
|
||||
}
|
||||
b.answer(ctx, q, "", false)
|
||||
b.startPurchase(ctx, act.user.ID, act, billing.ProductSkipQueue, 0, purchaseContext{deliveryID: d.ID})
|
||||
}
|
||||
|
||||
// skipWithCredits pays for the promotion from the requester's balance. It
|
||||
// reports false when the balance does not cover it.
|
||||
func (b *Bot) skipWithCredits(ctx context.Context, act actor, d *db.Delivery, job *db.Job, price int64) bool {
|
||||
st, err := b.bill.State(ctx, db.OwnerUser, act.user.ID)
|
||||
if err != nil || st.ID == "" || st.Credits < price {
|
||||
return false
|
||||
}
|
||||
applied, err := b.bill.Debit(ctx, st.ID, price, "skip_queue", d.ID, "skip:"+d.ID, act.user.ID)
|
||||
if err != nil || !applied {
|
||||
return false
|
||||
}
|
||||
promoted, err := b.sched.Promote(ctx, job.ID)
|
||||
if err != nil || !promoted {
|
||||
// The job got a worker in the meantime: give the sats back.
|
||||
if _, rerr := b.bill.Refund(ctx, st.ID, price, "skip_queue_refund", d.ID, "skip-refund:"+d.ID, 0); rerr != nil {
|
||||
b.log.Error("refund skip", "delivery_id", d.ID, "err", rerr)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// startSkipLink handles /start skip_<delivery>, the deep link from a group.
|
||||
func (b *Bot) startSkipLink(ctx context.Context, m *telego.Message, act actor, deliveryID string) {
|
||||
d, err := b.store.GetDelivery(ctx, deliveryID)
|
||||
if err != nil || d.UserID != act.user.ID {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "notice.expired", nil), nil)
|
||||
return
|
||||
}
|
||||
job, err := b.store.GetJob(ctx, d.JobID)
|
||||
if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree {
|
||||
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "pay.skip_not_needed", nil), nil)
|
||||
return
|
||||
}
|
||||
b.startPurchase(ctx, m.Chat.ID, act, billing.ProductSkipQueue, 0, purchaseContext{deliveryID: d.ID})
|
||||
}
|
||||
|
||||
// sourceLabel names what paid for a download, for status lines.
|
||||
func (b *Bot) sourceLabel(lang string, src entitle.Source) string {
|
||||
return b.tr.T(lang, "source."+string(src), nil)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// rateLimiter is a sliding window counter per key. It lives in memory: a
|
||||
// restart forgets it, which is fine for a limit measured in a minute.
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newRateLimiter() *rateLimiter {
|
||||
return &rateLimiter{hits: map[string][]time.Time{}, now: time.Now}
|
||||
}
|
||||
|
||||
// allow records a hit for key and reports whether it stays within limit
|
||||
// hits per window. A limit of 0 or less allows everything.
|
||||
func (r *rateLimiter) allow(key string, limit int, window time.Duration) bool {
|
||||
if limit <= 0 {
|
||||
return true
|
||||
}
|
||||
now := r.now()
|
||||
cut := now.Add(-window)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
kept := r.hits[key][:0]
|
||||
for _, t := range r.hits[key] {
|
||||
if t.After(cut) {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) >= limit {
|
||||
r.hits[key] = kept
|
||||
return false
|
||||
}
|
||||
r.hits[key] = append(kept, now)
|
||||
// Keep the map from growing without bound.
|
||||
if len(r.hits) > 50_000 {
|
||||
for k, v := range r.hits {
|
||||
if len(v) == 0 || !v[len(v)-1].After(cut) {
|
||||
delete(r.hits, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// tokenDigest returns a stable fingerprint of a bearer token, so the token
|
||||
// itself is never stored or logged.
|
||||
func tokenDigest(token string) string {
|
||||
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
|
||||
return hex.EncodeToString(sum[:16])
|
||||
}
|
||||
+39
-6
@@ -2,6 +2,7 @@ package bot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mymmrac/telego"
|
||||
@@ -16,9 +17,27 @@ import (
|
||||
// statusState remembers what a status message shows, so edits that would
|
||||
// change nothing or come too fast are skipped.
|
||||
type statusState struct {
|
||||
text string
|
||||
phase string
|
||||
at time.Time
|
||||
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
|
||||
@@ -33,6 +52,8 @@ func (b *Bot) eventLoop(ctx context.Context) {
|
||||
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) })
|
||||
}
|
||||
@@ -84,6 +105,10 @@ func (b *Bot) reconcile(ctx context.Context) {
|
||||
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 {
|
||||
@@ -128,6 +153,10 @@ func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (te
|
||||
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)
|
||||
@@ -135,7 +164,7 @@ func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (te
|
||||
return head + b.tr.HTML(lang, "status.queued", i18n.Args{
|
||||
"Position": pos.Ahead + 1,
|
||||
"Wait": b.tr.Span(lang, pos.Wait),
|
||||
}), cancel, "queued"
|
||||
}), kb, "queued"
|
||||
case db.JobRunning:
|
||||
switch job.Stage {
|
||||
case ytdlp.StageProcessing:
|
||||
@@ -185,15 +214,19 @@ func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *te
|
||||
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 {
|
||||
if st.text == text || (!force && st.phase == phase && now.Sub(st.at) < b.statusMinGap) {
|
||||
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: text, phase: phase, at: now}
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user