Files
MichilisandClaude Opus 5.5 d64db03f21 Phase 5: Telegram affiliate program
- docs/AFFILIATE.md: the owner's setup in Telegram (profile editor or
  BotFather's Mini App), commission and duration rules (raise only, end
  with commission 0, about 24 hours), who counts as referred, the link
  formats, and the no-double-rewards rule. Checked against Telegram's
  current pages.
- Affiliate purchases go through Stars invoices inside the Mini App
  (createInvoiceLink and WebApp.openInvoice, from Phase 4).
- /start accepts any payload; only our own rf_ (and old ref_) links set
  an inviter. A test sends payloads of every shape, Telegram's affiliate
  prefix included.
- Mini App Me page: an Earn section explaining both programs, with how
  to join Telegram's from the bot's profile, behind AFFILIATE_ENABLED.
  No affiliate numbers are computed or shown.
- /referral notes that Stars purchases earn through Telegram's program.
- The optional MTProto CLI is left out, with the reason in the docs.
- The Mini App browser test checks the Earn section in en, es and nl.

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

1070 lines
39 KiB
Go

package bot
import (
"bytes"
"context"
"errors"
"net/url"
"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.Selling() {
_, _ = b.send(ctx, chat, 0, b.tr.HTML(act.lang, "buy.unavailable", nil), nil)
return
}
text, kb := b.buyView(act.lang)
_, _ = b.send(ctx, chat, 0, text, kb)
}
// buyView is the buy screen: Lightning prices first, and a button to the
// Stars prices when Stars are on. Without Lightning it is the Stars prices.
func (b *Bot) buyView(lang string) (string, *telego.InlineKeyboardMarkup) {
paid := b.cfg.Limits.Paid
text := b.tr.HTML(lang, "buy.intro", i18n.Args{
"MaxSize": b.tr.Size(lang, min64(paid.MaxSizeMB<<20, b.cfg.MaxUploadBytes())),
"MaxDuration": b.tr.Span(lang, paid.MaxDuration.D()),
"PerDownload": b.tr.Sats(lang, b.cfg.Prices.CreditPerDownload),
})
if !b.bill.Enabled() {
stars, kb := b.starsMenu(lang)
return text + "\n\n" + stars, kb
}
rows := b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })
rows = append(rows, b.amountButtons(lang, billing.ProductCredits, b.cfg.Prices.CreditPacks), b.starsMenuButton(lang))
return 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.Selling() {
var packs []telego.InlineKeyboardButton
if b.bill.Enabled() {
packs = b.amountButtons(act.lang, billing.ProductCredits, b.cfg.Prices.CreditPacks)
}
kb = keyboard(packs, b.starsMenuButton(act.lang))
}
_, _ = 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.Selling() {
var rows [][]telego.InlineKeyboardButton
if b.bill.Enabled() {
rows = b.passButtons(lang, func(product string) string { return cbData(cbBuy, product) })
}
kb = keyboard(append(rows, b.starsMenuButton(lang))...)
}
_, _ = 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
}
text, kb, err := b.referralView(ctx, act, false)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, 0, text, kb)
}
// referralPrefix starts the /start payload of a referral link:
// rf_<code>. Old links carry ref_<Telegram user ID>; they keep working but
// are never shown again.
const (
referralPrefix = "rf_"
legacyReferralPrefix = "ref_"
)
// ReferralLink is a user's invite link. The bot's username comes from
// getMe, the code is random.
func (b *Bot) ReferralLink(ctx context.Context, userID int64) (string, error) {
code, err := b.store.RefCode(ctx, userID)
if err != nil {
return "", err
}
return "https://t.me/" + b.username + "?start=" + referralPrefix + code, nil
}
// ReferralStats sums up a user's referrals.
func (b *Bot) ReferralStats(ctx context.Context, userID int64) (db.ReferralStats, error) {
return b.store.ReferralStatsFor(ctx, userID)
}
// ReferralQR is a user's invite link as a QR code PNG.
func (b *Bot) ReferralQR(ctx context.Context, userID int64) ([]byte, error) {
link, err := b.ReferralLink(ctx, userID)
if err != nil {
return nil, err
}
return qrcode.Encode(link, qrcode.Medium, 512)
}
// shareURL opens Telegram's share sheet with a link and a line of text.
func shareURL(link, text string) string {
return "https://t.me/share/url?url=" + url.QueryEscape(link) + "&text=" + url.QueryEscape(text)
}
// referralView explains the referral program with the user's own link,
// stats and buttons to share it. back adds a button to the personal
// settings.
func (b *Bot) referralView(ctx context.Context, act actor, back bool) (string, *telego.InlineKeyboardMarkup, error) {
lang := act.lang
link, err := b.ReferralLink(ctx, act.user.ID)
if err != nil {
return "", nil, err
}
st, err := b.store.ReferralStatsFor(ctx, act.user.ID)
if err != nil {
return "", nil, err
}
text := b.tr.HTML(lang, "referral.text", i18n.Args{
"Link": link,
"Reward": b.tr.Sats(lang, b.cfg.Prices.ReferralReward),
"Invited": b.tr.Number(lang, int64(st.Invited)),
"Converted": b.tr.Number(lang, int64(st.Converted)),
"Earned": b.tr.Sats(lang, st.Earned),
"Pending": b.tr.Sats(lang, st.Pending),
})
if c := b.cfg.ReferralDailyCap; c > 0 {
text += "\n\n" + b.tr.HTML(lang, "referral.cap", i18n.Args{"Cap": b.tr.Sats(lang, c)})
}
if b.cfg.AffiliateEnabled {
// Stars purchases are rewarded by Telegram's affiliate program,
// never by ours: one purchase, one reward.
text += "\n\n" + b.tr.HTML(lang, "referral.affiliate_note", i18n.Args{"Bot": b.username})
}
rows := [][]telego.InlineKeyboardButton{
{
urlButton(b.tr.T(lang, "btn.share", nil), shareURL(link, b.tr.T(lang, "referral.share_text", nil))),
{Text: b.tr.T(lang, "btn.copy_link", nil), CopyText: &telego.CopyTextButton{Text: link}},
},
{button(b.tr.T(lang, "btn.qr", nil), cbReferralQR)},
}
if back {
rows = append(rows, b.backRow(lang))
}
return text, keyboard(rows...), nil
}
// cbReferralQR sends the invite link as a QR code.
const cbReferralQR = "rq"
func (b *Bot) cbSendReferralQR(ctx context.Context, q *telego.CallbackQuery, act actor) {
png, err := b.ReferralQR(ctx, act.user.ID)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
link, _ := b.ReferralLink(ctx, act.user.ID)
b.answer(ctx, q, "", false)
_, err = b.api.SendPhoto(ctx, &telego.SendPhotoParams{
ChatID: chatID(act.user.ID),
Photo: telego.InputFile{File: namedReader{Reader: bytes.NewReader(png), name: "invite.png"}},
Caption: b.tr.HTML(act.lang, "referral.qr_caption", i18n.Args{"Link": link}),
ParseMode: telego.ModeHTML,
})
if err != nil {
b.log.Warn("send referral QR", "user_id", act.user.ID, "err", err)
}
}
// applyReferral records who invited a user who arrived through an invite
// link, and reports whether payload was one. Only somebody new to the bot
// can be referred, never by themselves. Old links with the inviter's
// Telegram ID still work.
func (b *Bot) applyReferral(ctx context.Context, act actor, payload string) bool {
var referrer int64
switch {
case strings.HasPrefix(payload, referralPrefix):
if u, err := b.store.UserByRefCode(ctx, strings.TrimPrefix(payload, referralPrefix)); err == nil {
referrer = u.ID
}
case strings.HasPrefix(payload, legacyReferralPrefix):
id, err := strconv.ParseInt(strings.TrimPrefix(payload, legacyReferralPrefix), 10, 64)
if err != nil {
return false
}
referrer = id
default:
return false
}
if referrer != 0 && referrer != act.user.ID && 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)
}
}
return true
}
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
// groupID makes a group's wallet the target instead of the payer's.
groupID int64
}
// 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
}
// Every purchase has a target: the payer's own wallet or a group's.
ownerType, ownerID := db.OwnerUser, act.user.ID
if pc.groupID != 0 {
ownerType, ownerID = db.OwnerGroup, pc.groupID
}
w, err := b.bill.Wallet(ctx, ownerType, ownerID)
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()
text := 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),
})
if title := b.groupTitle(p); title != "" {
text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": title}) + "\n" + text
}
return text
}
// groupTitle returns the title of the group a purchase is for, or "" when
// its target is the payer's own wallet.
func (b *Bot) groupTitle(p *db.Purchase) string {
w, err := b.store.GetWallet(b.baseCtx, p.WalletID)
if err != nil || w.OwnerType != db.OwnerGroup {
return ""
}
g, err := b.store.GetGroup(b.baseCtx, w.OwnerID)
if err != nil || g.Title == "" {
return strconv.FormatInt(w.OwnerID, 10)
}
return g.Title
}
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)
if b.sendInvoiceWidget(ctx, chat, p, text, kb) {
return
}
// Upper case BOLT11 lets the QR code use its compact alphanumeric mode.
png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512)
if err == nil {
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:
text := b.paidText(ctx, p)
b.liveInvoice(ctx, p, text)
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, text, nil)
case db.PurchaseExpired:
text := b.tr.HTML(lang, "invoice.expired", i18n.Args{"Title": b.productTitle(lang, p.Product)})
b.liveInvoice(ctx, p, text)
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, text, nil)
case db.PurchaseCancelled:
if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(p.ChatID), MessageID: int(p.MessageID)}); err != nil {
_ = b.edit(ctx, p.ChatID, p.MessageID, p.MessageIsPhoto, b.tr.HTML(lang, "invoice.cancelled", nil), nil)
}
}
}
// 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 {
switch {
case p.MessageID == 0 && p.PaymentMethod == db.PayStars:
// Telegram's invoice message cannot be edited into "paid", and
// the payment arrived as a message: confirm it right away.
if msg, err := b.send(ctx, p.UserID, 0, b.paidText(ctx, p), nil); err == nil {
_ = b.store.SetPurchaseMessage(context.WithoutCancel(ctx), p.ID, p.UserID, int64(msg.MessageID), false)
}
case 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
amount := b.tr.Sats(lang, p.AmountSats)
if p.PaymentMethod == db.PayStars {
amount = b.starsAmount(lang, p.StarsAmount)
}
text := b.tr.HTML(lang, "invoice.paid", i18n.Args{
"Title": b.productTitle(lang, p.Product),
"Amount": amount,
})
w, err := b.store.GetWallet(ctx, p.WalletID)
if err != nil {
return text
}
// The same facts, worded for whose wallet it is.
balanceKey, passKey := "invoice.balance", "invoice.pass_until"
if w.OwnerType == db.OwnerGroup {
balanceKey, passKey = "invoice.group_balance", "invoice.group_pass_until"
text = b.tr.HTML(lang, "invoice.for_group", i18n.Args{"Group": b.groupTitle(p)}) + "\n" + text
}
switch p.Product {
case billing.ProductCredits:
text += "\n" + b.tr.HTML(lang, balanceKey, 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, passKey, 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 !b.bill.Enabled() {
rows = nil // Stars only: the passes come with the Stars button
}
if b.bill.StarsEnabled() {
rows = append(rows, []telego.InlineKeyboardButton{
button(b.tr.T(lang, "btn.pay_stars", nil), cbData(cbStarsOffer, req.ID, string(profile))),
})
}
if b.bill.Enabled() && (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))),
})
}
if b.cfg.MiniAppEnabled() {
rows = append(rows, []telego.InlineKeyboardButton{{
Text: b.tr.T(lang, "btn.open_app", nil), WebApp: &telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/?page=buy"},
}})
}
} else {
// Two targets, both pre-selected by the link: the requester's own
// wallet, or the group's.
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)},
[]telego.InlineKeyboardButton{urlButton(b.tr.T(lang, "btn.add_group_credits", nil), b.groupWalletLink(chat))},
)
}
_, _ = 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, req.URL, 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)
}