Files
Media-download-telegram-bot/internal/tg/fakeserver/server.go
T
MichilisandClaude Opus 5.5 2b5625e9d4 Phase 4: Telegram Stars payments
- Stars as a second payment method for passes and credit packs, next to
  Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set
  on their own). Invoices in XTR with no provider token and one price;
  pre-checkout checks payer, state, currency and amount;
  successful_payment settles through the same transaction as Lightning,
  so entitlement is identical. Idempotent by telegram_payment_charge_id
  (unique index).
- Migration 00009: payment_method on purchases and ledger entries, plus
  stars_amount, tg_charge_id and refunded_at on purchases. Stars
  purchases never reach LNbits.
- Chat: buy screen, /credits, /account and the over-limit offer show
  Lightning first and a Pay with Stars button.
- Mini App: Lightning and Stars switch on Buy; Stars use
  createInvoiceLink and WebApp.openInvoice, confirmed by the server-side
  payment event.
- Owner /refund <purchase or charge ID> calls refundStarPayment and takes
  back the credits or pass; refunded_payment messages do the same once.
  /stats shows revenue by payment method.
- The sats referral reward counts Lightning purchases only.
- The bot now asks Telegram for pre_checkout_query updates.

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

662 lines
19 KiB
Go

// Package fakeserver is a small in-memory stand-in for the Telegram Bot API.
// Tests and the load script point the bot at it, push updates in and inspect
// the calls the bot makes. It speaks real HTTP, so the bot runs through the
// same telego code paths as in production, including multipart uploads.
package fakeserver
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode/utf16"
)
// Token is a syntactically valid bot token accepted by the fake server.
const Token = "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01"
// BotID and BotUsername describe the fake bot account.
const (
BotID = 123456789
BotUsername = "nr_dl_test_bot"
)
// Call is one Bot API request made by the bot.
type Call struct {
Seq int
Method string
// Params holds the request parameters as strings. Nested values such as
// reply_markup are kept as JSON text.
Params map[string]string
// Files holds uploaded files by parameter name.
Files map[string]File
// MessageID is the ID of the message the call created or edited.
MessageID int
// Failed is true when the server answered with a scripted error.
Failed bool
}
// File is an uploaded file.
type File struct {
Name string
Size int64
}
// Button is one inline keyboard button.
type Button struct {
Text string `json:"text"`
Data string `json:"callback_data"`
URL string `json:"url"`
// WebApp is set on a button that opens a Mini App.
WebApp *struct {
URL string `json:"url"`
} `json:"web_app"`
}
// Buttons parses the inline keyboard of the call, flattened row by row.
func (c Call) Buttons() []Button {
var markup struct {
InlineKeyboard [][]Button `json:"inline_keyboard"`
}
if err := json.Unmarshal([]byte(c.Params["reply_markup"]), &markup); err != nil {
return nil
}
var out []Button
for _, row := range markup.InlineKeyboard {
out = append(out, row...)
}
return out
}
// Button returns the button whose callback data starts with prefix.
func (c Call) Button(prefix string) (Button, bool) {
for _, b := range c.Buttons() {
if strings.HasPrefix(b.Data, prefix) {
return b, true
}
}
return Button{}, false
}
// Text returns the text or caption of a send or edit call.
func (c Call) Text() string {
if t := c.Params["text"]; t != "" {
return t
}
return c.Params["caption"]
}
// ChatID returns the chat_id parameter as a number.
func (c Call) ChatID() int64 {
n, _ := strconv.ParseInt(c.Params["chat_id"], 10, 64)
return n
}
type scriptedError struct {
code int
desc string
}
// Server is the fake Bot API.
type Server struct {
HTTP *httptest.Server
mu sync.Mutex
cond *sync.Cond
updates []map[string]any
updateID int
msgID int
fileSeq int
seq int
calls []Call
failures map[string][]scriptedError
members map[string]string
sent map[int]map[string]any // messages the bot sent, by message ID
langs map[int64]string // the language_code each user last sent
// confirmed is the highest update ID the bot acknowledged by asking for
// a later offset. Like Telegram, confirmed updates are never sent again.
confirmed int
closed bool
}
// New starts a fake server on a random local port.
func New() *Server {
s := NewHandler()
s.HTTP = httptest.NewServer(s)
return s
}
// NewHandler returns a fake server that is not listening yet. It is an
// http.Handler, so a program can serve it on an address of its choice.
func NewHandler() *Server {
s := &Server{
msgID: 1000,
failures: map[string][]scriptedError{},
members: map[string]string{},
sent: map[int]map[string]any{},
}
s.cond = sync.NewCond(&s.mu)
return s
}
// ServeHTTP implements http.Handler.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.handle(w, r) }
// URL returns the API root to pass to the bot as TELEGRAM_API_URL.
func (s *Server) URL() string { return s.HTTP.URL }
// Close stops the server and releases long polls.
func (s *Server) Close() {
s.mu.Lock()
s.closed = true
s.cond.Broadcast()
s.mu.Unlock()
if s.HTTP != nil {
s.HTTP.CloseClientConnections()
s.HTTP.Close()
}
}
// FailNext makes the next call of a method fail with a Bot API error.
func (s *Server) FailNext(method string, code int, description string) {
s.mu.Lock()
defer s.mu.Unlock()
s.failures[method] = append(s.failures[method], scriptedError{code, description})
}
// SetMember sets the chat member status getChatMember reports, for example
// "administrator". The default is "member".
func (s *Server) SetMember(chatID, userID int64, status string) {
s.mu.Lock()
defer s.mu.Unlock()
s.members[fmt.Sprintf("%d:%d", chatID, userID)] = status
}
// Calls returns the calls of one method, or all calls when method is "".
func (s *Server) Calls(method string) []Call {
s.mu.Lock()
defer s.mu.Unlock()
var out []Call
for _, c := range s.calls {
if method == "" || c.Method == method {
out = append(out, c)
}
}
return out
}
// Seq returns the sequence number of the latest call, to be used as a
// starting point for WaitFor.
func (s *Server) Seq() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.seq
}
// WaitFor blocks until a call made after sequence number "after" matches,
// and returns it. ok is false when the timeout passes first. method may be
// several names separated by "|".
func (s *Server) WaitFor(after int, timeout time.Duration, method string, match func(Call) bool) (Call, bool) {
methods := strings.Split(method, "|")
deadline := time.Now().Add(timeout)
timer := time.AfterFunc(timeout, func() {
s.mu.Lock()
s.cond.Broadcast()
s.mu.Unlock()
})
defer timer.Stop()
s.mu.Lock()
defer s.mu.Unlock()
for {
for _, c := range s.calls {
if c.Seq <= after {
continue
}
for _, m := range methods {
if c.Method == m && (match == nil || match(c)) {
return c, true
}
}
}
if time.Now().After(deadline) || s.closed {
return Call{}, false
}
s.cond.Wait()
}
}
// MsgOpt customizes a pushed message.
type MsgOpt func(msg map[string]any)
// Lang sets the language_code of the sender.
func Lang(code string) MsgOpt {
return func(msg map[string]any) {
msg["from"].(map[string]any)["language_code"] = code
}
}
// ReplyTo makes the message a reply to an earlier message with given text.
func ReplyTo(messageID int, text string) MsgOpt {
return func(msg map[string]any) {
msg["reply_to_message"] = map[string]any{
"message_id": messageID,
"date": time.Now().Unix(),
"chat": msg["chat"],
"from": map[string]any{"id": 4242, "is_bot": false, "first_name": "Other"},
"text": text,
"entities": entitiesFor(text),
}
}
}
// From sets the first name and username of the sender.
func From(firstName, username string) MsgOpt {
return func(msg map[string]any) {
from := msg["from"].(map[string]any)
from["first_name"] = firstName
from["username"] = username
}
}
// PushMessage queues a text message update and returns its message ID.
// Negative chat IDs are groups, positive ones private chats.
func (s *Server) PushMessage(chatID, userID int64, text string, opts ...MsgOpt) int {
s.mu.Lock()
defer s.mu.Unlock()
s.msgID++
msg := map[string]any{
"message_id": s.msgID,
"date": time.Now().Unix(),
"chat": chatObject(chatID),
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": "en"},
"text": text,
}
if ents := entitiesFor(text); len(ents) > 0 {
msg["entities"] = ents
}
for _, o := range opts {
o(msg)
}
// Telegram sends the language of the user's app with every update, so
// later button presses of this user carry the same one.
if code, ok := msg["from"].(map[string]any)["language_code"].(string); ok {
s.langOf()[userID] = code
}
s.pushLocked(map[string]any{"message": msg})
return s.msgID
}
// langOf is the language_code each user last sent. Callers hold s.mu.
func (s *Server) langOf() map[int64]string {
if s.langs == nil {
s.langs = map[int64]string{}
}
return s.langs
}
// userLang is the language_code to send for a user. Callers hold s.mu.
func (s *Server) userLang(userID int64) string {
if code, ok := s.langOf()[userID]; ok {
return code
}
return "en"
}
// PushCallback queues a button press on a message.
func (s *Server) PushCallback(chatID, userID int64, messageID int, data string) string {
s.mu.Lock()
defer s.mu.Unlock()
id := fmt.Sprintf("cb%d", s.updateID+1)
// Like Telegram, the update carries the message the button sits on.
msg, known := s.sent[messageID]
if !known {
msg = map[string]any{
"message_id": messageID,
"date": time.Now().Unix(),
"chat": chatObject(chatID),
"from": botUser(),
"text": "card",
}
}
s.pushLocked(map[string]any{"callback_query": map[string]any{
"id": id,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"chat_instance": "ci",
"data": data,
"message": msg,
}})
return id
}
// PushWidgetQuery queues a request from the widget in a message, as a
// widget_query update. It returns the query ID.
func (s *Server) PushWidgetQuery(chatID, userID int64, messageID int, data string) string {
s.mu.Lock()
defer s.mu.Unlock()
s.msgID++
id := "wq" + strconv.Itoa(s.msgID)
s.pushLocked(map[string]any{"widget_query": map[string]any{
"id": id,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"chat": chatObject(chatID),
"message_id": messageID,
"chat_instance": "ci" + strconv.FormatInt(chatID, 10),
"type": map[string]any{"type": "data"},
"data": data,
}})
return id
}
// PushPreCheckout queues the query Telegram sends before it takes a
// payment, and returns its ID.
func (s *Server) PushPreCheckout(userID int64, payload, currency string, total int) string {
s.mu.Lock()
defer s.mu.Unlock()
id := fmt.Sprintf("pcq%d", s.updateID+1)
s.pushLocked(map[string]any{"pre_checkout_query": map[string]any{
"id": id,
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
"currency": currency,
"total_amount": total,
"invoice_payload": payload,
}})
return id
}
// PushSuccessfulPayment queues the service message of a completed payment
// in the payer's private chat.
func (s *Server) PushSuccessfulPayment(userID int64, payload, currency string, total int, chargeID string) {
s.pushPaymentLocked(userID, "successful_payment", map[string]any{
"currency": currency, "total_amount": total, "invoice_payload": payload,
"telegram_payment_charge_id": chargeID, "provider_payment_charge_id": "",
})
}
// PushRefundedPayment queues the service message of a refunded payment.
func (s *Server) PushRefundedPayment(userID int64, payload string, total int, chargeID string) {
s.pushPaymentLocked(userID, "refunded_payment", map[string]any{
"currency": "XTR", "total_amount": total, "invoice_payload": payload,
"telegram_payment_charge_id": chargeID,
})
}
func (s *Server) pushPaymentLocked(userID int64, field string, body map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
s.msgID++
s.pushLocked(map[string]any{"message": map[string]any{
"message_id": s.msgID,
"date": time.Now().Unix(),
"chat": chatObject(userID),
"from": map[string]any{"id": userID, "is_bot": false, "first_name": "User", "language_code": s.userLang(userID)},
field: body,
}})
}
// PushRaw queues an arbitrary update body, for example my_chat_member.
func (s *Server) PushRaw(update map[string]any) {
s.mu.Lock()
defer s.mu.Unlock()
s.pushLocked(update)
}
func (s *Server) pushLocked(update map[string]any) {
s.updateID++
update["update_id"] = s.updateID
s.updates = append(s.updates, update)
s.cond.Broadcast()
}
func chatObject(chatID int64) map[string]any {
if chatID < 0 {
return map[string]any{"id": chatID, "type": "supergroup", "title": "Test Group"}
}
return map[string]any{"id": chatID, "type": "private", "first_name": "User"}
}
func botUser() map[string]any {
return map[string]any{"id": BotID, "is_bot": true, "first_name": "NR Download Bot", "username": BotUsername}
}
var (
cmdRe = regexp.MustCompile(`^/[A-Za-z0-9_]+(@[A-Za-z0-9_]+)?`)
urlRe = regexp.MustCompile(`(?i)(https?://[^\s]+|\b[a-z0-9-]+\.(be|com|org|net|tv)/[^\s]+)`)
)
func entitiesFor(text string) []map[string]any {
var out []map[string]any
u16 := func(byteOff int) int { return len(utf16.Encode([]rune(text[:byteOff]))) }
if loc := cmdRe.FindStringIndex(text); loc != nil {
out = append(out, map[string]any{"type": "bot_command", "offset": 0, "length": u16(loc[1])})
}
for _, loc := range urlRe.FindAllStringIndex(text, -1) {
out = append(out, map[string]any{"type": "url", "offset": u16(loc[0]), "length": u16(loc[1]) - u16(loc[0])})
}
return out
}
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
// Path: /bot<token>/<method>
rest, ok := strings.CutPrefix(r.URL.Path, "/bot"+Token+"/")
if !ok {
writeJSON(w, http.StatusUnauthorized, map[string]any{"ok": false, "error_code": 401, "description": "Unauthorized"})
return
}
method := rest
params, files, err := readParams(r)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"ok": false, "error_code": 400, "description": "Bad Request: " + err.Error()})
return
}
if method == "getUpdates" {
s.getUpdates(w, params)
return
}
s.mu.Lock()
s.seq++
call := Call{Seq: s.seq, Method: method, Params: params, Files: files}
if q := s.failures[method]; len(q) > 0 {
fail := q[0]
s.failures[method] = q[1:]
call.Failed = true
s.calls = append(s.calls, call)
s.cond.Broadcast()
s.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error_code": fail.code, "description": fail.desc})
return
}
result := s.resultLocked(&call)
s.calls = append(s.calls, call)
s.cond.Broadcast()
s.mu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "result": result})
}
func (s *Server) getUpdates(w http.ResponseWriter, params map[string]string) {
offset, _ := strconv.Atoi(params["offset"])
// Long polls are kept short so tests shut down quickly.
deadline := time.Now().Add(150 * time.Millisecond)
timer := time.AfterFunc(150*time.Millisecond, func() {
s.mu.Lock()
s.cond.Broadcast()
s.mu.Unlock()
})
defer timer.Stop()
s.mu.Lock()
defer s.mu.Unlock()
if offset-1 > s.confirmed {
s.confirmed = offset - 1
}
for {
var out []map[string]any
for _, u := range s.updates {
if id := u["update_id"].(int); id > s.confirmed && id >= offset {
out = append(out, u)
}
}
if len(out) > 0 || time.Now().After(deadline) || s.closed {
if out == nil {
out = []map[string]any{}
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "result": out})
return
}
s.cond.Wait()
}
}
// resultLocked builds a plausible result for a call.
func (s *Server) resultLocked(c *Call) any {
switch c.Method {
case "getMe":
return botUser()
case "getChatMember":
status := s.members[c.Params["chat_id"]+":"+c.Params["user_id"]]
if status == "" {
status = "member"
}
uid, _ := strconv.ParseInt(c.Params["user_id"], 10, 64)
return map[string]any{"status": status, "user": map[string]any{"id": uid, "is_bot": false, "first_name": "User"}}
case "createInvoiceLink":
s.fileSeq++
return fmt.Sprintf("https://t.me/$fake_invoice_%d", s.fileSeq)
case "sendMessage", "sendPhoto", "sendVideo", "sendAudio", "sendDocument", "sendAnimation", "sendWidget", "sendInvoice":
s.msgID++
c.MessageID = s.msgID
msg := s.messageLocked(c)
s.sent[c.MessageID] = msg
return msg
case "editMessageText", "editMessageCaption", "editMessageReplyMarkup", "editMessageMedia":
c.MessageID, _ = strconv.Atoi(c.Params["message_id"])
return s.messageLocked(c)
case "editMessageWidgetData", "deleteMessage":
c.MessageID, _ = strconv.Atoi(c.Params["message_id"])
return true
default:
return true
}
}
func (s *Server) messageLocked(c *Call) map[string]any {
msg := map[string]any{
"message_id": c.MessageID,
"date": time.Now().Unix(),
"chat": chatObject(c.ChatID()),
"from": botUser(),
}
if t := c.Params["text"]; t != "" {
msg["text"] = t
}
if t := c.Params["caption"]; t != "" {
msg["caption"] = t
}
media := func(field string) map[string]any {
// A string parameter is a file_id or URL and keeps its identity; an
// upload gets a fresh file_id.
id := c.Params[field]
if _, uploaded := c.Files[field]; uploaded || id == "" || strings.HasPrefix(id, "http") {
s.fileSeq++
id = fmt.Sprintf("%s-file-%d", field, s.fileSeq)
}
return map[string]any{"file_id": id, "file_unique_id": "u-" + id}
}
switch c.Method {
case "sendPhoto":
ph := media("photo")
ph["width"], ph["height"] = 320, 180
msg["photo"] = []any{ph}
case "sendVideo":
v := media("video")
v["width"], v["height"], v["duration"] = 1280, 720, 60
msg["video"] = v
case "sendAudio":
a := media("audio")
a["duration"] = 60
msg["audio"] = a
case "sendDocument":
msg["document"] = media("document")
case "sendAnimation":
a := media("animation")
a["width"], a["height"], a["duration"] = 320, 180, 3
msg["animation"] = a
case "sendWidget":
msg["widget"] = map[string]any{"html": c.Params["html"], "chat_data": c.Params["chat_data"], "public_data": c.Params["public_data"]}
case "sendInvoice":
var prices []struct {
Amount int `json:"amount"`
}
_ = json.Unmarshal([]byte(c.Params["prices"]), &prices)
total := 0
for _, p := range prices {
total += p.Amount
}
msg["invoice"] = map[string]any{"title": c.Params["title"], "description": c.Params["description"],
"start_parameter": "", "currency": c.Params["currency"], "total_amount": total}
}
return msg
}
func readParams(r *http.Request) (map[string]string, map[string]File, error) {
params := map[string]string{}
files := map[string]File{}
ct := r.Header.Get("Content-Type")
switch {
case strings.HasPrefix(ct, "multipart/form-data"):
mr, err := r.MultipartReader()
if err != nil {
return nil, nil, err
}
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
return nil, nil, err
}
if part.FileName() != "" {
n, _ := io.Copy(io.Discard, part)
files[part.FormName()] = File{Name: part.FileName(), Size: n}
continue
}
b, _ := io.ReadAll(part)
params[part.FormName()] = string(b)
}
default:
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, nil, err
}
if len(strings.TrimSpace(string(body))) == 0 {
return params, files, nil
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(body, &raw); err != nil {
return nil, nil, err
}
for k, v := range raw {
var str string
if json.Unmarshal(v, &str) == nil {
params[k] = str
} else {
params[k] = string(v)
}
}
}
return params, files, nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}