Files
Media-download-telegram-bot/internal/api/miniapp.go
T
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

845 lines
27 KiB
Go

package api
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io/fs"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
qrcode "github.com/skip2/go-qrcode"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/bot"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/groups"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
// MiniApp serves the Telegram Mini App: the static front end under /app/
// and its JSON API under /app/api/.
//
// Every API call carries the initData string Telegram gave the app, in
// "Authorization: tma <initData>". It is validated on each request; there
// is no session and no cookie. Whatever the front end shows, what a user
// may do and what it costs is decided here, by the same service the chat
// commands use.
type MiniApp struct {
Cfg config.Config
Store *db.Store
Billing *billing.Billing
Service *service.Service
Bot *bot.Bot
I18n *i18n.Bundle
Admins *groups.Admins
Log *slog.Logger
// Static is the built front end.
Static fs.FS
// MaxAge bounds how old an initData may be. Defaults to 24 hours.
MaxAge time.Duration
Now func() time.Time
}
// session is the authenticated caller of one request.
type session struct {
user *db.User
lang string
init *InitData
}
type appHandler func(w http.ResponseWriter, r *http.Request, s *session)
// RegisterMiniApp adds the Mini App routes to the server.
func (s *Server) RegisterMiniApp(m *MiniApp) {
if m.Log == nil {
m.Log = s.log
}
if m.MaxAge <= 0 {
m.MaxAge = 24 * time.Hour
}
if m.Now == nil {
m.Now = time.Now
}
api := func(pattern string, h appHandler) { s.mux.HandleFunc(pattern, m.auth(h)) }
api("GET /app/api/me", m.me)
api("PUT /app/api/me", m.updateMe)
api("GET /app/api/i18n", m.messages)
api("POST /app/api/probe", m.probe)
api("POST /app/api/download", m.download)
api("GET /app/api/queue", m.queue)
api("POST /app/api/queue/{id}/cancel", m.cancel)
api("POST /app/api/queue/{id}/prioritize", m.prioritize)
api("GET /app/api/history", m.history)
api("POST /app/api/history/{id}/resend", m.resend)
api("GET /app/api/products", m.products)
api("POST /app/api/purchase", m.purchase)
api("GET /app/api/purchase/{id}", m.purchaseStatus)
api("POST /app/api/purchase/{id}/cancel", m.purchaseCancel)
api("GET /app/api/groups", m.groups)
api("GET /app/api/groups/{id}", m.group)
api("PUT /app/api/groups/{id}/settings", m.groupSettings)
api("GET /app/api/groups/{id}/usage", m.groupUsage)
if m.Static != nil {
s.mux.Handle("GET /app/", m.static())
}
}
// static serves the built front end. Unknown paths get index.html, which
// is what a single page app needs. Files carry an ETag of their content,
// so a client revalidates cheaply and picks up a new build at once.
func (m *MiniApp) static() http.Handler {
etags := map[string]string{}
_ = fs.WalkDir(m.Static, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
if data, err := fs.ReadFile(m.Static, path); err == nil {
sum := sha256.Sum256(data)
etags[path] = `"` + hex.EncodeToString(sum[:8]) + `"`
}
return nil
})
files := http.StripPrefix("/app/", http.FileServerFS(m.Static))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/app/")
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Cache-Control", "no-cache")
// The app only loads its own code plus Telegram's bridge script,
// and may only be framed by Telegram's web clients. No images from
// other hosts: a thumbnail fetched by the browser would show the
// user's address to the video site.
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self' https://telegram.org; "+
"style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "+
"frame-ancestors https://web.telegram.org https://*.telegram.org")
if _, ok := etags[path]; !ok {
path = "index.html"
r = r.Clone(r.Context())
r.URL.Path = "/app/"
}
h.Set("ETag", etags[path])
files.ServeHTTP(w, r)
})
}
func (m *MiniApp) fail(w http.ResponseWriter, status int, code, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{"error": code, "message": message})
}
// explain answers with the bot's wording for an operation error.
func (m *MiniApp) explain(w http.ResponseWriter, s *session, err error) {
code, msg, upgradable := m.Bot.Explain(s.lang, err)
status := http.StatusUnprocessableEntity
switch code {
case "internal":
status = http.StatusInternalServerError
case "not_found":
// The chat wording talks about a card, which the app does not have.
status, msg = http.StatusNotFound, m.I18n.T(s.lang, "app.error.not_found", nil)
case "rate_limited":
status = http.StatusTooManyRequests
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{"error": code, "message": msg, "upgradable": upgradable})
}
func (m *MiniApp) ok(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(v)
}
// auth validates initData and loads the user. It runs on every call.
func (m *MiniApp) auth(next appHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
raw, _ := strings.CutPrefix(r.Header.Get("Authorization"), "tma ")
init, err := ValidateInitData(raw, m.Cfg.Telegram.Token, m.MaxAge, m.Now())
if err != nil {
// The caller is unknown, so the browser's language is the best
// guess for the one sentence it gets to read.
lang, _, _ := strings.Cut(r.Header.Get("Accept-Language"), ",")
lang, _, _ = strings.Cut(lang, ";")
m.fail(w, http.StatusUnauthorized, "unauthorized", m.I18n.T(m.I18n.Resolve(strings.TrimSpace(lang)), "app.error.unauthorized", nil))
return
}
u, err := m.Store.UpsertUser(r.Context(), init.User.ID, init.User.Username, init.User.FirstName, init.User.LanguageCode)
if err != nil {
m.Log.Error("mini app: load user", "err", err)
m.fail(w, http.StatusInternalServerError, "internal", "")
return
}
lang := u.LangOverride
if lang == "" {
lang = m.I18n.Resolve(u.Lang)
}
if u.Banned {
m.fail(w, http.StatusForbidden, "forbidden", m.I18n.T(lang, "app.error.banned", nil))
return
}
next(w, r, &session{user: u, lang: lang, init: init})
}
}
func decode(r *http.Request, v any) error {
return json.NewDecoder(http.MaxBytesReader(nil, r.Body, 64<<10)).Decode(v)
}
// --- me ----------------------------------------------------------------------
type tierJSON struct {
MaxSize int64 `json:"max_size"`
MaxDuration int64 `json:"max_duration"`
ActiveJobs int `json:"active_jobs"`
DailyDownloads int `json:"daily_downloads"`
DailyBytes int64 `json:"daily_bytes"`
}
func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) {
ctx := r.Context()
who := service.Who{UserID: s.user.ID, ChatID: s.user.ID, ChatType: "private"}
dec, err := m.Service.Entitlement(ctx, who, false)
if err != nil {
m.explain(w, s, err)
return
}
st, _ := m.Billing.State(ctx, db.OwnerUser, s.user.ID)
usage, _ := m.Service.Usage(ctx, s.user.ID)
refStats, _ := m.Bot.ReferralStats(ctx, s.user.ID)
refLink, err := m.Bot.ReferralLink(ctx, s.user.ID)
if err != nil {
m.explain(w, s, err)
return
}
refQR := ""
if png, err := m.Bot.ReferralQR(ctx, s.user.ID); err == nil {
refQR = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
}
var langs []map[string]string
for _, l := range m.I18n.Langs() {
if !m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID) {
langs = append(langs, map[string]string{"code": l, "name": m.I18n.T(l, "language.name", nil)})
}
}
support := m.Cfg.Support
if support == "" {
support = "@" + m.Bot.Username()
}
m.ok(w, map[string]any{
"id": s.user.ID,
"name": s.user.FirstName,
"lang": s.lang,
"lang_override": s.user.LangOverride,
"dir": i18n.Dir(s.lang),
"languages": langs,
"quality": appQuality(s.user.Quality),
"pass_until": st.PassUntil,
"balance": st.Credits,
"source": string(dec.Source),
"usage": map[string]any{"downloads": usage.Downloads, "bytes": usage.Bytes},
"limits": tierJSON{
MaxSize: dec.Limits.MaxSize, MaxDuration: dec.Limits.MaxDuration, ActiveJobs: dec.Limits.ActiveJobs,
DailyDownloads: dec.Limits.DailyDownloads, DailyBytes: dec.Limits.DailyBytes,
},
"payments": m.Billing.Enabled(),
"referral_link": refLink,
"referral_count": refStats.Invited,
"referral_converted": refStats.Converted,
"referral_earned": refStats.Earned,
"referral_pending": refStats.Pending,
"referral_qr": refQR,
"referral_reward": m.Cfg.Prices.ReferralReward,
"referral_daily_cap": m.Cfg.ReferralDailyCap,
// Telegram's affiliate program is set up and paid by Telegram; the
// app only explains it, and shows no numbers of its own.
"affiliate_enabled": m.Cfg.AffiliateEnabled,
"stars_enabled": m.Billing.StarsEnabled(),
"support": support,
"start_param": s.init.StartParam,
"bot": m.Bot.Username(),
})
}
// The app writes "" for "ask every time", as it does for groups. In the
// users table "" means the user never chose, which behaves like "fit"
// (best that fits the limit) after the first link, and "ask" is stored.
func appQuality(stored string) string {
switch stored {
case "":
return "fit"
case "ask":
return ""
}
return stored
}
func storedQuality(app string) string {
if app == "" {
return "ask"
}
return app
}
func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) {
var in struct {
Quality *string `json:"quality"`
Lang *string `json:"lang"`
}
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
ctx := r.Context()
if in.Quality != nil {
q := storedQuality(*in.Quality)
if q != "ask" && q != "fit" {
p, err := media.Parse(q)
if err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
}
if err := m.Store.SetUserQuality(ctx, s.user.ID, q); err != nil {
m.explain(w, s, err)
return
}
}
if in.Lang != nil {
lang := ""
if *in.Lang != "" && *in.Lang != "auto" {
for _, l := range m.I18n.Langs() {
if l == *in.Lang && (!m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID)) {
lang = l
}
}
if lang == "" {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
}
if err := m.Store.SetUserLang(ctx, s.user.ID, lang); err != nil {
m.explain(w, s, err)
return
}
if lang != s.user.LangOverride {
m.Bot.SyncUserMenu(ctx, s.user.ID, lang)
}
}
m.ok(w, map[string]bool{"ok": true})
}
// appTables are the catalog tables the Mini App reads. Its own texts are
// under "app"; names it shares with the chat (products, units, button and
// setting labels) are not written twice.
var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language", "referral"}
// messages returns the Mini App's texts in the user's language, from the
// same catalogs the bot uses. Keys keep their full name: "app.tab.home".
func (m *MiniApp) messages(w http.ResponseWriter, _ *http.Request, s *session) {
out := map[string]any{}
for _, table := range appTables {
for k, v := range m.I18n.Section(s.lang, table) {
out[table+"."+k] = v
}
}
m.ok(w, map[string]any{"lang": s.lang, "dir": i18n.Dir(s.lang), "messages": out})
}
// --- downloads ---------------------------------------------------------------
func (m *MiniApp) probe(w http.ResponseWriter, r *http.Request, s *session) {
var in struct {
URL string `json:"url"`
}
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
url, err := links.Normalize(in.URL)
if err != nil {
m.fail(w, http.StatusUnprocessableEntity, "bad_link", m.I18n.T(s.lang, "app.error.bad_link", nil))
return
}
info, err := m.Bot.AppProbe(r.Context(), s.user, url)
if err != nil {
m.explain(w, s, err)
return
}
type option struct {
Profile string `json:"profile"`
Size int64 `json:"size,omitempty"`
}
opts := []option{{Profile: "best", Size: info.Sizes["best"]}}
for _, p := range []media.Profile{media.P1080, media.P720, media.P480} {
if info.MaxHeight == 0 || info.MaxHeight > p.Height() {
opts = append(opts, option{Profile: string(p), Size: info.Sizes[string(p)]})
}
}
if info.HasAudio {
opts = append(opts, option{Profile: "mp3", Size: info.Sizes["mp3"]})
}
m.ok(w, map[string]any{
"url": url, "title": info.Title, "uploader": info.Uploader,
"duration": info.Duration, "site": info.Site, "options": opts,
})
}
func (m *MiniApp) download(w http.ResponseWriter, r *http.Request, s *session) {
var in struct {
URL string `json:"url"`
Profile string `json:"profile"`
}
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
url, uerr := links.Normalize(in.URL)
profile, perr := media.Parse(in.Profile)
if uerr != nil || perr != nil {
m.fail(w, http.StatusUnprocessableEntity, "bad_link", m.I18n.T(s.lang, "app.error.bad_link", nil))
return
}
if err := m.Bot.AppDownload(r.Context(), s.user, s.lang, url, profile); err != nil {
m.explain(w, s, err)
return
}
m.ok(w, map[string]bool{"ok": true})
}
func (m *MiniApp) queue(w http.ResponseWriter, r *http.Request, s *session) {
jobs, err := m.Bot.AppQueue(r.Context(), s.user.ID)
if err != nil {
m.explain(w, s, err)
return
}
m.ok(w, map[string]any{"jobs": jobs})
}
func (m *MiniApp) cancel(w http.ResponseWriter, r *http.Request, s *session) {
if err := m.Bot.AppCancel(r.Context(), s.user.ID, r.PathValue("id")); err != nil {
m.explain(w, s, err)
return
}
m.ok(w, map[string]bool{"ok": true})
}
func (m *MiniApp) prioritize(w http.ResponseWriter, r *http.Request, s *session) {
done, p, err := m.Bot.AppSkip(r.Context(), s.user, s.lang, r.PathValue("id"))
if err != nil {
m.explain(w, s, err)
return
}
out := map[string]any{"done": done}
if p != nil {
out["purchase"] = m.purchaseJSON(p, true)
}
m.ok(w, out)
}
func (m *MiniApp) history(w http.ResponseWriter, r *http.Request, s *session) {
limit := 30
if r.URL.Query().Get("limit") == "5" {
limit = 5
}
dels, err := m.Store.History(r.Context(), s.user.ID, limit)
if err != nil {
m.explain(w, s, err)
return
}
type item struct {
ID string `json:"id"`
Title string `json:"title"`
Profile string `json:"profile"`
Size int64 `json:"size"`
At int64 `json:"at"`
}
items := []item{}
for _, d := range dels {
job, err := m.Store.GetJob(r.Context(), d.JobID)
if err != nil {
continue
}
items = append(items, item{ID: d.ID, Title: job.Title, Profile: job.Profile, Size: job.FileSize, At: d.UpdatedAt})
}
m.ok(w, map[string]any{"items": items})
}
func (m *MiniApp) resend(w http.ResponseWriter, r *http.Request, s *session) {
if err := m.Bot.AppResend(r.Context(), s.user, s.lang, r.PathValue("id")); err != nil {
m.explain(w, s, err)
return
}
m.ok(w, map[string]bool{"ok": true})
}
// --- buying ------------------------------------------------------------------
func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) {
p := m.Cfg.Prices
paid := m.Cfg.Limits.Paid
size := paid.MaxSizeMB << 20
if up := m.Cfg.MaxUploadBytes(); up > 0 && up < size {
size = up
}
stars := func(product string, amount int64) int64 {
n, _ := m.Billing.StarsPrice(product, amount)
return n
}
starsPacks := []map[string]int64{}
for _, a := range p.CreditPacks {
if n := stars(billing.ProductCredits, a); n > 0 {
starsPacks = append(starsPacks, map[string]int64{"amount": a, "stars": n})
}
}
m.ok(w, map[string]any{
"enabled": m.Billing.Selling(),
"lightning": m.Billing.Enabled(),
"stars": m.Billing.StarsEnabled(),
"passes": []map[string]any{
{"product": billing.ProductPassDay, "price": p.PassDay, "stars": stars(billing.ProductPassDay, 0)},
{"product": billing.ProductPassWeek, "price": p.PassWeek, "stars": stars(billing.ProductPassWeek, 0)},
{"product": billing.ProductPassMonth, "price": p.PassMonth, "stars": stars(billing.ProductPassMonth, 0)},
},
"stars_packs": starsPacks,
"credit_packs": p.CreditPacks,
"credit_per_download": p.CreditPerDownload,
"paid": tierJSON{MaxSize: size, MaxDuration: int64(paid.MaxDuration.D().Seconds()), ActiveJobs: paid.ActiveJobs, DailyDownloads: paid.DailyDownloads, DailyBytes: paid.DailyMB << 20},
"invoice_seconds": int(m.Cfg.LNbits.InvoiceExpiry.D().Seconds()),
})
}
// purchaseJSON is what the app needs to show an invoice. The QR code is
// made here, so the front end needs no QR library.
func (m *MiniApp) purchaseJSON(p *db.Purchase, withInvoice bool) map[string]any {
out := map[string]any{
"id": p.ID, "product": p.Product, "amount": p.AmountSats, "status": p.Status,
"expires_at": p.ExpiresAt, "paid_at": p.PaidAt, "method": p.PaymentMethod, "stars": p.StarsAmount,
}
if withInvoice && p.Status == db.PurchasePending && p.PaymentMethod != db.PayStars {
out["bolt11"] = p.Bolt11
if png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512); err == nil {
out["qr"] = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png)
}
}
return out
}
func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) {
var in struct {
Target string `json:"target"` // "me" or a group chat ID
Product string `json:"product"`
Amount int64 `json:"amount"`
// Method is "lightning" (the default) or "stars".
Method string `json:"method"`
}
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
// Products that need a download or a job behind them are not sold
// from this endpoint.
switch in.Product {
case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth, billing.ProductCredits:
default:
m.explain(w, s, billing.ErrBadProduct)
return
}
var groupID int64
if in.Target != "" && in.Target != "me" {
id, err := strconv.ParseInt(in.Target, 10, 64)
if err != nil || id >= 0 {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
groupID = id
}
if in.Method == db.PayStars {
p, link, err := m.Bot.AppStarsPurchase(r.Context(), s.user, s.lang, groupID, in.Product, in.Amount)
if err != nil {
m.explain(w, s, err)
return
}
out := m.purchaseJSON(p, true)
out["invoice_link"] = link
m.ok(w, out)
return
}
p, err := m.Bot.AppPurchase(r.Context(), s.user, s.lang, groupID, in.Product, in.Amount, "")
if err != nil {
m.explain(w, s, err)
return
}
m.ok(w, m.purchaseJSON(p, true))
}
// purchaseStatus is polled by the app while an invoice is open. Each call
// asks the payment backend, so the app notices a payment within seconds
// even when the webhook is not set up.
func (m *MiniApp) purchaseStatus(w http.ResponseWriter, r *http.Request, s *session) {
p, err := m.Billing.Check(r.Context(), r.PathValue("id"), s.user.ID)
if errors.Is(err, billing.ErrLightningDown) {
// Still answer with what is known; the next poll may reach it.
if p, err = m.Store.GetPurchase(r.Context(), r.PathValue("id")); err == nil && p.UserID != s.user.ID {
err = db.ErrNotFound
}
}
if err != nil {
m.explain(w, s, db.ErrNotFound)
return
}
out := m.purchaseJSON(p, false)
if p.Status == db.PurchasePaid {
if wl, err := m.Store.GetWallet(r.Context(), p.WalletID); err == nil {
out["balance"] = wl.Balance
if until, err := m.Store.PassUntil(r.Context(), wl.ID, db.NowMilli()); err == nil {
out["pass_until"] = until
}
}
}
m.ok(w, out)
}
func (m *MiniApp) purchaseCancel(w http.ResponseWriter, r *http.Request, s *session) {
if _, err := m.Billing.Cancel(r.Context(), r.PathValue("id"), s.user.ID); err != nil {
m.explain(w, s, db.ErrNotFound)
return
}
m.ok(w, map[string]bool{"ok": true})
}
// --- groups ------------------------------------------------------------------
func (m *MiniApp) groupJSON(ctx context.Context, g *db.Group) map[string]any {
st, _ := m.Billing.State(ctx, db.OwnerGroup, g.ChatID)
return map[string]any{
"id": strconv.FormatInt(g.ChatID, 10), "title": g.Title, "balance": st.Credits, "pass_until": st.PassUntil,
}
}
// groups lists the groups where the caller is an admin and the bot is
// present. Admin status is asked from Telegram, never taken from the app.
func (m *MiniApp) groups(w http.ResponseWriter, r *http.Request, s *session) {
ctx := r.Context()
list, err := m.Store.GroupsOfUser(ctx, s.user.ID, 50)
if err != nil {
m.explain(w, s, err)
return
}
out := []map[string]any{}
for _, g := range list {
if m.Admins.IsAdmin(ctx, g.ChatID, s.user.ID) {
out = append(out, m.groupJSON(ctx, g))
}
}
m.ok(w, map[string]any{"groups": out})
}
// adminGroup loads the group of a request and checks that the caller is
// one of its admins. Every group endpoint goes through it.
func (m *MiniApp) adminGroup(w http.ResponseWriter, r *http.Request, s *session) (*db.Group, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return nil, false
}
g, err := m.Store.GetGroup(r.Context(), id)
if err != nil || !g.Present() {
m.explain(w, s, db.ErrNotFound)
return nil, false
}
if !m.Admins.IsAdmin(r.Context(), id, s.user.ID) {
m.fail(w, http.StatusForbidden, "forbidden", m.I18n.T(s.lang, "notice.admins_only", nil))
return nil, false
}
return g, true
}
type settingsJSON struct {
Enabled bool `json:"enabled"`
AutoDetect bool `json:"auto_detect"`
DeleteCmds bool `json:"delete_commands"`
WhoCanUse string `json:"who_can_use"`
SpendRule string `json:"spend_rule"`
SpendCap int64 `json:"spend_cap"`
DailyCap int64 `json:"daily_cap"`
MaxSizeMB int64 `json:"max_size_mb"`
MaxDuration int64 `json:"max_duration"`
Quality string `json:"quality"`
Lang string `json:"lang"`
Allowed []string `json:"allowed"`
Blocked []string `json:"blocked"`
}
func toSettingsJSON(st *db.GroupSettings) settingsJSON {
nonNil := func(v []string) []string {
if v == nil {
return []string{}
}
return v
}
return settingsJSON{
Enabled: st.Enabled, AutoDetect: st.AutoDetect, DeleteCmds: st.DeleteCmds, WhoCanUse: st.WhoCanUse,
SpendRule: st.SpendRule, SpendCap: st.SpendCap, DailyCap: st.DailyCap, MaxSizeMB: st.MaxSizeMB,
MaxDuration: st.MaxDuration, Quality: st.Quality, Lang: st.Lang,
Allowed: nonNil(db.Sites(st.Allowed)), Blocked: nonNil(db.Sites(st.Blocked)),
}
}
func (m *MiniApp) group(w http.ResponseWriter, r *http.Request, s *session) {
g, ok := m.adminGroup(w, r, s)
if !ok {
return
}
st, err := m.Store.GetGroupSettings(r.Context(), g.ChatID)
if err != nil {
m.explain(w, s, err)
return
}
out := m.groupJSON(r.Context(), g)
out["settings"] = toSettingsJSON(st)
out["tier_max_size_mb"] = m.Cfg.Limits.Paid.MaxSizeMB
out["tier_max_duration"] = int64(m.Cfg.Limits.Paid.MaxDuration.D().Seconds())
m.ok(w, out)
}
func cleanHosts(in []string) (string, bool) {
var out []string
seen := map[string]bool{}
for _, raw := range in {
h := groups.CleanHost(raw)
if h == "" {
return "", false
}
if !seen[h] {
seen[h] = true
out = append(out, h)
}
}
if len(out) > 50 {
return "", false
}
return strings.Join(out, ","), true
}
// groupSettings replaces a group's settings. Every field is validated:
// the front end is not trusted to send sane values.
func (m *MiniApp) groupSettings(w http.ResponseWriter, r *http.Request, s *session) {
g, ok := m.adminGroup(w, r, s)
if !ok {
return
}
var in settingsJSON
if err := decode(r, &in); err != nil {
m.fail(w, http.StatusBadRequest, "bad_request", "")
return
}
bad := func() {
m.fail(w, http.StatusBadRequest, "bad_request", m.I18n.T(s.lang, "app.error.bad_settings", nil))
}
switch in.WhoCanUse {
case db.UseEveryone, db.UsePassHolders, db.UseAdmins:
default:
bad()
return
}
switch in.SpendRule {
case db.SpendAnyone, db.SpendAdmins, db.SpendCapped:
default:
bad()
return
}
tier := m.Cfg.Limits.Paid
if in.SpendCap < 0 || in.SpendCap > billing.MaxAmount || in.DailyCap < 0 || in.DailyCap > billing.MaxAmount ||
in.MaxSizeMB < 0 || in.MaxDuration < 0 {
bad()
return
}
// Caps go up to the group's tier and no further.
if tier.MaxSizeMB > 0 && in.MaxSizeMB > tier.MaxSizeMB {
in.MaxSizeMB = tier.MaxSizeMB
}
if max := int64(tier.MaxDuration.D().Seconds()); max > 0 && in.MaxDuration > max {
in.MaxDuration = max
}
if in.Quality != "" {
if p, err := media.Parse(in.Quality); err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) {
bad()
return
}
}
if in.Lang != "" {
known := false
for _, l := range m.I18n.Langs() {
known = known || l == in.Lang
}
if !known {
bad()
return
}
}
allowed, ok1 := cleanHosts(in.Allowed)
blocked, ok2 := cleanHosts(in.Blocked)
if !ok1 || !ok2 {
bad()
return
}
st := &db.GroupSettings{
ChatID: g.ChatID, Enabled: in.Enabled, AutoDetect: in.AutoDetect, DeleteCmds: in.DeleteCmds,
WhoCanUse: in.WhoCanUse, SpendRule: in.SpendRule, SpendCap: in.SpendCap, DailyCap: in.DailyCap,
MaxSizeMB: in.MaxSizeMB, MaxDuration: in.MaxDuration, Quality: in.Quality, Lang: in.Lang,
Allowed: allowed, Blocked: blocked,
}
old, _ := m.Store.GetGroupSettings(r.Context(), g.ChatID)
if err := m.Store.SaveGroupSettings(r.Context(), st); err != nil {
m.explain(w, s, err)
return
}
if old != nil && old.Lang != st.Lang {
m.Bot.SyncGroupMenu(r.Context(), g.ChatID, st.Lang)
}
m.Log.Info("group settings changed in the mini app", "chat_id", g.ChatID, "by", s.user.ID)
m.ok(w, map[string]any{"settings": toSettingsJSON(st)})
}
func (m *MiniApp) groupUsage(w http.ResponseWriter, r *http.Request, s *session) {
g, ok := m.adminGroup(w, r, s)
if !ok {
return
}
since := service.Day(m.Now().AddDate(0, 0, -6))
usage, err := m.Store.GroupUsage(r.Context(), g.ChatID, since, 100)
if err != nil {
m.explain(w, s, err)
return
}
type row struct {
Name string `json:"name"`
Downloads int64 `json:"downloads"`
Sats int64 `json:"sats"`
Bytes int64 `json:"bytes"`
}
rows := []row{}
for _, u := range usage {
name := u.Name
if name == "" {
name = strconv.FormatInt(u.UserID, 10)
}
rows = append(rows, row{Name: name, Downloads: u.Downloads, Sats: u.Sats, Bytes: u.Bytes})
}
m.ok(w, map[string]any{"days": 7, "members": rows})
}