Files
Media-download-telegram-bot/internal/bot/money.go
T
MichilisandClaude Fable 5.2 0d50f453a0 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>
2026-11-18 08:09:35 +00:00

861 lines
31 KiB
Go

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)
}