diff --git a/.env.example b/.env.example index b50cc94..a6045b0 100644 --- a/.env.example +++ b/.env.example @@ -218,6 +218,14 @@ REFERRAL_REWARD_SATS=200 # and are paid on a later day. 0 means no cap. REFERRAL_DAILY_CAP=2000 +# --- Telegram Stars --------------------------------------------------------------- +# Offer Telegram Stars as a second way to pay for passes and credit packs, +# next to Lightning. Needs nothing in @BotFather. Stars prices are set on +# their own, never converted from sats; a product without a price is not +# sold for Stars. Keys: pass_day, pass_week, pass_month, credits_. +STARS_ENABLED=false +STARS_PRICES=pass_day=50,pass_week=200,pass_month=600,credits_1000=70,credits_5000=330,credits_20000=1300 + # --- Rate limits ------------------------------------------------------------ # Links per minute. 0 means no limit. RATE_USER_PER_MINUTE=10 diff --git a/config.example.toml b/config.example.toml index ad53836..7f32888 100644 --- a/config.example.toml +++ b/config.example.toml @@ -31,6 +31,11 @@ caption_attribution = true referral_reward_sats = 200 referral_daily_cap = 2000 +# Telegram Stars as a second way to pay, next to Lightning. Prices in Stars +# are set here, never converted from sats. A product without a price is not +# sold for Stars. +stars_enabled = false + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook @@ -142,3 +147,11 @@ group_per_minute = 30 [log] level = "info" format = "json" + +[stars_prices] +pass_day = 50 +pass_week = 200 +pass_month = 600 +credits_1000 = 70 +credits_5000 = 330 +credits_20000 = 1300 diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 1d45e5b..cdf44c7 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -1070,3 +1070,68 @@ the affiliate program. What was found and planned is in link (a `copy_text` button) and QR code (a PNG sent in the chat). The Mini App Me page shows the same numbers, copy and share, and the QR code as an image in the profile response. + +### Phase 4: Telegram Stars payments + +- **Where the prices live.** "A separate config table (stars_prices)" is + read as a configuration table: `[stars_prices]` in the TOML file, or + `STARS_PRICES="pass_day=50,credits_1000=70"`. It is not a database + table. Keys are `pass_day`, `pass_week`, `pass_month` and + `credits_`, one per credit pack. A product without a price is + not sold for Stars; nothing is converted from sats. The defaults + (50, 200, 600; 70, 330, 1300) are placeholders for the owner to set. + `STARS_ENABLED` is off by default, so existing setups keep working + unchanged. +- **What Stars buy.** Stars buy passes and credit packs, for the user's + own wallet. Stars purchases from the Mini App can also be for a group. + Skipping the queue, one-off payments for a single file, donations and + group top-ups from the chat stay Lightning only. One-off prices depend + on the file size, and a fixed Stars price per size step was not asked + for. +- **How it is paid.** + - The invoice uses currency XTR, an empty provider token and exactly + one price, with payload `dlp:`. + - The pre-checkout answer checks that the payload belongs to this payer + and is still pending, and that currency and amount match. + - `successful_payment` settles through the same transaction as + Lightning, so a pass or credits are granted exactly the same way and + the follow-up (the download behind an over-limit offer) runs the + same way. + - The `telegram_payment_charge_id` is stored under a unique index, so + a repeated event settles nothing twice. + - A Stars purchase gets a placeholder payment hash (`stars:`) and + is never sent to LNbits, by the poll or by "Check payment". +- **The books.** `purchases.payment_method` and `ledger.payment_method` + (migration 00009) say lightning or stars; older rows are lightning. + `purchases.amount_sats` of a Stars purchase is the sats value of what + it bought: the credit pack, or the pass's Lightning price. + `stars_amount` is what was paid in Stars. /stats shows revenue per + method: sats for Lightning, Stars for Stars, refunds counted apart. +- **Refunds.** + - `/refund ` calls `refundStarPayment` and + then takes back what the purchase granted: credits as far as they + are left, or the pass. Passes stacked after a refunded pass move up + by its length. + - The old `/refund ` form still gives sats back. + - A `refunded_payment` message from Telegram (for example after the + owner's refund) undoes the purchase too. That only happens once. + - A payment that cannot be matched to an order is logged with its + charge ID, so the owner can refund it. +- **A failed download after a Stars payment** follows the Lightning + policy unchanged. The scheduler retries a job once. What a download + charged is given back when it finally fails. A pass that was bought + stays, and a pass bought for a download that can no longer start stays + too. No extension of the pass was added, since Lightning has none. +- **In the chat.** The buy screen, /credits and /account show the + Lightning buttons first and a "Pay with Stars" button that switches the + message to Stars prices and back. The over-limit offer adds a Stars + button that shows the Stars passes in a message of their own. Once + paid, a new message confirms the payment, because Telegram's invoice + message cannot be edited into "paid". +- **In the Mini App**, Buy has a Lightning and Stars switch. A Stars + purchase returns an invoice link (`createInvoiceLink`), which the app + opens with `WebApp.openInvoice`. The status the app gets back only + closes or keeps the view. The app learns about the payment by asking + the core, which settles it from Telegram's `successful_payment` update. +- `pre_checkout_query` was added to the update types the bot asks + Telegram for. diff --git a/docs/SCREENS.md b/docs/SCREENS.md index 838523d..b251b6a 100644 --- a/docs/SCREENS.md +++ b/docs/SCREENS.md @@ -145,14 +145,6 @@ Downloading… editMessageText -``` -Test Video -Sending it to Telegram… -[Cancel] -``` - -editMessageText - ``` Test Video Sending it to Telegram… @@ -362,7 +354,7 @@ editMessageText Share your link. When somebody you invited pays for a first purchase in sats (Lightning), you get 200 sats in credits. -https://t.me/nr_dl_test_bot?start=rf_CW5AYJM3 +https://t.me/nr_dl_test_bot?start=rf_YY6OJU6T Invited: 0 · Bought something: 0 Earned: 0 sats · Waiting: 0 sats @@ -553,6 +545,7 @@ Downloads: 4 of 5 Volume: 4 KB of 250 MB [Day pass · 700 sats] [Week pass · 3,000 sats] [Month pass · 9,000 sats] +[⭐ Pay with Stars] ``` sendMessage @@ -574,7 +567,7 @@ sendMessage Share your link. When somebody you invited pays for a first purchase in sats (Lightning), you get 200 sats in credits. -https://t.me/nr_dl_test_bot?start=rf_CW5AYJM3 +https://t.me/nr_dl_test_bot?start=rf_YY6OJU6T Invited: 0 · Bought something: 0 Earned: 0 sats · Waiting: 0 sats @@ -597,6 +590,7 @@ You pay in sats over Lightning. [Day pass · 700 sats] [Week pass · 3,000 sats] [Month pass · 9,000 sats] [1,000 sats] [5,000 sats] [20,000 sats] +[⭐ Pay with Stars] ``` sendMessage @@ -606,6 +600,7 @@ sendMessage One download costs 50 sats. Top up: [1,000 sats] [5,000 sats] [20,000 sats] +[⭐ Pay with Stars] ``` sendMessage @@ -862,6 +857,7 @@ You pay in sats over Lightning. [Day pass · 700 sats] [Week pass · 3,000 sats] [Month pass · 9,000 sats] [1,000 sats] [5,000 sats] [20,000 sats] +[⭐ Pay with Stars] ``` sendPhoto @@ -869,13 +865,40 @@ sendPhoto ``` Day pass · 700 sats -lnbc7000n1fake932bb5fc424d32f8967f5a103ec1aa9b323d60cf969ac292033fe465b6058e60 +lnbc7000n1fakee38a3d34236055a47c726ecb0a1c30d15a717a59fccef6acb0cff8dcb7dc200f Scan the code or tap the invoice to copy it. Valid for 10 minutes. [Open in wallet] [Check payment] [Cancel] ``` +editMessageText + +``` +Pay with Telegram Stars +The same passes and credits, paid from your Stars balance in Telegram. +[Day pass · ⭐ 50] [Week pass · ⭐ 200] +[Month pass · ⭐ 600] +[1,000 sats · ⭐ 70] [5,000 sats · ⭐ 330] [20,000 sats · ⭐ 1,300] +[⚡ Pay with Lightning] +``` + +editMessageText + +``` +Passes and credits + +A pass lifts your limits to 1.95 GB and 3 hours per download and puts you in the priority queue for as long as it runs. + +Credits pay per download, 50 sats each, with the same limits and priority. They never expire. + +You pay in sats over Lightning. +[Day pass · 700 sats] [Week pass · 3,000 sats] +[Month pass · 9,000 sats] +[1,000 sats] [5,000 sats] [20,000 sats] +[⭐ Pay with Stars] +``` + ## es sendMessage @@ -1234,7 +1257,7 @@ editMessageText Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes 200 sats en créditos. -https://t.me/nr_dl_test_bot?start=rf_MXZGYTEK +https://t.me/nr_dl_test_bot?start=rf_Q3U2NIQH Invitados: 0 · Compraron algo: 0 Ganado: 0 sats · En espera: 0 sats @@ -1425,6 +1448,7 @@ Descargas: 4 de 5 Volumen: 4 KB de 250 MB [Pase de un día · 700 sats] [Pase semanal · 3.000 sats] [Pase mensual · 9.000 sats] +[⭐ Pagar con Estrellas] ``` sendMessage @@ -1446,7 +1470,7 @@ sendMessage Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes 200 sats en créditos. -https://t.me/nr_dl_test_bot?start=rf_MXZGYTEK +https://t.me/nr_dl_test_bot?start=rf_Q3U2NIQH Invitados: 0 · Compraron algo: 0 Ganado: 0 sats · En espera: 0 sats @@ -1469,6 +1493,7 @@ Pagas en sats por Lightning. [Pase de un día · 700 sats] [Pase semanal · 3.000 sats] [Pase mensual · 9.000 sats] [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Pagar con Estrellas] ``` sendMessage @@ -1478,6 +1503,7 @@ sendMessage Una descarga cuesta 50 sats. Carga saldo: [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Pagar con Estrellas] ``` sendMessage @@ -1734,6 +1760,7 @@ Pagas en sats por Lightning. [Pase de un día · 700 sats] [Pase semanal · 3.000 sats] [Pase mensual · 9.000 sats] [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Pagar con Estrellas] ``` sendPhoto @@ -1741,13 +1768,40 @@ sendPhoto ``` Pase de un día · 700 sats -lnbc7000n1fake5bb91054d0d2b0cbcc9f5394928a595cf2ccba08d4a09432f7db5063c88ffd85 +lnbc7000n1fake7bf3f553278730f9f02e2e8e66bb1524a1efc083ab3bfe31c83c00e15d64e033 Escanea el código o toca la factura para copiarla. Vale por 10 minutos. [Abrir en la billetera] [Verificar el pago] [Cancelar] ``` +editMessageText + +``` +Pagar con Estrellas de Telegram +Los mismos pases y créditos, pagados con tu saldo de Estrellas en Telegram. +[Pase de un día · ⭐ 50] [Pase semanal · ⭐ 200] +[Pase mensual · ⭐ 600] +[1.000 sats · ⭐ 70] [5.000 sats · ⭐ 330] [20.000 sats · ⭐ 1.300] +[⚡ Pagar con Lightning] +``` + +editMessageText + +``` +Pases y créditos + +Un pase sube tus límites a 1,95 GB y 3 horas por descarga y te pone en la fila prioritaria mientras dure. + +Los créditos pagan por descarga, 50 sats cada una, con los mismos límites y la misma prioridad. No vencen nunca. + +Pagas en sats por Lightning. +[Pase de un día · 700 sats] [Pase semanal · 3.000 sats] +[Pase mensual · 9.000 sats] +[1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Pagar con Estrellas] +``` + ## nl sendMessage @@ -1827,7 +1881,7 @@ editMessageText ``` Test Video -Downloaden… +Naar Telegram sturen… [Annuleren] ``` @@ -1835,7 +1889,7 @@ editMessageText ``` Test Video -Naar Telegram sturen… +Downloaden… [Annuleren] ``` @@ -2106,7 +2160,7 @@ editMessageText Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij 200 sats aan tegoed. -https://t.me/nr_dl_test_bot?start=rf_4VIFLSDC +https://t.me/nr_dl_test_bot?start=rf_TXUCNI2E Uitgenodigd: 0 · Iets gekocht: 0 Verdiend: 0 sats · Wacht nog: 0 sats @@ -2297,6 +2351,7 @@ Downloads: 4 van 5 Volume: 4 KB van 250 MB [Dagpas · 700 sats] [Weekpas · 3.000 sats] [Maandpas · 9.000 sats] +[⭐ Betalen met Stars] ``` sendMessage @@ -2318,7 +2373,7 @@ sendMessage Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij 200 sats aan tegoed. -https://t.me/nr_dl_test_bot?start=rf_4VIFLSDC +https://t.me/nr_dl_test_bot?start=rf_TXUCNI2E Uitgenodigd: 0 · Iets gekocht: 0 Verdiend: 0 sats · Wacht nog: 0 sats @@ -2341,6 +2396,7 @@ Je betaalt in sats via Lightning. [Dagpas · 700 sats] [Weekpas · 3.000 sats] [Maandpas · 9.000 sats] [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Betalen met Stars] ``` sendMessage @@ -2350,6 +2406,7 @@ sendMessage Eén download kost 50 sats. Opwaarderen: [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Betalen met Stars] ``` sendMessage @@ -2606,6 +2663,7 @@ Je betaalt in sats via Lightning. [Dagpas · 700 sats] [Weekpas · 3.000 sats] [Maandpas · 9.000 sats] [1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Betalen met Stars] ``` sendPhoto @@ -2613,9 +2671,36 @@ sendPhoto ``` Dagpas · 700 sats -lnbc7000n1fake2279497394e085369465914011a009430187243aabd22a7b3642440c8ec67831 +lnbc7000n1fake5443af8ff471a30e71eaa1ee0db07d5d314f447f88f895369ea8892d717b5879 Scan de code of tik op de factuur om hem te kopiëren. Geldig voor 10 minuten. [Openen in wallet] [Betaling controleren] [Annuleren] ``` + +editMessageText + +``` +Betalen met Telegram Stars +Dezelfde passen en hetzelfde tegoed, betaald met je Stars-saldo in Telegram. +[Dagpas · ⭐ 50] [Weekpas · ⭐ 200] +[Maandpas · ⭐ 600] +[1.000 sats · ⭐ 70] [5.000 sats · ⭐ 330] [20.000 sats · ⭐ 1.300] +[⚡ Betalen met Lightning] +``` + +editMessageText + +``` +Passen en tegoed + +Een pas verhoogt je limieten naar 1,95 GB en 3 uur per download en zet je in de voorrangswachtrij zolang hij loopt. + +Tegoed betaalt per download, 50 sats per stuk, met dezelfde limieten en voorrang. Het verloopt nooit. + +Je betaalt in sats via Lightning. +[Dagpas · 700 sats] [Weekpas · 3.000 sats] +[Maandpas · 9.000 sats] +[1.000 sats] [5.000 sats] [20.000 sats] +[⭐ Betalen met Stars] +``` diff --git a/internal/api/miniapp.go b/internal/api/miniapp.go index 547dd14..e478c60 100644 --- a/internal/api/miniapp.go +++ b/internal/api/miniapp.go @@ -491,13 +491,26 @@ func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) { 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.Enabled(), + "enabled": m.Billing.Selling(), + "lightning": m.Billing.Enabled(), + "stars": m.Billing.StarsEnabled(), "passes": []map[string]any{ - {"product": billing.ProductPassDay, "price": p.PassDay}, - {"product": billing.ProductPassWeek, "price": p.PassWeek}, - {"product": billing.ProductPassMonth, "price": p.PassMonth}, + {"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}, @@ -510,9 +523,9 @@ func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) { 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, + "expires_at": p.ExpiresAt, "paid_at": p.PaidAt, "method": p.PaymentMethod, "stars": p.StarsAmount, } - if withInvoice && p.Status == db.PurchasePending { + 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) @@ -526,6 +539,8 @@ func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) { 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", "") @@ -548,6 +563,17 @@ func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) { } 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) diff --git a/internal/app/app.go b/internal/app/app.go index 883fb6b..dd6134a 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -371,7 +371,7 @@ func New(ctx context.Context, opts Options) (*App, error) { } // allowedUpdates is the list of update types the bot asks Telegram for. -var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query"} +var allowedUpdates = []string{"message", "callback_query", "my_chat_member", "widget_query", "pre_checkout_query"} // Run starts every loop and blocks until ctx ends. Shutdown is ordered: // updates stop first, then the worker hands back its jobs, then the diff --git a/internal/app/flow_test.go b/internal/app/flow_test.go index 7c5965b..d546854 100644 --- a/internal/app/flow_test.go +++ b/internal/app/flow_test.go @@ -223,6 +223,13 @@ func tour(t *testing.T, h *moneyHarness, user int64, lang string) { buy := h.wait(seq, "sendMessage", inChat) seq = pressOn(buy, "by:pass_day") h.wait(seq, "sendPhoto", inChat) + // The same in Stars, and its invoice. + seq = pressOn(buy, "sm") + stars := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID }) + seq = pressOn(stars, "sb:pass_day") + h.wait(seq, "sendInvoice", inChat) + seq = pressOn(stars, "lm") + h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID }) } // Links of the tour with scripted outcomes. @@ -263,7 +270,7 @@ func TestEveryScreenInSpanishAndDutch(t *testing.T) { t.Run(lang, func(t *testing.T) { // A missing message or a fallback to English is logged as a bug, // which fails the test (see guardHandler). - h := startApp(t, tourFake(), nil) + h := startApp(t, tourFake(), withStars) const user = int64(501) tour(t, h, user, lang) if out != "" { diff --git a/internal/app/stars_test.go b/internal/app/stars_test.go new file mode 100644 index 0000000..a29f64d --- /dev/null +++ b/internal/app/stars_test.go @@ -0,0 +1,214 @@ +package app_test + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +func withStars(c *config.Config) { c.StarsEnabled = true } + +// invoiceOf reads the essentials of a sendInvoice or createInvoiceLink call. +func invoiceOf(t *testing.T, c fakeserver.Call) (payload string, total int) { + t.Helper() + var prices []struct { + Label string `json:"label"` + Amount int `json:"amount"` + } + if err := json.Unmarshal([]byte(c.Params["prices"]), &prices); err != nil || len(prices) != 1 { + t.Fatalf("a Stars invoice needs exactly one price: %s (%v)", c.Params["prices"], err) + } + if c.Params["currency"] != "XTR" || c.Params["provider_token"] != "" { + t.Fatalf("currency %q, provider token %q: want XTR and none", c.Params["currency"], c.Params["provider_token"]) + } + if n := len([]rune(c.Params["title"])); n < 1 || n > 32 { + t.Fatalf("title %q is %d characters", c.Params["title"], n) + } + return c.Params["payload"], prices[0].Amount +} + +// precheck sends a pre-checkout query and returns the bot's answer. +func (h *harness) precheck(user int64, payload, currency string, total int) fakeserver.Call { + h.t.Helper() + seq := h.srv.Seq() + id := h.srv.PushPreCheckout(user, payload, currency, total) + return h.wait(seq, "answerPreCheckoutQuery", func(c fakeserver.Call) bool { return c.Params["pre_checkout_query_id"] == id }) +} + +func TestStarsPurchaseInTheChat(t *testing.T) { + const owner = int64(900) + h := startMoney(t, nil, func(c *config.Config) { + withStars(c) + c.Owners = []int64{owner} + }) + ctx := context.Background() + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/buy") + buy := h.wait(seq, "sendMessage", textHas("Passes and credits")) + // Lightning first, Stars one tap away. + if got := labels(buy); !strings.HasPrefix(got, "Day pass · 700 sats") || !strings.HasSuffix(got, "⭐ Pay with Stars") { + t.Fatalf("buy buttons = %q", got) + } + seq = h.press(alice, alice, buy, "sm") + menu := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == buy.MessageID }) + if got := labels(menu); got != "Day pass · ⭐ 50 | Week pass · ⭐ 200 | Month pass · ⭐ 600 | 1,000 sats · ⭐ 70 | 5,000 sats · ⭐ 330 | 20,000 sats · ⭐ 1,300 | ⚡ Pay with Lightning" { + t.Fatalf("stars buttons = %q", got) + } + seq = h.press(alice, alice, menu, "sb:pass_week") + inv := h.wait(seq, "sendInvoice", nil) + payload, total := invoiceOf(t, inv) + if total != 200 || !strings.HasPrefix(payload, "dlp:") || inv.ChatID() != alice { + t.Fatalf("invoice: payload %q, total %d, chat %d", payload, total, inv.ChatID()) + } + if n, _ := h.ln.Calls(); n != 0 { + t.Fatal("a Stars invoice created a Lightning invoice") + } + + // Pre-checkout: only the exact order passes. + if a := h.precheck(alice, payload, "XTR", 199); a.Params["ok"] != "false" || a.Params["error_message"] == "" { + t.Fatalf("wrong amount answered %+v", a.Params) + } + if a := h.precheck(bob, payload, "XTR", 200); a.Params["ok"] != "false" { + t.Fatalf("another payer answered %+v", a.Params) + } + if a := h.precheck(alice, payload, "XTR", 200); a.Params["ok"] != "true" { + t.Fatalf("the right order answered %+v", a.Params) + } + + // The payment, then the same event again: one pass, one confirmation. + seq = h.srv.Seq() + h.srv.PushSuccessfulPayment(alice, payload, "XTR", 200, "tg-charge-1") + h.wait(seq, "sendMessage", textHas("Paid.")) + st, _ := h.app.Billing.State(ctx, db.OwnerUser, alice) + if st.PassUntil == 0 { + t.Fatal("no pass after the Stars payment") + } + seq = h.srv.Seq() + h.srv.PushSuccessfulPayment(alice, payload, "XTR", 200, "tg-charge-1") + h.never(seq, "sendMessage", textHas("Paid.")) + if again, _ := h.app.Billing.State(ctx, db.OwnerUser, alice); again.PassUntil != st.PassUntil { + t.Fatal("a repeated payment event extended the pass") + } + + // Revenue by method for the owner. + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/stats") + stats := h.wait(seq, "sendMessage", textHas("Revenue")) + if !strings.Contains(stats.Text(), "Stars: 200 Stars from 1 purchase, 0 refunded") { + t.Fatalf("stats = %q", stats.Text()) + } + + // The owner refunds it: Telegram returns the Stars, the pass goes. + p, err := h.app.Store.GetPurchaseByCharge(ctx, "tg-charge-1") + if err != nil { + t.Fatal(err) + } + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/refund "+p.ID) + refund := h.wait(seq, "refundStarPayment", nil) + if refund.Params["user_id"] != "42" || refund.Params["telegram_payment_charge_id"] != "tg-charge-1" { + t.Fatalf("refundStarPayment = %+v", refund.Params) + } + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "refunded") }) + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner && strings.Contains(c.Text(), "Refunded 200 Stars") }) + if st, _ := h.app.Billing.State(ctx, db.OwnerUser, alice); st.PassUntil != 0 { + t.Fatal("the refunded pass is still active") + } + // Telegram's own refund message for it changes nothing more. + seq = h.srv.Seq() + h.srv.PushRefundedPayment(alice, payload, 200, "tg-charge-1") + h.never(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + // A refunded purchase is not refunded twice. + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/refund tg-charge-1") + h.wait(seq, "sendMessage", textHas("cannot be refunded")) + if n := len(h.srv.Calls("refundStarPayment")); n != 1 { + t.Fatalf("refundStarPayment called %d times", n) + } + // The old /refund still gives sats back. + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/refund 42 300") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner }) + if got := h.balance(alice); got != 300 { + t.Fatalf("balance after a sats refund = %d", got) + } + h.booksBalance() +} + +func TestStarsPassForAnOverLimitDownload(t *testing.T) { + h := startMoney(t, &ytdlptest.Fake{FileSize: 4096}, withStars) + card := h.card(alice, alice, bigLink) + seq := h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", textHas("You can lift the limit")) + // Lightning first; Stars below it. + if got := labels(offer); !strings.HasPrefix(got, "Day pass · 700 sats") || !strings.Contains(got, "⭐ Pay with Stars") { + t.Fatalf("offer buttons = %q", got) + } + seq = h.press(alice, alice, offer, "so:") + stars := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("sv:"); return ok }) + seq = h.press(alice, alice, stars, "sv:pass_day") + payload, total := invoiceOf(t, h.wait(seq, "sendInvoice", nil)) + if total != 50 { + t.Fatalf("day pass costs %d Stars", total) + } + if n := len(h.fake.Downloads()); n != 0 { + t.Fatal("downloaded before payment") + } + h.precheck(alice, payload, "XTR", 50) + seq = h.srv.Seq() + h.srv.PushSuccessfulPayment(alice, payload, "XTR", 50, "tg-charge-9") + // The download it was for starts, like after a Lightning payment. + h.finished(seq, alice) + sent := h.waitSent(alice, 1) + if sent[0].Source != "own_pass" { + t.Fatalf("delivery source = %q, want own_pass", sent[0].Source) + } +} + +func TestMiniAppStarsPurchase(t *testing.T) { + h := startApp(t, nil, withStars) + products := h.must(alice, "GET", "products", nil) + if products.Body["stars"] != true || products.Body["lightning"] != true { + t.Fatalf("products = %s", products.Raw) + } + if packs := products.list("stars_packs"); len(packs) != 3 || packs[0]["stars"] != float64(70) { + t.Fatalf("stars packs = %v", packs) + } + seq := h.srv.Seq() + p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 5000, "method": "stars"}) + if p.str("method") != "stars" || p.num("stars") != 330 || p.str("status") != "pending" || + !strings.HasPrefix(p.str("invoice_link"), "https://t.me/$fake_invoice") || p.str("bolt11") != "" { + t.Fatalf("purchase = %s", p.Raw) + } + link := h.wait(seq, "createInvoiceLink", nil) + payload, total := invoiceOf(t, link) + if total != 330 { + t.Fatalf("invoice link total = %d", total) + } + // A pack without a Stars price is not sold for Stars. + h.refused(h.call(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 1234, "method": "stars"}), 422, "bad_amount") + + // The payment arrives as a Telegram update; the app sees it on its next poll. + h.precheck(alice, payload, "XTR", 330) + h.srv.PushSuccessfulPayment(alice, payload, "XTR", 330, "tg-charge-app") + id := p.str("id") + for i := 0; ; i++ { + if st := h.must(alice, "GET", "purchase/"+id, nil); st.str("status") == "paid" { + break + } + if i > 200 { + t.Fatal("the purchase never showed as paid") + } + time.Sleep(20 * time.Millisecond) + } + if got := h.balance(alice); got != 5000 { + t.Fatalf("balance = %d", got) + } +} diff --git a/internal/billing/billing.go b/internal/billing/billing.go index b78ee40..c809468 100644 --- a/internal/billing/billing.go +++ b/internal/billing/billing.go @@ -196,26 +196,26 @@ func (b *Billing) State(ctx context.Context, ownerType string, ownerID int64) (e // Credit adds sats to a wallet. The dedupe key makes it idempotent. func (b *Billing) Credit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) { - return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor) + return b.move(ctx, db.LedgerCredit, walletID, sats, reason, ref, dedupe, actor, "") } // Debit takes sats from a wallet, or fails with db.ErrInsufficient. func (b *Billing) Debit(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) { - return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor) + return b.move(ctx, db.LedgerDebit, walletID, sats, reason, ref, dedupe, actor, "") } // Refund gives sats back to a wallet. func (b *Billing) Refund(ctx context.Context, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) { - return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor) + return b.move(ctx, db.LedgerRefund, walletID, sats, reason, ref, dedupe, actor, "") } -func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64) (bool, error) { +func (b *Billing) move(ctx context.Context, kind, walletID string, sats int64, reason, ref, dedupe string, actor int64, method string) (bool, error) { var applied bool err := b.store.InTx(ctx, func(tx *db.Store) error { var err error applied, err = tx.AddLedger(ctx, &db.LedgerEntry{ WalletID: walletID, Kind: kind, Amount: sats, Reason: reason, Ref: ref, - DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(), + DedupeKey: dedupe, ActorID: actor, CreatedAt: b.nowMilli(), PaymentMethod: method, }) return err }) @@ -390,7 +390,9 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (* if p.UserID != userID { return nil, ErrNotOwner } - if p.Status != db.PurchasePaid { + if p.Status != db.PurchasePaid && p.PaymentMethod != db.PayStars { + // A Stars payment arrives as a Telegram update; there is nothing + // to ask LNbits about. if _, err := b.checkOne(ctx, p); err != nil { return nil, err } @@ -400,7 +402,7 @@ func (b *Billing) Check(ctx context.Context, purchaseID string, userID int64) (* // checkOne confirms a purchase with LNbits and settles or expires it. func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, err error) { - if p.Status == db.PurchasePaid { + if p.Status == db.PurchasePaid || p.PaymentMethod == db.PayStars { return false, nil } if b.ln == nil { @@ -442,6 +444,13 @@ func (b *Billing) checkOne(ctx context.Context, p *db.Purchase) (settled bool, e // transaction. It is idempotent: the second and later calls return false // and change nothing. Callers must have confirmed the payment. func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) { + settled, _, err := b.settle(ctx, purchaseID, nil) + return settled, err +} + +// settle is Settle with a step of its own inside the transaction, run once +// the purchase is marked paid: a Stars payment records its charge ID there. +func (b *Billing) settle(ctx context.Context, purchaseID string, inTx func(tx *db.Store) error) (bool, *db.Purchase, error) { var ( settled bool p *db.Purchase @@ -452,6 +461,11 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) { if err != nil || !won { return err } + if inTx != nil { + if err := inTx(tx); err != nil { + return err + } + } if p, err = tx.GetPurchase(ctx, purchaseID); err != nil { return err } @@ -460,6 +474,7 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) { if _, err := tx.AddLedger(ctx, &db.LedgerEntry{ WalletID: p.WalletID, Kind: db.LedgerCredit, Amount: p.AmountSats, Reason: "purchase", Ref: p.ID, DedupeKey: "purchase:" + p.ID, ActorID: p.UserID, CreatedAt: now, + PaymentMethod: p.PaymentMethod, }); err != nil { return err } @@ -483,18 +498,18 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) { return nil }) if errors.Is(err, db.ErrDuplicate) { - return false, nil // another connection settled it first + return false, nil, nil // another connection settled it first } if err != nil || !settled { - return false, err + return false, nil, err } b.mu.Lock() b.stats.InvoicesSettled++ b.mu.Unlock() b.log.Info("invoice settled", "purchase_id", p.ID, "product", p.Product, "sats", p.AmountSats, - "user_id", p.UserID, "wallet_id", p.WalletID) + "stars", p.StarsAmount, "method", p.PaymentMethod, "user_id", p.UserID, "wallet_id", p.WalletID) b.emit(EventPaid, p) - return true, nil + return true, p, nil } // rewardReferrer pays the inviter of a user who settled their first @@ -544,7 +559,9 @@ func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purcha // countsForReferral reports whether a purchase was paid in a way our // referral program rewards: Lightning. -func countsForReferral(p *db.Purchase) bool { return true } +func countsForReferral(p *db.Purchase) bool { + return p.PaymentMethod == db.PayLightning || p.PaymentMethod == "" +} // underCap reports whether an inviter may be paid amount more today. func (b *Billing) underCap(ctx context.Context, tx *db.Store, referrer int64, day int, amount int64) (bool, error) { @@ -642,7 +659,7 @@ func (b *Billing) ConvertToCredits(ctx context.Context, p *db.Purchase) (bool, e if err != nil { return false, err } - return b.Credit(ctx, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID) + return b.move(ctx, db.LedgerCredit, w.ID, p.AmountSats, "purchase_fallback", p.ID, "purchase-fallback:"+p.ID, p.UserID, p.PaymentMethod) } // --- reconciliation -------------------------------------------------------- diff --git a/internal/billing/stars.go b/internal/billing/stars.go new file mode 100644 index 0000000..aa8722e --- /dev/null +++ b/internal/billing/stars.go @@ -0,0 +1,206 @@ +package billing + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/ids" +) + +// Telegram Stars are the second way to pay, next to Lightning, for passes +// and credit packs. Their prices are set on their own (StarsPrices), never +// converted from sats. A Stars purchase grants exactly what the same +// Lightning purchase grants, through the same settlement, so entitlement +// does not care how something was paid. +// +// The flow is Telegram's: the bot sends an invoice in XTR (or makes an +// invoice link for the Mini App), Telegram asks the bot to confirm with a +// pre-checkout query, takes the Stars, and sends a message with a +// successful_payment. Its telegram_payment_charge_id is stored with the +// purchase under a unique index, so a repeated event settles nothing twice. + +// Errors of Stars payments. +var ( + ErrStarsOff = errors.New("billing: stars payments are off") + ErrNotForStars = errors.New("billing: this is not sold for stars") + ErrStarsMismatch = errors.New("billing: the payment does not match the invoice") + ErrInvoiceClosed = errors.New("billing: the invoice is closed") + ErrUnknownCharge = errors.New("billing: unknown payment") +) + +// StarsPayloadPrefix starts the invoice payload of a Stars purchase. +const StarsPayloadPrefix = "dlp:" + +// starsInvoiceLife is how long a Stars purchase is shown as open. Telegram +// invoices do not expire, so a payment that comes later still settles. +const starsInvoiceLife = 24 * time.Hour + +// StarsEnabled reports whether Stars are offered. +func (b *Billing) StarsEnabled() bool { return b.cfg.StarsEnabled } + +// Selling reports whether anything can be bought, by either method. +func (b *Billing) Selling() bool { return b.Enabled() || b.StarsEnabled() } + +// StarsPrice returns the price in Stars of a product, or false when it is +// not sold for Stars. +func (b *Billing) StarsPrice(product string, amount int64) (int64, bool) { + if !b.StarsEnabled() { + return 0, false + } + switch { + case passKind(product) != "": + return b.cfg.StarsPrice(product, 0) + case product == ProductCredits: + return b.cfg.StarsPrice(product, amount) + } + return 0, false +} + +// StarsPayload is the invoice payload of a Stars purchase. +func StarsPayload(p *db.Purchase) string { return StarsPayloadPrefix + p.ID } + +// CreateStarsPurchase records a purchase to be paid in Stars. The caller +// sends the invoice. amount_sats keeps the sats value of what is bought: +// the credit pack, or the pass's Lightning price, for the books. +func (b *Billing) CreateStarsPurchase(ctx context.Context, np NewPurchase) (*db.Purchase, error) { + if !b.StarsEnabled() { + return nil, ErrStarsOff + } + stars, ok := b.StarsPrice(np.Product, np.Amount) + if !ok { + return nil, ErrNotForStars + } + sats, err := b.Price(np.Product, np.Amount) + if err != nil { + return nil, err + } + now := b.nowMilli() + id := ids.New() + p := &db.Purchase{ + ID: id, UserID: np.UserID, WalletID: np.WalletID, Product: np.Product, AmountSats: sats, + Status: db.PurchasePending, PaymentHash: "stars:" + id, Lang: np.Lang, + RequestID: np.RequestID, Profile: np.Profile, DeliveryID: np.DeliveryID, + CreatedAt: now, ExpiresAt: now + starsInvoiceLife.Milliseconds(), + PaymentMethod: db.PayStars, StarsAmount: stars, + } + if err := b.store.InsertPurchase(ctx, p); err != nil { + return nil, err + } + b.log.Info("stars invoice created", "purchase_id", p.ID, "product", p.Product, "stars", stars, "user_id", np.UserID) + return p, nil +} + +// starsPurchase finds the purchase an invoice payload names, for its payer. +func (b *Billing) starsPurchase(ctx context.Context, payload string, userID int64) (*db.Purchase, error) { + id, ok := strings.CutPrefix(payload, StarsPayloadPrefix) + if !ok { + return nil, ErrUnknownCharge + } + p, err := b.store.GetPurchase(ctx, id) + if errors.Is(err, db.ErrNotFound) { + return nil, ErrUnknownCharge + } + if err != nil { + return nil, err + } + if p.PaymentMethod != db.PayStars || p.UserID != userID { + return nil, ErrUnknownCharge + } + return p, nil +} + +// PreCheckStars decides a pre-checkout query: Telegram is about to take +// the Stars and asks whether the order still stands. +func (b *Billing) PreCheckStars(ctx context.Context, payload string, userID int64, currency string, total int64) error { + p, err := b.starsPurchase(ctx, payload, userID) + if err != nil { + return err + } + if currency != "XTR" || total != p.StarsAmount { + return ErrStarsMismatch + } + if p.Status != db.PurchasePending { + return ErrInvoiceClosed + } + return nil +} + +// SettleStars settles a purchase from a successful_payment. The same +// payment arriving again changes nothing: settled is then false and the +// purchase is returned as it is. +func (b *Billing) SettleStars(ctx context.Context, payload, chargeID string, userID int64, currency string, total int64) (bool, *db.Purchase, error) { + if chargeID == "" { + return false, nil, ErrUnknownCharge + } + if p, err := b.store.GetPurchaseByCharge(ctx, chargeID); err == nil { + return false, p, nil // seen before + } + p, err := b.starsPurchase(ctx, payload, userID) + if err != nil { + return false, nil, err + } + if currency != "XTR" || total != p.StarsAmount { + b.log.Error("stars payment does not match its invoice", "purchase_id", p.ID, "currency", currency, + "total", total, "want", p.StarsAmount) + return false, p, ErrStarsMismatch + } + settled, paid, err := b.settle(ctx, p.ID, func(tx *db.Store) error { + return tx.SetPurchaseCharge(ctx, p.ID, chargeID) + }) + if err != nil { + return false, p, err + } + if !settled { + cur, err := b.store.GetPurchase(ctx, p.ID) + return false, cur, err + } + return true, paid, nil +} + +// UndoStarsPurchase takes back what a refunded Stars purchase granted: +// the credits (as far as they are left) or the pass. It is safe to call +// more than once; only the first call changes anything. The Stars +// themselves are returned by Telegram (refundStarPayment). +func (b *Billing) UndoStarsPurchase(ctx context.Context, purchaseID string) (bool, error) { + var undone bool + err := b.store.InTx(ctx, func(tx *db.Store) error { + now := b.nowMilli() + won, err := tx.MarkPurchaseRefunded(ctx, purchaseID, now) + if err != nil || !won { + return err + } + p, err := tx.GetPurchase(ctx, purchaseID) + if err != nil { + return err + } + switch { + case p.Product == ProductCredits: + w, err := tx.GetWallet(ctx, p.WalletID) + if err != nil { + return err + } + take := min(w.Balance, p.AmountSats) + if take > 0 { + if _, err := tx.AddLedger(ctx, &db.LedgerEntry{ + WalletID: p.WalletID, Kind: db.LedgerDebit, Amount: take, Reason: "stars_refund", + Ref: p.ID, DedupeKey: "stars-refund:" + p.ID, CreatedAt: now, PaymentMethod: db.PayStars, + }); err != nil { + return err + } + } + case passKind(p.Product) != "": + if _, err := tx.RemovePassesFrom(ctx, p.WalletID, p.ID); err != nil { + return err + } + } + undone = true + return nil + }) + if err == nil && undone { + b.log.Info("stars purchase refunded", "purchase_id", purchaseID) + } + return undone, err +} diff --git a/internal/billing/stars_test.go b/internal/billing/stars_test.go new file mode 100644 index 0000000..a157d49 --- /dev/null +++ b/internal/billing/stars_test.go @@ -0,0 +1,208 @@ +package billing_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" +) + +const bob = int64(43) + +func starsRig(t *testing.T) *rig { + t.Helper() + r := newRig(t) + r.cfg.StarsEnabled = true + r.b = r.newBilling() + return r +} + +func (r *rig) buyStars(user int64, product string, amount int64) *db.Purchase { + r.t.Helper() + p, err := r.b.CreateStarsPurchase(context.Background(), billing.NewPurchase{ + UserID: user, WalletID: r.wallet(user).ID, Product: product, Amount: amount, Lang: "en", + }) + if err != nil { + r.t.Fatalf("CreateStarsPurchase: %v", err) + } + return p +} + +func TestStarsPricesAreTheirOwn(t *testing.T) { + r := starsRig(t) + ctx := context.Background() + p := r.buyStars(alice, billing.ProductCredits, 5000) + if p.PaymentMethod != db.PayStars || p.StarsAmount != 330 || p.AmountSats != 5000 || p.Bolt11 != "" { + t.Fatalf("purchase = %+v", p) + } + // Only passes and credit packs with a configured price are sold. + for _, c := range []struct { + product string + amount int64 + }{{billing.ProductOneOff, 1000}, {billing.ProductDonation, 500}, {billing.ProductCredits, 1234}, {billing.ProductSkipQueue, 0}} { + _, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: c.product, Amount: c.amount}) + if !errors.Is(err, billing.ErrNotForStars) { + t.Errorf("%s %d: %v, want ErrNotForStars", c.product, c.amount, err) + } + } + // Off means off. + r.cfg.StarsEnabled = false + r.b = r.newBilling() + if _, err := r.b.CreateStarsPurchase(ctx, billing.NewPurchase{UserID: alice, WalletID: r.wallet(alice).ID, Product: billing.ProductPassDay}); !errors.Is(err, billing.ErrStarsOff) { + t.Fatalf("stars off: %v", err) + } + if creates, statuses := r.ln.Calls(); creates != 0 || statuses != 0 { + t.Fatalf("a Stars purchase talked to LNbits: %d creates, %d statuses", creates, statuses) + } +} + +func TestStarsPreCheckout(t *testing.T) { + r := starsRig(t) + ctx := context.Background() + p := r.buyStars(alice, billing.ProductPassDay, 0) + payload := billing.StarsPayload(p) + cases := []struct { + name string + payload string + user int64 + currency string + total int64 + want error + }{ + {"matches", payload, alice, "XTR", 50, nil}, + {"other amount", payload, alice, "XTR", 49, billing.ErrStarsMismatch}, + {"other currency", payload, alice, "USD", 50, billing.ErrStarsMismatch}, + {"other payer", payload, bob, "XTR", 50, billing.ErrUnknownCharge}, + {"unknown payload", "dlp:nope", alice, "XTR", 50, billing.ErrUnknownCharge}, + {"foreign payload", "something else", alice, "XTR", 50, billing.ErrUnknownCharge}, + } + for _, c := range cases { + if err := r.b.PreCheckStars(ctx, c.payload, c.user, c.currency, c.total); !errors.Is(err, c.want) { + t.Errorf("%s: %v, want %v", c.name, err, c.want) + } + } + // A cancelled invoice is not paid any more. + if _, err := r.b.Cancel(ctx, p.ID, alice); err != nil { + t.Fatal(err) + } + if err := r.b.PreCheckStars(ctx, payload, alice, "XTR", 50); !errors.Is(err, billing.ErrInvoiceClosed) { + t.Fatalf("cancelled: %v", err) + } +} + +func TestStarsPaymentGrantsTheSameAsLightningOnce(t *testing.T) { + r := starsRig(t) + ctx := context.Background() + // The same pass, once over Lightning (bob) and once in Stars (alice). + _ = r.ln.Pay(r.buy(bob, billing.ProductPassWeek, 0).PaymentHash) + p := r.buyStars(alice, billing.ProductPassWeek, 0) + settled, paid, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200) + if err != nil || !settled || paid.Status != db.PurchasePaid || paid.ChargeID != "charge-1" { + t.Fatalf("SettleStars = %v, %+v, %v", settled, paid, err) + } + stA, _ := r.b.State(ctx, db.OwnerUser, alice) + stB, _ := r.b.State(ctx, db.OwnerUser, bob) + if stA.PassUntil == 0 || stA.PassUntil != stB.PassUntil { + t.Fatalf("pass until: stars %d, lightning %d", stA.PassUntil, stB.PassUntil) + } + // The same payment event again, and again with the poll: nothing new. + for i := 0; i < 3; i++ { + again, cur, err := r.b.SettleStars(ctx, billing.StarsPayload(p), "charge-1", alice, "XTR", 200) + if err != nil || again || cur.ID != p.ID { + t.Fatalf("repeat %d: %v %+v %v", i, again, cur, err) + } + } + if n := r.count(billing.EventPaid); n != 2 { + t.Fatalf("%d paid events, want 2 (one per purchase)", n) + } + if _, err := r.b.Reconcile(ctx, time.Hour); err != nil { + t.Fatal(err) + } + if st, _ := r.b.State(ctx, db.OwnerUser, alice); st.PassUntil != stA.PassUntil { + t.Fatal("the pass was extended twice") + } + + // Credits: the pack's sats arrive in the wallet, marked as paid in Stars. + c := r.buyStars(alice, billing.ProductCredits, 1000) + if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(c), "charge-2", alice, "XTR", 70); err != nil { + t.Fatal(err) + } + if got := r.balance(alice); got != 1000 { + t.Fatalf("balance = %d", got) + } + if l := r.ledger(alice); len(l) == 0 || l[0].PaymentMethod != db.PayStars { + t.Fatalf("ledger = %+v", l) + } + // A payment that does not match its invoice is not settled. + m := r.buyStars(alice, billing.ProductCredits, 5000) + if _, _, err := r.b.SettleStars(ctx, billing.StarsPayload(m), "charge-3", alice, "XTR", 1); !errors.Is(err, billing.ErrStarsMismatch) { + t.Fatalf("mismatch: %v", err) + } + r.booksBalance() +} + +func TestStarsRefundUndoesThePurchase(t *testing.T) { + r := starsRig(t) + ctx := context.Background() + c := r.buyStars(alice, billing.ProductCredits, 1000) + _, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(c), "c1", alice, "XTR", 70) + pass := r.buyStars(alice, billing.ProductPassDay, 0) + _, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(pass), "c2", alice, "XTR", 50) + week := r.buyStars(alice, billing.ProductPassWeek, 0) + _, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(week), "c3", alice, "XTR", 200) + before, _ := r.b.State(ctx, db.OwnerUser, alice) + + // The day pass goes; the week pass stacked after it moves up a day. + if ok, err := r.b.UndoStarsPurchase(ctx, pass.ID); err != nil || !ok { + t.Fatalf("undo pass: %v %v", ok, err) + } + after, _ := r.b.State(ctx, db.OwnerUser, alice) + if got := before.PassUntil - after.PassUntil; got != (24 * time.Hour).Milliseconds() { + t.Fatalf("pass shortened by %d ms, want one day", got) + } + // Credits are taken back as far as they are left. + if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); !ok || r.balance(alice) != 0 { + t.Fatalf("balance after refund = %d", r.balance(alice)) + } + // Once only, and never for a Lightning purchase. + if ok, _ := r.b.UndoStarsPurchase(ctx, c.ID); ok { + t.Fatal("refunded twice") + } + ln := r.buy(bob, billing.ProductCredits, 1000) + _ = r.ln.Pay(ln.PaymentHash) + if ok, _ := r.b.UndoStarsPurchase(ctx, ln.ID); ok || r.balance(bob) != 1000 { + t.Fatal("a Lightning purchase was undone as a Stars refund") + } + if p := r.purchase(pass.ID); p.Status != db.PurchaseRefunded || p.RefundedAt == 0 { + t.Fatalf("purchase = %+v", p) + } + r.booksBalance() +} + +func TestStarsPurchasesEarnNoSatsReferral(t *testing.T) { + r := starsRig(t) + ctx := context.Background() + const inviter, invited = int64(700), int64(701) + for _, id := range []int64{inviter, invited} { + if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil { + t.Fatal(err) + } + } + if _, err := r.store.SetReferrer(ctx, invited, inviter); err != nil { + t.Fatal(err) + } + // Telegram's affiliate program covers Stars; our sats reward does not. + p := r.buyStars(invited, billing.ProductPassDay, 0) + _, _, _ = r.b.SettleStars(ctx, billing.StarsPayload(p), "c1", invited, "XTR", 50) + if r.balance(inviter) != 0 { + t.Fatal("a Stars purchase paid a sats referral reward") + } + // The first Lightning purchase after it does. + _ = r.ln.Pay(r.buy(invited, billing.ProductCredits, 1000).PaymentHash) + if r.balance(inviter) != 200 { + t.Fatalf("inviter balance = %d, want 200", r.balance(inviter)) + } +} diff --git a/internal/bot/appops.go b/internal/bot/appops.go index 0ac9505..da55621 100644 --- a/internal/bot/appops.go +++ b/internal/bot/appops.go @@ -226,6 +226,42 @@ func (b *Bot) AppPurchase(ctx context.Context, user *db.User, lang string, group }) } +// AppStarsPurchase creates a Stars purchase from the Mini App and an +// invoice link for WebApp.openInvoice. Payments made inside the Mini App +// are the ones Telegram's affiliate program counts. +func (b *Bot) AppStarsPurchase(ctx context.Context, user *db.User, lang string, groupID int64, product string, amount int64) (*db.Purchase, string, error) { + if !billing.ValidProduct(product) { + return nil, "", billing.ErrBadProduct + } + if !b.rate.allow("ap:"+itoa(user.ID), 10, time.Minute) { + return nil, "", ErrRateLimited + } + ownerType, ownerID := db.OwnerUser, user.ID + if groupID != 0 { + g, err := b.store.GetGroup(ctx, groupID) + if err != nil || !g.Present() { + return nil, "", db.ErrNotFound + } + ownerType, ownerID = db.OwnerGroup, groupID + } + w, err := b.bill.Wallet(ctx, ownerType, ownerID) + if err != nil { + return nil, "", err + } + p, err := b.bill.CreateStarsPurchase(ctx, billing.NewPurchase{ + UserID: user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, + }) + if err != nil { + return nil, "", err + } + link, err := b.StarsInvoiceLink(ctx, p) + if err != nil { + _, _ = b.bill.Cancel(context.WithoutCancel(ctx), p.ID, user.ID) + return nil, "", err + } + return p, link, nil +} + // Explain turns an error from the operations above into a stable code and // a message in the user's language. func (b *Bot) Explain(lang string, err error) (code, message string, upgradable bool) { @@ -248,7 +284,8 @@ func (b *Bot) Explain(lang string, err error) (code, message string, upgradable return "payments_off", b.tr.T(lang, "buy.unavailable", nil), false case errors.Is(err, billing.ErrLightningDown): return "payments_down", b.tr.T(lang, "buy.backend_down_short", nil), false - case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct): + case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct), + errors.Is(err, billing.ErrNotForStars), errors.Is(err, billing.ErrStarsOff): return "bad_amount", b.tr.T(lang, "buy.bad_amount", nil), false } b.log.Error("mini app operation failed", "err", err) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index e1557fa..738ef01 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -302,6 +302,8 @@ func updateChatID(u telego.Update) int64 { return u.CallbackQuery.From.ID case u.MyChatMember != nil: return u.MyChatMember.Chat.ID + case u.PreCheckoutQuery != nil: + return u.PreCheckoutQuery.From.ID case u.WidgetQuery != nil: if u.WidgetQuery.Chat != nil { return u.WidgetQuery.Chat.ID @@ -332,6 +334,8 @@ func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { b.handleMyChatMember(ctx, u.MyChatMember) case u.WidgetQuery != nil: b.handleWidgetQuery(ctx, u.WidgetQuery) + case u.PreCheckoutQuery != nil: + b.handlePreCheckout(ctx, u.PreCheckoutQuery) } } @@ -347,6 +351,8 @@ func updateUser(u telego.Update) (*telego.User, *telego.Chat) { return &u.CallbackQuery.From, &chat } return &u.CallbackQuery.From, nil + case u.PreCheckoutQuery != nil: + return &u.PreCheckoutQuery.From, nil } return nil, nil } @@ -361,6 +367,8 @@ func updateType(u telego.Update) string { return "my_chat_member" case u.WidgetQuery != nil: return "widget_query" + case u.PreCheckoutQuery != nil: + return "pre_checkout_query" } return "other" } diff --git a/internal/bot/commands.go b/internal/bot/commands.go index 183f679..21e6540 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -19,7 +19,19 @@ import ( func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { act, ok := actorFrom(ctx) - if !ok || act.user.Banned { + if !ok { + return + } + // Payments are settled whoever pays: the Stars were already taken. + switch { + case m.SuccessfulPayment != nil: + b.handleSuccessfulPayment(ctx, m, act) + return + case m.RefundedPayment != nil: + b.handleRefundedPayment(ctx, m, act) + return + } + if act.user.Banned { return } private := isPrivate(m.Chat.Type) @@ -524,6 +536,14 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbShowUpgrade(ctx, q, act) case cbReferralQR: b.cbSendReferralQR(ctx, q, act) + case cbStarsMenu, cbLightningMenu: + b.cbSwitchPayment(ctx, q, act, action == cbStarsMenu) + case cbStarsBuy: + b.cbStarsProduct(ctx, q, act, id, arg) + case cbStarsOffer: + b.cbStarsForOffer(ctx, q, act, id, arg) + case cbStarsOfferBuy: + b.cbStarsOfferProduct(ctx, q, act, id, arg) case cbPersonal: b.cbPersonalSetting(ctx, q, act, id, arg) case cbSkipQueue: diff --git a/internal/bot/money.go b/internal/bot/money.go index b61f0b9..c69dad2 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -77,19 +77,30 @@ func (b *Bot) cmdBuy(ctx context.Context, m *telego.Message, act actor) { } func (b *Bot) showBuy(ctx context.Context, chat int64, act actor) { - if !b.bill.Enabled() { + 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 - 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), + 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), }) - _, _ = b.send(ctx, chat, 0, text, keyboard(rows...)) + 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 { @@ -113,8 +124,12 @@ func (b *Bot) cmdCredits(ctx context.Context, m *telego.Message, act actor) { "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)) + 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) } @@ -173,8 +188,12 @@ func (b *Bot) cmdAccount(ctx context.Context, m *telego.Message, act actor) { "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) })...) + 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) } @@ -656,7 +675,14 @@ func (b *Bot) handlePayEvent(ctx context.Context, ev billing.Event) { } b.showPurchaseState(ctx, p) if ev.Type == billing.EventPaid { - if p.MessageID == 0 { + 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) @@ -686,9 +712,13 @@ func (b *Bot) confirmWithoutInvoice(ctx context.Context, purchaseID string) { // 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": b.tr.Sats(lang, p.AmountSats), + "Amount": amount, }) w, err := b.store.GetWallet(ctx, p.WalletID) if err != nil { @@ -860,7 +890,15 @@ func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string 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 { + 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), diff --git a/internal/bot/owner.go b/internal/bot/owner.go index eb4b253..d5ca3f5 100644 --- a/internal/bot/owner.go +++ b/internal/bot/owner.go @@ -52,6 +52,12 @@ func (b *Bot) ownerCommand(ctx context.Context, m *telego.Message, act actor, cm case "credit": b.cmdCredit(ctx, m, act, false) case "refund": + // /refund returns a Stars payment; + // /refund gives sats back, as before. + if f := strings.Fields(commandArgs(m)); len(f) == 1 && !isDigits(f[0]) { + b.refundStars(ctx, m, act, f[0]) + return true + } b.cmdCredit(ctx, m, act, true) case "blocklist": b.cmdBlocklist(ctx, m, act) @@ -97,7 +103,7 @@ func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) { } } maint, _ := b.store.GetKV(ctx, "maintenance") - b.ownerReply(ctx, m, act, "owner.stats", i18n.Args{ + text := b.tr.HTML(lang, "owner.stats", i18n.Args{ "Users": b.tr.Number(lang, users), "Done": b.tr.Number(lang, jobs[db.JobDone]), "Failed": b.tr.Number(lang, jobs[db.JobFailed]), @@ -109,6 +115,27 @@ func (b *Bot) cmdStats(ctx context.Context, m *telego.Message, act actor) { "Created": bst.InvoicesCreated, "Settled": bst.InvoicesSettled, "Lightning": ln, "Books": books, "Maint": b.onOff(lang, maint == "1"), }) + // Revenue by payment method, all time. + if revenue, err := b.store.RevenueByMethod(ctx, 0); err == nil && len(revenue) > 0 { + text += "\n\n" + b.tr.HTML(lang, "owner.revenue_title", nil) + for _, r := range revenue { + key, amount := "owner.revenue_lightning", b.tr.Sats(lang, r.Sats) + if r.Method == db.PayStars { + key, amount = "owner.revenue_stars", b.starsAmount(lang, r.Stars) + } + text += "\n" + b.tr.HTML(lang, key, i18n.Args{"Amount": amount, "Count": r.Purchases, "Refunded": r.Refunded}) + } + } + _, _ = b.send(ctx, m.Chat.ID, 0, text, nil) +} + +func isDigits(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return s != "" } // cmdQueueAll is /queue all for owners: every queued and running job. diff --git a/internal/bot/result.go b/internal/bot/result.go index dc8458a..53dc2dd 100644 --- a/internal/bot/result.go +++ b/internal/bot/result.go @@ -415,7 +415,7 @@ func (b *Bot) errorKeyboard(lang string, req *db.Request, profile media.Profile, // upgradeButton is "Upgrade", when there is something to buy. func (b *Bot) upgradeButton(lang string, private bool) []telego.InlineKeyboardButton { - if !b.bill.Enabled() { + if !b.bill.Selling() { return nil } if !private { diff --git a/internal/bot/stars.go b/internal/bot/stars.go new file mode 100644 index 0000000..25ff3f9 --- /dev/null +++ b/internal/bot/stars.go @@ -0,0 +1,313 @@ +package bot + +import ( + "context" + "errors" + "strconv" + "strings" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +// This file is the chat side of Telegram Stars payments: the Stars price +// buttons next to the Lightning ones, the invoice, the pre-checkout +// answer, the successful and refunded payment messages, and the owner's +// refund. Lightning stays the first option everywhere. + +const ( + cbStarsMenu = "sm" // sm: the Stars prices, in place of the Lightning ones + cbLightningMenu = "lm" // lm: back to the Lightning prices + cbStarsBuy = "sb" // sb:[:] + cbStarsOffer = "so" // so::, Stars for an over-limit offer + cbStarsOfferBuy = "sv" // sv::: +) + +// starsLabel is a price in Stars for a button, such as "Day pass · ⭐ 50". +func (b *Bot) starsLabel(lang, label string, stars int64) string { + return b.tr.T(lang, "btn.with_stars", i18n.Args{"Label": label, "Stars": b.tr.Number(lang, stars)}) +} + +// starsAmount is a price in Stars for a sentence. +func (b *Bot) starsAmount(lang string, stars int64) string { + return b.tr.T(lang, "unit.stars", i18n.Args{"Count": stars, "N": b.tr.Number(lang, stars)}) +} + +// starsPassButtons are the passes that have a Stars price. +func (b *Bot) starsPassButtons(lang string, data func(product string) string) [][]telego.InlineKeyboardButton { + var row []telego.InlineKeyboardButton + for _, product := range []string{billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth} { + if stars, ok := b.bill.StarsPrice(product, 0); ok { + row = append(row, button(b.starsLabel(lang, b.productTitle(lang, product), stars), data(product))) + } + } + if len(row) == 3 { + return [][]telego.InlineKeyboardButton{row[:2], row[2:]} + } + return [][]telego.InlineKeyboardButton{row} +} + +// starsMenu is the Stars counterpart of the buy screen. +func (b *Bot) starsMenu(lang string) (string, *telego.InlineKeyboardMarkup) { + rows := b.starsPassButtons(lang, func(product string) string { return cbData(cbStarsBuy, product) }) + var packs []telego.InlineKeyboardButton + for _, a := range b.cfg.Prices.CreditPacks { + if stars, ok := b.bill.StarsPrice(billing.ProductCredits, a); ok { + packs = append(packs, button(b.starsLabel(lang, b.tr.Sats(lang, a), stars), + cbData(cbStarsBuy, billing.ProductCredits, strconv.FormatInt(a, 10)))) + } + } + rows = append(rows, packs) + if b.bill.Enabled() { + rows = append(rows, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.pay_lightning", nil), cbLightningMenu)}) + } + return b.tr.HTML(lang, "stars.intro", nil), keyboard(rows...) +} + +// starsMenuButton opens the Stars prices, when Stars are on. +func (b *Bot) starsMenuButton(lang string) []telego.InlineKeyboardButton { + if !b.bill.StarsEnabled() { + return nil + } + return []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.pay_stars", nil), cbStarsMenu)} +} + +// cbSwitchPayment turns a buy screen into the Stars prices or back. +func (b *Bot) cbSwitchPayment(ctx context.Context, q *telego.CallbackQuery, act actor, stars bool) { + if q.Message == nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + chat, msgID := q.Message.GetChat().ID, int64(q.Message.GetMessageID()) + if stars { + text, kb := b.starsMenu(act.lang) + _ = b.edit(ctx, chat, msgID, false, text, kb) + return + } + text, kb := b.buyView(act.lang) + _ = b.edit(ctx, chat, msgID, false, text, kb) +} + +// cbStarsProduct handles a Stars price button of the buy screen. +func (b *Bot) cbStarsProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, amountArg string) { + b.answer(ctx, q, "", false) + amount, _ := strconv.ParseInt(amountArg, 10, 64) + b.startStarsPurchase(ctx, act, product, amount, purchaseContext{}) +} + +// cbStarsForOffer shows the Stars passes for an over-limit offer, as a +// message of its own under the Lightning offer. +func (b *Bot) cbStarsForOffer(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) { + req, err := b.store.GetRequest(ctx, requestID) + if err != nil || req.UserID != act.user.ID || req.Status != db.RequestReady { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + rows := b.starsPassButtons(act.lang, func(product string) string { + return cbData(cbStarsOfferBuy, product, req.ID, profileArg) + }) + _, _ = b.send(ctx, act.user.ID, 0, b.tr.HTML(act.lang, "stars.offer", nil), keyboard(rows...)) +} + +// cbStarsOfferProduct buys a pass in Stars for an over-limit offer; the +// download starts once it is paid, as with Lightning. +func (b *Bot) cbStarsOfferProduct(ctx context.Context, q *telego.CallbackQuery, act actor, product, rest string) { + requestID, profileArg, _ := strings.Cut(rest, ":") + req, err := b.store.GetRequest(ctx, requestID) + _, perr := media.Parse(profileArg) + if err != nil || perr != nil || req.UserID != act.user.ID || req.Status != db.RequestReady { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if _, err := service.ParseCardInfo(req.Info); err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + b.answer(ctx, q, "", false) + b.startStarsPurchase(ctx, act, product, 0, purchaseContext{requestID: req.ID, profile: profileArg}) +} + +// startStarsPurchase records a Stars purchase and sends its invoice to the +// payer's private chat. +func (b *Bot) startStarsPurchase(ctx context.Context, act actor, product string, amount int64, pc purchaseContext) { + lang := act.lang + chat := act.user.ID + if !billing.ValidProduct(product) { + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "buy.bad_amount", nil), nil) + return + } + 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.CreateStarsPurchase(ctx, billing.NewPurchase{ + UserID: act.user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, + RequestID: pc.requestID, Profile: pc.profile, DeliveryID: pc.deliveryID, + }) + switch { + case errors.Is(err, billing.ErrStarsOff), errors.Is(err, billing.ErrNotForStars), + 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 + } + if _, err := b.api.SendInvoice(ctx, b.starsInvoice(p, chat)); err != nil { + b.log.Error("send stars invoice", "purchase_id", p.ID, "err", err) + _, _ = b.bill.Cancel(context.WithoutCancel(ctx), p.ID, p.UserID) + _, _ = b.send(ctx, chat, 0, b.tr.HTML(lang, "error.internal", nil), nil) + } +} + +// starsInvoice is the sendInvoice call for a Stars purchase: currency XTR, +// no provider token, exactly one price. +func (b *Bot) starsInvoice(p *db.Purchase, chat int64) *telego.SendInvoiceParams { + title, desc := b.starsInvoiceTexts(p) + return &telego.SendInvoiceParams{ + ChatID: chatID(chat), Title: title, Description: desc, Payload: billing.StarsPayload(p), + Currency: "XTR", Prices: []telego.LabeledPrice{{Label: title, Amount: int(p.StarsAmount)}}, + } +} + +// starsInvoiceTexts are the title (1 to 32 characters) and description +// (1 to 255) of a Stars invoice. +func (b *Bot) starsInvoiceTexts(p *db.Purchase) (title, desc string) { + lang := p.Lang + title = b.productTitle(lang, p.Product) + if p.Product == billing.ProductCredits { + title = b.tr.T(lang, "stars.credits_title", i18n.Args{"Amount": b.tr.Sats(lang, p.AmountSats)}) + } + title = shorten(title, 32) + desc = b.tr.T(lang, "stars.invoice_description", i18n.Args{"Title": title}) + if g := b.groupTitle(p); g != "" { + desc = b.tr.T(lang, "invoice.for_group", i18n.Args{"Group": g}) + "\n" + desc + } + return title, shorten(plainText(desc), 255) +} + +// StarsInvoiceLink makes an invoice link for a Stars purchase, for the +// Mini App to open with WebApp.openInvoice. +func (b *Bot) StarsInvoiceLink(ctx context.Context, p *db.Purchase) (string, error) { + title, desc := b.starsInvoiceTexts(p) + link, err := b.api.CreateInvoiceLink(ctx, &telego.CreateInvoiceLinkParams{ + Title: title, Description: desc, Payload: billing.StarsPayload(p), + Currency: "XTR", Prices: []telego.LabeledPrice{{Label: title, Amount: int(p.StarsAmount)}}, + }) + if err != nil { + return "", err + } + return *link, nil +} + +// handlePreCheckout answers Telegram's last question before it takes the +// Stars. It has ten seconds; the check is a database read. +func (b *Bot) handlePreCheckout(ctx context.Context, q *telego.PreCheckoutQuery) { + lang := b.tr.Resolve(q.From.LanguageCode) + if act, ok := actorFrom(ctx); ok { + lang = act.lang + } + err := b.bill.PreCheckStars(ctx, q.InvoicePayload, q.From.ID, q.Currency, int64(q.TotalAmount)) + params := &telego.AnswerPreCheckoutQueryParams{PreCheckoutQueryID: q.ID, Ok: err == nil} + if err != nil { + key := "stars.precheck_failed" + if errors.Is(err, billing.ErrInvoiceClosed) { + key = "stars.precheck_closed" + } + params.ErrorMessage = b.tr.T(lang, key, nil) + b.log.Info("pre-checkout refused", "user_id", q.From.ID, "err", err) + } + if err := b.api.AnswerPreCheckoutQuery(ctx, params); err != nil { + b.log.Warn("answerPreCheckoutQuery failed", "err", err) + } +} + +// handleSuccessfulPayment settles the purchase a Stars payment was for. +// The paid event that follows confirms it in the chat and starts what was +// paid for. The same payment twice settles once. +func (b *Bot) handleSuccessfulPayment(ctx context.Context, m *telego.Message, act actor) { + sp := m.SuccessfulPayment + _, p, err := b.bill.SettleStars(context.WithoutCancel(ctx), sp.InvoicePayload, sp.TelegramPaymentChargeID, + m.From.ID, sp.Currency, int64(sp.TotalAmount)) + if err != nil { + // The Stars were taken but cannot be matched to an order. The owner + // can return them with /refund and the charge ID from this log line. + b.log.Error("stars payment not settled", "user_id", m.From.ID, "charge_id", sp.TelegramPaymentChargeID, + "payload", sp.InvoicePayload, "total", sp.TotalAmount, "err", err) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "stars.payment_problem", nil), nil) + return + } + b.log.Info("stars payment received", "purchase_id", p.ID, "user_id", m.From.ID, "stars", sp.TotalAmount) +} + +// handleRefundedPayment takes back what a refunded Stars purchase granted. +// It runs for refunds made through /refund as well as any other, and does +// nothing the second time. +func (b *Bot) handleRefundedPayment(ctx context.Context, m *telego.Message, act actor) { + rp := m.RefundedPayment + p, err := b.store.GetPurchaseByCharge(ctx, rp.TelegramPaymentChargeID) + if err != nil { + b.log.Warn("refund of an unknown stars payment", "charge_id", rp.TelegramPaymentChargeID) + return + } + undone, err := b.bill.UndoStarsPurchase(context.WithoutCancel(ctx), p.ID) + if err != nil { + b.log.Error("undo refunded stars purchase", "purchase_id", p.ID, "err", err) + return + } + if undone { + _, _ = b.send(ctx, p.UserID, 0, b.tr.HTML(p.Lang, "stars.refunded", i18n.Args{ + "Title": b.productTitle(p.Lang, p.Product), "Amount": b.starsAmount(p.Lang, p.StarsAmount), + }), nil) + } +} + +// refundStars is the owner's /refund for a Stars payment: by purchase ID +// or by Telegram's charge ID. Telegram returns the Stars; the purchase's +// credits or pass are taken back. +func (b *Bot) refundStars(ctx context.Context, m *telego.Message, act actor, ref string) { + p, err := b.store.GetPurchase(ctx, ref) + if err != nil { + p, err = b.store.GetPurchaseByCharge(ctx, ref) + } + if err != nil || p.PaymentMethod != db.PayStars { + b.ownerReply(ctx, m, act, "owner.not_found", nil) + return + } + if p.Status != db.PurchasePaid || p.ChargeID == "" { + b.ownerReply(ctx, m, act, "owner.stars_not_refundable", i18n.Args{"Status": p.Status}) + return + } + if err := b.api.RefundStarPayment(ctx, &telego.RefundStarPaymentParams{ + UserID: p.UserID, TelegramPaymentChargeID: p.ChargeID, + }); err != nil { + b.log.Warn("refundStarPayment failed", "purchase_id", p.ID, "err", err) + b.ownerReply(ctx, m, act, "owner.stars_refund_failed", i18n.Args{"Reason": err.Error()}) + return + } + undone, err := b.bill.UndoStarsPurchase(context.WithoutCancel(ctx), p.ID) + if err != nil { + b.internalError(ctx, m.Chat.ID, act, err) + return + } + if undone { + _, _ = b.send(ctx, p.UserID, 0, b.tr.HTML(p.Lang, "stars.refunded", i18n.Args{ + "Title": b.productTitle(p.Lang, p.Product), "Amount": b.starsAmount(p.Lang, p.StarsAmount), + }), nil) + } + b.ownerReply(ctx, m, act, "owner.stars_refunded", i18n.Args{ + "ID": p.ID, "Amount": b.starsAmount(act.lang, p.StarsAmount), "User": strconv.FormatInt(p.UserID, 10), + }) +} diff --git a/internal/config/config.go b/internal/config/config.go index 7760f91..a1aeace 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -113,6 +113,45 @@ type Config struct { // day (UTC), in sats. Rewards above it wait and are paid on a later // day. 0 means no cap. ReferralDailyCap int64 `toml:"referral_daily_cap" env:"REFERRAL_DAILY_CAP"` + + // StarsEnabled offers Telegram Stars as a second way to pay for passes + // and credits, next to Lightning. It needs no setup beyond the bot. + StarsEnabled bool `toml:"stars_enabled" env:"STARS_ENABLED"` + // StarsPrices is the price in Stars of each product sold for Stars: + // pass_day, pass_week, pass_month and credits_ for a credit pack + // (credits_1000 = 70). These are set on their own, never converted from + // sats. A product without a price is not offered for Stars. In the + // environment: STARS_PRICES="pass_day=50,credits_1000=70". + StarsPrices map[string]int64 `toml:"stars_prices"` +} + +// StarsPrice returns the price in Stars of a product, or false when it +// is not sold for Stars. amount names the credit pack. +func (c Config) StarsPrice(product string, amount int64) (int64, bool) { + key := product + if product == "credits" { + key = "credits_" + strconv.FormatInt(amount, 10) + } + n, ok := c.StarsPrices[key] + return n, ok && n > 0 +} + +// ParseStarsPrices reads STARS_PRICES: "pass_day=50,credits_1000=70". +func ParseStarsPrices(raw string) (map[string]int64, error) { + out := map[string]int64{} + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + k, v, ok := strings.Cut(part, "=") + n, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64) + if !ok || err != nil { + return nil, fmt.Errorf("STARS_PRICES: bad entry %q, want product=stars", part) + } + out[strings.TrimSpace(k)] = n + } + return out, nil } // Telegram holds the Bot API settings. @@ -387,6 +426,10 @@ func Default() Config { CaptionAttribution: true, ReferralRewardSats: -1, ReferralDailyCap: 2000, + StarsPrices: map[string]int64{ + "pass_day": 50, "pass_week": 200, "pass_month": 600, + "credits_1000": 70, "credits_5000": 330, "credits_20000": 1300, + }, } } @@ -424,6 +467,13 @@ func Load(path string) (Config, error) { if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil { return cfg, err } + if raw, ok := os.LookupEnv("STARS_PRICES"); ok && raw != "" { + m, err := ParseStarsPrices(raw) + if err != nil { + return cfg, err + } + cfg.StarsPrices = m + } if raw, ok := os.LookupEnv("SITE_TAGS"); ok && raw != "" { m, err := ParseSiteTags(raw) if err != nil { @@ -467,6 +517,19 @@ func (c Config) Validate() error { if c.QueueNoticeThresholdSeconds < 0 { errs = append(errs, "QUEUE_NOTICE_THRESHOLD_SECONDS must not be negative") } + for k, n := range c.StarsPrices { + known := k == "pass_day" || k == "pass_week" || k == "pass_month" + if amount, ok := strings.CutPrefix(k, "credits_"); ok { + v, err := strconv.ParseInt(amount, 10, 64) + known = err == nil && v > 0 + } + if !known { + errs = append(errs, fmt.Sprintf("stars_prices: unknown product %q (pass_day, pass_week, pass_month, credits_)", k)) + } + if n < 1 || n > 100000 { + errs = append(errs, fmt.Sprintf("stars_prices: %s must be between 1 and 100000 Stars", k)) + } + } if c.ReferralDailyCap < 0 { errs = append(errs, "REFERRAL_DAILY_CAP must not be negative") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index fc69421..853cf25 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -393,3 +393,35 @@ func TestReferralRewardNames(t *testing.T) { t.Fatal("a negative cap was accepted") } } + +func TestStarsPrices(t *testing.T) { + cfg := Default() + if n, ok := cfg.StarsPrice("pass_week", 0); !ok || n != 200 { + t.Fatalf("default pass_week = %d %v", n, ok) + } + if n, ok := cfg.StarsPrice("credits", 5000); !ok || n != 330 { + t.Fatalf("default 5000 credits = %d %v", n, ok) + } + if _, ok := cfg.StarsPrice("credits", 1234); ok { + t.Fatal("a pack without a Stars price is sold for Stars") + } + if _, ok := cfg.StarsPrice("one_off", 0); ok { + t.Fatal("one-off payments are not sold for Stars") + } + m, err := ParseStarsPrices(" pass_day=25, credits_1000=60 ") + if err != nil || m["pass_day"] != 25 || m["credits_1000"] != 60 || len(m) != 2 { + t.Fatalf("ParseStarsPrices = %v, %v", m, err) + } + if _, err := ParseStarsPrices("pass_day=lots"); err == nil { + t.Fatal("a bad price was accepted") + } + cfg.Telegram.Token = "x" + cfg.StarsPrices = map[string]int64{"pass_year": 5} + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "pass_year") { + t.Fatalf("unknown product: %v", err) + } + cfg.StarsPrices = map[string]int64{"pass_day": 0} + if err := cfg.Validate(); err == nil { + t.Fatal("a price of 0 Stars was accepted") + } +} diff --git a/internal/db/groups.go b/internal/db/groups.go index 2fda2aa..ee23c87 100644 --- a/internal/db/groups.go +++ b/internal/db/groups.go @@ -300,9 +300,9 @@ func (s *Store) ActiveJobs(ctx context.Context, limit int) ([]*Job, error) { ORDER BY CASE status WHEN 'running' THEN 0 ELSE 1 END, `+queueOrder+` LIMIT ?`, limit)) } -// SatsReceived sums paid purchases. +// SatsReceived sums purchases paid over Lightning. func (s *Store) SatsReceived(ctx context.Context) (int64, error) { var n sql.NullInt64 - err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid'`).Scan(&n) + err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid' AND payment_method = 'lightning'`).Scan(&n) return n.Int64, err } diff --git a/internal/db/migrations/00009_stars.sql b/internal/db/migrations/00009_stars.sql new file mode 100644 index 0000000..5a95783 --- /dev/null +++ b/internal/db/migrations/00009_stars.sql @@ -0,0 +1,24 @@ +-- +goose Up +-- Telegram Stars as a second payment method. Every purchase and every +-- ledger entry says how it was paid; everything before this was Lightning. +ALTER TABLE purchases ADD COLUMN payment_method TEXT NOT NULL DEFAULT 'lightning'; +-- What a Stars purchase cost in Stars. amount_sats keeps the sats value of +-- what it bought (the credit pack, or the pass price) for the wallet. +ALTER TABLE purchases ADD COLUMN stars_amount BIGINT NOT NULL DEFAULT 0; +-- Telegram's identifier of a Stars payment. Unique, so the same payment +-- event can never settle twice. +ALTER TABLE purchases ADD COLUMN tg_charge_id TEXT NOT NULL DEFAULT ''; +ALTER TABLE purchases ADD COLUMN refunded_at BIGINT NOT NULL DEFAULT 0; +CREATE UNIQUE INDEX purchases_charge_idx ON purchases (tg_charge_id) WHERE tg_charge_id <> ''; +CREATE INDEX purchases_method_idx ON purchases (payment_method, status); + +ALTER TABLE ledger ADD COLUMN payment_method TEXT NOT NULL DEFAULT 'lightning'; + +-- +goose Down +ALTER TABLE ledger DROP COLUMN payment_method; +DROP INDEX purchases_method_idx; +DROP INDEX purchases_charge_idx; +ALTER TABLE purchases DROP COLUMN refunded_at; +ALTER TABLE purchases DROP COLUMN tg_charge_id; +ALTER TABLE purchases DROP COLUMN stars_amount; +ALTER TABLE purchases DROP COLUMN payment_method; diff --git a/internal/db/models.go b/internal/db/models.go index bc12e8f..51e9e10 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -255,6 +255,9 @@ type LedgerEntry struct { DedupeKey string ActorID int64 CreatedAt int64 + // PaymentMethod is how the money behind the entry was paid: lightning + // or stars. Empty means lightning. + PaymentMethod string } // Pass is a time window of paid limits on a wallet. @@ -291,8 +294,24 @@ type Purchase struct { CreatedAt int64 ExpiresAt int64 PaidAt int64 + // PaymentMethod is lightning or stars. + PaymentMethod string + // StarsAmount is the price in Stars of a Stars purchase. + StarsAmount int64 + // ChargeID is Telegram's telegram_payment_charge_id of a Stars payment. + ChargeID string + RefundedAt int64 } +// Payment methods. +const ( + PayLightning = "lightning" + PayStars = "stars" +) + +// PurchaseRefunded is the status of a Stars purchase that was refunded. +const PurchaseRefunded = "refunded" + // Usage is what a user consumed on one UTC day. type Usage struct { Downloads int diff --git a/internal/db/money.go b/internal/db/money.go index f9cc5ce..72fbfdf 100644 --- a/internal/db/money.go +++ b/internal/db/money.go @@ -117,9 +117,13 @@ func (s *Store) AddLedger(ctx context.Context, e *LedgerEntry) (applied bool, er if e.CreatedAt == 0 { e.CreatedAt = NowMilli() } + if e.PaymentMethod == "" { + e.PaymentMethod = PayLightning + } _, err = s.exec(ctx, `INSERT INTO ledger (id, wallet_id, kind, amount, balance_after, reason, ref, - dedupe_key, actor_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt) + dedupe_key, actor_id, created_at, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + e.ID, e.WalletID, e.Kind, e.Amount, e.BalanceAfter, e.Reason, e.Ref, e.DedupeKey, e.ActorID, e.CreatedAt, + e.PaymentMethod) if isUniqueViolation(err) { // Lost a race against the same key on another connection. The // surrounding transaction must roll back, which undoes the balance. @@ -171,7 +175,7 @@ func (s *Store) VerifyWallets(ctx context.Context) ([]WalletMismatch, error) { // ListLedger returns the newest entries of a wallet. func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]*LedgerEntry, error) { rows, err := s.rows(ctx, `SELECT id, wallet_id, kind, amount, balance_after, reason, ref, dedupe_key, - actor_id, created_at FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, + actor_id, created_at, payment_method FROM ledger WHERE wallet_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, walletID, limit) if err != nil { return nil, err @@ -181,7 +185,7 @@ func (s *Store) ListLedger(ctx context.Context, walletID string, limit int) ([]* for rows.Next() { var e LedgerEntry if err := rows.Scan(&e.ID, &e.WalletID, &e.Kind, &e.Amount, &e.BalanceAfter, &e.Reason, &e.Ref, - &e.DedupeKey, &e.ActorID, &e.CreatedAt); err != nil { + &e.DedupeKey, &e.ActorID, &e.CreatedAt, &e.PaymentMethod); err != nil { return nil, err } out = append(out, &e) @@ -237,13 +241,14 @@ func (s *Store) ExtendPass(ctx context.Context, walletID string, lengthMS, now i const purchaseCols = `id, user_id, wallet_id, product, amount_sats, status, payment_hash, bolt11, chat_id, message_id, message_is_photo, lang, request_id, profile, delivery_id, fulfilled, created_at, - expires_at, paid_at` + expires_at, paid_at, payment_method, stars_amount, tg_charge_id, refunded_at` func scanPurchase(sc interface{ Scan(...any) error }) (*Purchase, error) { var p Purchase err := sc.Scan(&p.ID, &p.UserID, &p.WalletID, &p.Product, &p.AmountSats, &p.Status, &p.PaymentHash, &p.Bolt11, &p.ChatID, &p.MessageID, &p.MessageIsPhoto, &p.Lang, &p.RequestID, &p.Profile, - &p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt) + &p.DeliveryID, &p.Fulfilled, &p.CreatedAt, &p.ExpiresAt, &p.PaidAt, + &p.PaymentMethod, &p.StarsAmount, &p.ChargeID, &p.RefundedAt) if err != nil { return nil, notFound(err) } @@ -268,11 +273,14 @@ func scanPurchases(rows *sql.Rows, err error) ([]*Purchase, error) { // InsertPurchase stores a new purchase. func (s *Store) InsertPurchase(ctx context.Context, p *Purchase) error { + if p.PaymentMethod == "" { + p.PaymentMethod = PayLightning + } _, err := s.exec(ctx, `INSERT INTO purchases (`+purchaseCols+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, p.ID, p.UserID, p.WalletID, p.Product, p.AmountSats, p.Status, p.PaymentHash, p.Bolt11, p.ChatID, p.MessageID, p.MessageIsPhoto, p.Lang, p.RequestID, p.Profile, p.DeliveryID, p.Fulfilled, - p.CreatedAt, p.ExpiresAt, p.PaidAt) + p.CreatedAt, p.ExpiresAt, p.PaidAt, p.PaymentMethod, p.StarsAmount, p.ChargeID, p.RefundedAt) return err } @@ -322,7 +330,8 @@ func (s *Store) SetPurchaseMessage(ctx context.Context, id string, chatID, messa // arrive in the moment an invoice expires or is cancelled. func (s *Store) UnsettledPurchases(ctx context.Context, closedAfter int64, limit int) ([]*Purchase, error) { return scanPurchases(s.rows(ctx, `SELECT `+purchaseCols+` FROM purchases - WHERE status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?) + WHERE payment_method = 'lightning' + AND (status = 'pending' OR (status IN ('expired', 'cancelled') AND expires_at > ?)) ORDER BY created_at LIMIT ?`, closedAfter, limit)) } @@ -333,13 +342,18 @@ func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Pur WHERE status = 'paid' AND fulfilled = ? ORDER BY paid_at LIMIT ?`, false, limit)) } -// CountPaidPurchases counts the paid purchases of a user, donations aside. // CountReferralPurchases counts the settled purchases of a user that our -// referral program looks at: everything but donations, paid in sats. +// referral program looks at: everything but donations, paid over +// Lightning. func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) { - return s.CountPaidPurchases(ctx, userID) + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status IN ('paid', 'refunded') + AND product <> 'donation' AND payment_method = 'lightning'`, userID).Scan(&n) + return n, err } +// CountPaidPurchases counts the paid purchases of a user, donations aside. + func (s *Store) CountPaidPurchases(ctx context.Context, userID int64) (int, error) { var n int err := s.row(ctx, `SELECT COUNT(*) FROM purchases WHERE user_id = ? AND status = 'paid' @@ -431,3 +445,83 @@ func (s *Store) UseGiftCode(ctx context.Context, code string, userID, now int64) } return err == nil, err } + +// SetPurchaseCharge records Telegram's charge ID of a Stars payment. The +// unique index makes a second purchase with the same charge fail with +// ErrDuplicate. +func (s *Store) SetPurchaseCharge(ctx context.Context, id, chargeID string) error { + _, err := s.exec(ctx, `UPDATE purchases SET tg_charge_id = ? WHERE id = ? AND tg_charge_id = ''`, chargeID, id) + if isUniqueViolation(err) { + return ErrDuplicate + } + return err +} + +// GetPurchaseByCharge finds a Stars purchase by Telegram's charge ID. +func (s *Store) GetPurchaseByCharge(ctx context.Context, chargeID string) (*Purchase, error) { + if chargeID == "" { + return nil, ErrNotFound + } + return scanPurchase(s.row(ctx, `SELECT `+purchaseCols+` FROM purchases WHERE tg_charge_id = ?`, chargeID)) +} + +// MarkPurchaseRefunded moves a paid Stars purchase to refunded. It +// reports false when it was not paid, so a refund is undone once. +func (s *Store) MarkPurchaseRefunded(ctx context.Context, id string, now int64) (bool, error) { + n, err := s.exec(ctx, `UPDATE purchases SET status = 'refunded', refunded_at = ? + WHERE id = ? AND status = 'paid' AND payment_method = 'stars'`, now, id) + return n == 1, err +} + +// RemovePassesFrom deletes the passes a purchase granted, for a refund, +// and moves later passes of the wallet back by the time they lose. +func (s *Store) RemovePassesFrom(ctx context.Context, walletID, source string) (int64, error) { + var start, end sql.NullInt64 + if err := s.row(ctx, `SELECT MIN(starts_at), MAX(expires_at) FROM passes WHERE wallet_id = ? AND source = ?`, + walletID, source).Scan(&start, &end); err != nil || !start.Valid { + return 0, err + } + n, err := s.exec(ctx, `DELETE FROM passes WHERE wallet_id = ? AND source = ?`, walletID, source) + if err != nil || n == 0 { + return n, err + } + // Passes that were stacked after the refunded one start earlier now. + length := end.Int64 - start.Int64 + _, err = s.exec(ctx, `UPDATE passes SET starts_at = starts_at - ?, expires_at = expires_at - ? + WHERE wallet_id = ? AND starts_at >= ?`, length, length, walletID, end.Int64) + return n, err +} + +// Revenue is what one payment method brought in. +type Revenue struct { + Method string + Purchases int + Sats int64 // Lightning: sats received + Stars int64 // Stars: Stars received, refunds excluded + Refunded int +} + +// RevenueByMethod sums settled purchases per payment method since a +// moment (0 for all time). Refunded Stars purchases are counted apart. +func (s *Store) RevenueByMethod(ctx context.Context, since int64) ([]Revenue, error) { + rows, err := s.rows(ctx, `SELECT payment_method, + COALESCE(SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'lightning' THEN amount_sats ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'paid' AND payment_method = 'stars' THEN stars_amount ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END), 0) + FROM purchases WHERE status IN ('paid', 'refunded') AND paid_at >= ? + GROUP BY payment_method ORDER BY payment_method`, since) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Revenue + for rows.Next() { + var r Revenue + if err := rows.Scan(&r.Method, &r.Purchases, &r.Sats, &r.Stars, &r.Refunded); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} diff --git a/internal/service/service.go b/internal/service/service.go index 3dd92c5..cea8d9b 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -507,7 +507,7 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError { le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]} if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || strings.HasPrefix(code, "group_") || - code == LimitMaintenance || dec.Source.Paid() || !s.billing.Enabled() { + code == LimitMaintenance || dec.Source.Paid() || !s.billing.Selling() { return le } // Would the paid tier accept it? Only then is it worth offering. diff --git a/internal/tg/api.go b/internal/tg/api.go index d8b205f..19cfd09 100644 --- a/internal/tg/api.go +++ b/internal/tg/api.go @@ -37,6 +37,10 @@ type API interface { AnswerWidgetQuery(ctx context.Context, params *telego.AnswerWidgetQueryParams) error GetChatMember(ctx context.Context, params *telego.GetChatMemberParams) (telego.ChatMember, error) SetChatMenuButton(ctx context.Context, params *telego.SetChatMenuButtonParams) error + SendInvoice(ctx context.Context, params *telego.SendInvoiceParams) (*telego.Message, error) + CreateInvoiceLink(ctx context.Context, params *telego.CreateInvoiceLinkParams) (*string, error) + AnswerPreCheckoutQuery(ctx context.Context, params *telego.AnswerPreCheckoutQueryParams) error + RefundStarPayment(ctx context.Context, params *telego.RefundStarPaymentParams) error } var _ API = (*telego.Bot)(nil) diff --git a/internal/tg/fakeserver/server.go b/internal/tg/fakeserver/server.go index 1999462..f2a51b6 100644 --- a/internal/tg/fakeserver/server.go +++ b/internal/tg/fakeserver/server.go @@ -353,6 +353,52 @@ func (s *Server) PushWidgetQuery(chatID, userID int64, messageID int, data strin 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() @@ -479,7 +525,10 @@ func (s *Server) resultLocked(c *Call) any { } 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 "sendMessage", "sendPhoto", "sendVideo", "sendAudio", "sendDocument", "sendAnimation", "sendWidget": + 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) @@ -540,6 +589,17 @@ func (s *Server) messageLocked(c *Call) map[string]any { 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 } diff --git a/locales/en.toml b/locales/en.toml index 62e11a2..f964e03 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -156,6 +156,9 @@ pick = "Pick a format:" cancelled = "Cancelled." [btn] +pay_lightning = "⚡ Pay with Lightning" +pay_stars = "⭐ Pay with Stars" +with_stars = "{{.Label}} · ⭐ {{.Stars}}" qr = "QR code" copy_link = "Copy link" share = "Share" @@ -440,6 +443,10 @@ Page {{.Page}} of {{.Pages}}. Tap one to see it and get it again.""" # --- Owner commands --------------------------------------------------------- [owner] +revenue_title = "Revenue" +stars_refunded = "Refunded {{.Amount}} to user {{.User}} for purchase {{.ID}}. What it granted was taken back." +stars_refund_failed = "Telegram refused the refund: {{.Reason}}" +stars_not_refundable = "This Stars purchase cannot be refunded (status: {{.Status}})." books_ok = "ledger and balances agree" ln_ok = "reachable" ln_down = "NOT reachable" @@ -480,7 +487,11 @@ Create a gift code: gift_code = "Gift code: {{.Code}}\nUses: {{.Uses}}" granted = "Done. The pass of {{.ID}} runs until {{.Until}}." credit_usage = "Example: /credit 123456789 500" -refund_usage = "Examples:\n/refund 123456789 500\n/refund 123456789 pass 24h" +refund_usage = """ +Examples: +/refund 123456789 500 +/refund 123456789 pass 24h +/refund PURCHASE_ID returns a Stars payment""" no_pass = "That wallet has no active pass to extend." credited = "Done. {{.Amount}} added to {{.ID}}. Balance: {{.Balance}}." blocklist_empty = "The blocklist is empty." @@ -756,6 +767,8 @@ cancel_confirm = "Cancel \"{{.Title}}\"?" cancelled = "Cancelled." [app.buy] +method_stars = "Telegram Stars ⭐" +method_lightning = "Lightning ⚡" unavailable = "Payments are not set up on this bot." step = "Step {{.Step}} of {{.Total}}" target_title = "Who is it for?" @@ -780,6 +793,9 @@ at_once = "At the same time" none = "No limit" [app.invoice] +refunded = "Refunded" +stars_pay = "Open the payment again" +stars_waiting = "Waiting for Telegram to confirm the payment…" qr_alt = "Lightning invoice as a QR code" copy = "Copy invoice" waiting = "Waiting for payment · {{.Time}}" @@ -917,3 +933,29 @@ Share your link. When somebody you invited pays for a first purchase in sats (Li Invited: {{.Invited}} · Bought something: {{.Converted}} Earned: {{.Earned}} · Waiting: {{.Pending}}""" + +[unit.stars] +one = "{{.N}} Star" +other = "{{.N}} Stars" + +[stars] +refunded = "Your payment for {{.Title}} was refunded: {{.Amount}} went back to your Telegram balance." +payment_problem = "Your payment arrived, but I could not match it to an order. The bot owner can see it and will sort it out." +precheck_closed = "This invoice is closed. Please start the purchase again." +precheck_failed = "This invoice does not match your order. Please start the purchase again." +invoice_description = "{{.Title}} for The Noderunners Download Bot, yours as soon as the payment arrives." +credits_title = "{{.Amount}} in credits" +offer = """ +Pay with Telegram Stars +A pass covers this download. It starts as soon as the payment arrives.""" +intro = """ +Pay with Telegram Stars +The same passes and credits, paid from your Stars balance in Telegram.""" + +[owner.revenue_lightning] +one = "Lightning: {{.Amount}} from {{.Count}} purchase" +other = "Lightning: {{.Amount}} from {{.Count}} purchases" + +[owner.revenue_stars] +one = "Stars: {{.Amount}} from {{.Count}} purchase, {{.Refunded}} refunded" +other = "Stars: {{.Amount}} from {{.Count}} purchases, {{.Refunded}} refunded" diff --git a/locales/es.toml b/locales/es.toml index 2469eeb..975745c 100644 --- a/locales/es.toml +++ b/locales/es.toml @@ -147,6 +147,9 @@ pick = "Elige un formato:" cancelled = "Cancelado." [btn] +pay_lightning = "⚡ Pagar con Lightning" +pay_stars = "⭐ Pagar con Estrellas" +with_stars = "{{.Label}} · ⭐ {{.Stars}}" qr = "Código QR" copy_link = "Copiar enlace" share = "Compartir" @@ -422,6 +425,10 @@ header = """ Página {{.Page}} de {{.Pages}}. Toca una para verla y recibirla otra vez.""" [owner] +revenue_title = "Ingresos" +stars_refunded = "Devueltas {{.Amount}} al usuario {{.User}} por la compra {{.ID}}. Lo que otorgó se retiró." +stars_refund_failed = "Telegram rechazó la devolución: {{.Reason}}" +stars_not_refundable = "Esta compra con Estrellas no se puede devolver (estado: {{.Status}})." books_ok = "el libro mayor y los saldos coinciden" ln_ok = "disponible" ln_down = "NO disponible" @@ -462,7 +469,11 @@ Crear un código de regalo: gift_code = "Código de regalo: {{.Code}}\nUsos: {{.Uses}}" granted = "Listo. El pase de {{.ID}} dura hasta el {{.Until}}." credit_usage = "Ejemplo: /credit 123456789 500" -refund_usage = "Ejemplos:\n/refund 123456789 500\n/refund 123456789 pass 24h" +refund_usage = """ +Ejemplos: +/refund 123456789 500 +/refund 123456789 pass 24h +/refund PURCHASE_ID devuelve un pago con Estrellas""" no_pass = "Esa billetera no tiene un pase activo para extender." credited = "Listo. Se agregaron {{.Amount}} a {{.ID}}. Saldo: {{.Balance}}." blocklist_empty = "La lista de bloqueo está vacía." @@ -731,6 +742,8 @@ cancel_confirm = "Cancelar \"{{.Title}}\"?" cancelled = "Cancelado." [app.buy] +method_stars = "Estrellas ⭐" +method_lightning = "Lightning ⚡" unavailable = "Los pagos no están configurados en este bot." step = "Paso {{.Step}} de {{.Total}}" target_title = "Para quién es?" @@ -755,6 +768,9 @@ at_once = "Al mismo tiempo" none = "Sin límite" [app.invoice] +refunded = "Devuelto" +stars_pay = "Abrir el pago otra vez" +stars_waiting = "Esperando a que Telegram confirme el pago…" qr_alt = "Factura Lightning como código QR" copy = "Copiar la factura" waiting = "Esperando el pago · {{.Time}}" @@ -890,3 +906,29 @@ Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sat Invitados: {{.Invited}} · Compraron algo: {{.Converted}} Ganado: {{.Earned}} · En espera: {{.Pending}}""" + +[unit.stars] +one = "{{.N}} Estrella" +other = "{{.N}} Estrellas" + +[stars] +refunded = "Se te devolvió el pago de {{.Title}}: {{.Amount}} volvieron a tu saldo de Telegram." +payment_problem = "Tu pago llegó, pero no pude asociarlo a un pedido. El dueño del bot lo ve y lo va a resolver." +precheck_closed = "Esta factura está cerrada. Empieza la compra otra vez, por favor." +precheck_failed = "Esta factura no coincide con tu pedido. Empieza la compra otra vez, por favor." +invoice_description = "{{.Title}} para The Noderunners Download Bot, tuyo en cuanto llega el pago." +credits_title = "{{.Amount}} en créditos" +offer = """ +Pagar con Estrellas de Telegram +Un pase cubre esta descarga. Empieza en cuanto llega el pago.""" +intro = """ +Pagar con Estrellas de Telegram +Los mismos pases y créditos, pagados con tu saldo de Estrellas en Telegram.""" + +[owner.revenue_lightning] +one = "Lightning: {{.Amount}} de {{.Count}} compra" +other = "Lightning: {{.Amount}} de {{.Count}} compras" + +[owner.revenue_stars] +one = "Estrellas: {{.Amount}} de {{.Count}} compra, {{.Refunded}} devueltas" +other = "Estrellas: {{.Amount}} de {{.Count}} compras, {{.Refunded}} devueltas" diff --git a/locales/nl.toml b/locales/nl.toml index 68d3ca7..f363ff2 100644 --- a/locales/nl.toml +++ b/locales/nl.toml @@ -146,6 +146,9 @@ pick = "Kies een formaat:" cancelled = "Geannuleerd." [btn] +pay_lightning = "⚡ Betalen met Lightning" +pay_stars = "⭐ Betalen met Stars" +with_stars = "{{.Label}} · ⭐ {{.Stars}}" qr = "QR-code" copy_link = "Link kopiëren" share = "Delen" @@ -421,6 +424,10 @@ header = """ Pagina {{.Page}} van {{.Pages}}. Tik op een download om hem te bekijken en opnieuw te krijgen.""" [owner] +revenue_title = "Omzet" +stars_refunded = "{{.Amount}} terugbetaald aan gebruiker {{.User}} voor aankoop {{.ID}}. Wat die opleverde is teruggenomen." +stars_refund_failed = "Telegram weigerde de terugbetaling: {{.Reason}}" +stars_not_refundable = "Deze Stars-aankoop kan niet worden terugbetaald (status: {{.Status}})." books_ok = "grootboek en saldi kloppen" ln_ok = "bereikbaar" ln_down = "NIET bereikbaar" @@ -461,7 +468,11 @@ Een cadeaucode maken: gift_code = "Cadeaucode: {{.Code}}\nKeer te gebruiken: {{.Uses}}" granted = "Klaar. De pas van {{.ID}} loopt tot {{.Until}}." credit_usage = "Voorbeeld: /credit 123456789 500" -refund_usage = "Voorbeelden:\n/refund 123456789 500\n/refund 123456789 pass 24h" +refund_usage = """ +Voorbeelden: +/refund 123456789 500 +/refund 123456789 pass 24h +/refund PURCHASE_ID betaalt een Stars-betaling terug""" no_pass = "Die wallet heeft geen actieve pas om te verlengen." credited = "Klaar. {{.Amount}} toegevoegd aan {{.ID}}. Saldo: {{.Balance}}." blocklist_empty = "De blokkeerlijst is leeg." @@ -730,6 +741,8 @@ cancel_confirm = "\"{{.Title}}\" annuleren?" cancelled = "Geannuleerd." [app.buy] +method_stars = "Telegram Stars ⭐" +method_lightning = "Lightning ⚡" unavailable = "Betalingen zijn op deze bot niet ingesteld." step = "Stap {{.Step}} van {{.Total}}" target_title = "Voor wie is het?" @@ -754,6 +767,9 @@ at_once = "Tegelijk" none = "Geen limiet" [app.invoice] +refunded = "Terugbetaald" +stars_pay = "De betaling opnieuw openen" +stars_waiting = "Wachten tot Telegram de betaling bevestigt…" qr_alt = "Lightning-factuur als QR-code" copy = "Factuur kopiëren" waiting = "Wachten op betaling · {{.Time}}" @@ -889,3 +905,29 @@ Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning Uitgenodigd: {{.Invited}} · Iets gekocht: {{.Converted}} Verdiend: {{.Earned}} · Wacht nog: {{.Pending}}""" + +[unit.stars] +one = "{{.N}} Star" +other = "{{.N}} Stars" + +[stars] +refunded = "Je betaling voor {{.Title}} is terugbetaald: {{.Amount}} staat weer op je Telegram-saldo." +payment_problem = "Je betaling is binnen, maar ik kon hem niet aan een bestelling koppelen. De eigenaar van de bot ziet het en lost het op." +precheck_closed = "Deze factuur is gesloten. Begin de aankoop opnieuw." +precheck_failed = "Deze factuur past niet bij je bestelling. Begin de aankoop opnieuw." +invoice_description = "{{.Title}} voor The Noderunners Download Bot, van jou zodra de betaling binnen is." +credits_title = "{{.Amount}} aan tegoed" +offer = """ +Betalen met Telegram Stars +Een pas dekt deze download. Hij begint zodra de betaling binnen is.""" +intro = """ +Betalen met Telegram Stars +Dezelfde passen en hetzelfde tegoed, betaald met je Stars-saldo in Telegram.""" + +[owner.revenue_lightning] +one = "Lightning: {{.Amount}} uit {{.Count}} aankoop" +other = "Lightning: {{.Amount}} uit {{.Count}} aankopen" + +[owner.revenue_stars] +one = "Stars: {{.Amount}} uit {{.Count}} aankoop, {{.Refunded}} terugbetaald" +other = "Stars: {{.Amount}} uit {{.Count}} aankopen, {{.Refunded}} terugbetaald" diff --git a/web/miniapp/dist/assets/app.js b/web/miniapp/dist/assets/app.js index 1585624..8a1bdfb 100644 --- a/web/miniapp/dist/assets/app.js +++ b/web/miniapp/dist/assets/app.js @@ -1,9 +1,9 @@ -var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function ee(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var te=ee.prototype=new b;te.constructor=ee,_(te,y.prototype),te.isPureReactComponent=!0;var ne=Array.isArray;function re(){}var x={H:null,A:null,T:null,S:null},ie=Object.prototype.hasOwnProperty;function S(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function ae(e,t){return S(e.type,t,e.props)}function oe(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function se(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ce=/\/+/g;function le(e,t){return typeof e==`object`&&e&&e.key!=null?se(``+e.key):t.toString(36)}function ue(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(re,re):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function de(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,de(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+le(e,0):a,ne(o)?(i=``,c!=null&&(i=c.replace(ce,`$&/`)+`/`),de(o,r,i,``,function(e){return e})):o!=null&&(oe(o)&&(o=ae(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(ce,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(ne(e))for(var u=0;u{n.exports=t()})),r=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,te||(te=!0,ae());else{var t=n(l);t!==null&&ce(ee,t.startTime-e)}}}var te=!1,ne=-1,re=5,x=-1;function ie(){return g?!0:!(e.unstable_now()-xt&&ie());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ce(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ae():te=!1}}}var ae;if(typeof y==`function`)ae=function(){y(S)};else if(typeof MessageChannel<`u`){var oe=new MessageChannel,se=oe.port2;oe.port1.onmessage=S,ae=function(){se.postMessage(null)}}else ae=function(){_(S,0)};function ce(t,n){ne=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ne),ne=-1):h=!0,ce(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,te||(te=!0,ae()))),r},e.unstable_shouldYield=ie,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),i=e(((e,t)=>{t.exports=r()})),a=e((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=a()})),s=e((e=>{var t=i(),r=n(),a=o();function s(e){var t=`https://react.dev/errors/`+e;if(1Ee||(e.current=Te[Ee],Te[Ee]=null,Ee--)}function k(e,t){Ee++,Te[Ee]=e.current,e.current=t}var ke=De(null),Ae=De(null),je=De(null),Me=De(null);function Ne(e,t){switch(k(je,t),k(Ae,e),k(ke,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?up(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=up(t),e=dp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Oe(ke),k(ke,e)}function Pe(){Oe(ke),Oe(Ae),Oe(je)}function Fe(e){var t=e.memoizedState;t!==null&&(sh._currentValue=t.memoizedState,k(Me,e)),t=ke.current;var n=dp(t,e.type);t!==n&&(k(Ae,e),k(ke,n))}function Ie(e){Ae.current===e&&(Oe(ke),Oe(Ae)),Me.current===e&&(Oe(Me),sh._currentValue=we)}var Le,Re;function ze(e){if(Le===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Le=t&&t[1]||``,Re=-1()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function ee(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var te=ee.prototype=new b;te.constructor=ee,_(te,y.prototype),te.isPureReactComponent=!0;var ne=Array.isArray;function re(){}var x={H:null,A:null,T:null,S:null},S=Object.prototype.hasOwnProperty;function C(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function w(e,t){return C(e.type,t,e.props)}function ie(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function ae(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var oe=/\/+/g;function se(e,t){return typeof e==`object`&&e&&e.key!=null?ae(``+e.key):t.toString(36)}function ce(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(re,re):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function le(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,le(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+se(e,0):a,ne(o)?(i=``,c!=null&&(i=c.replace(oe,`$&/`)+`/`),le(o,r,i,``,function(e){return e})):o!=null&&(ie(o)&&(o=w(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(oe,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(ne(e))for(var u=0;u{n.exports=t()})),r=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,te||(te=!0,w());else{var t=n(l);t!==null&&oe(ee,t.startTime-e)}}}var te=!1,ne=-1,re=5,x=-1;function S(){return g?!0:!(e.unstable_now()-xt&&S());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&oe(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?w():te=!1}}}var w;if(typeof y==`function`)w=function(){y(C)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=C,w=function(){ae.postMessage(null)}}else w=function(){_(C,0)};function oe(t,n){ne=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ne),ne=-1):h=!0,oe(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,te||(te=!0,w()))),r},e.unstable_shouldYield=S,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),i=e(((e,t)=>{t.exports=r()})),a=e((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=a()})),s=e((e=>{var t=i(),r=n(),a=o();function s(e){var t=`https://react.dev/errors/`+e;if(1we||(e.current=Ce[we],Ce[we]=null,we--)}function j(e,t){we++,Ce[we]=e.current,e.current=t}var De=Te(null),Oe=Te(null),ke=Te(null),Ae=Te(null);function je(e,t){switch(j(ke,t),j(Oe,e),j(De,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?up(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=up(t),e=dp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Ee(De),j(De,e)}function Me(){Ee(De),Ee(Oe),Ee(ke)}function Ne(e){var t=e.memoizedState;t!==null&&(sh._currentValue=t.memoizedState,j(Ae,e)),t=De.current;var n=dp(t,e.type);t!==n&&(j(Oe,e),j(De,n))}function Pe(e){Oe.current===e&&(Ee(De),Ee(Oe)),Ae.current===e&&(Ee(Ae),sh._currentValue=Se)}var Fe,Ie;function Le(e){if(Fe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Fe=t&&t[1]||``,Ie=-1)`:-1i||c[r]!==l[i]){var u=` -`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Be=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?ze(n):``}function He(e,t){switch(e.tag){case 26:case 27:case 5:return ze(e.type);case 16:return ze(`Lazy`);case 13:return e.child!==t&&t!==null?ze(`Suspense Fallback`):ze(`Suspense`);case 19:return ze(`SuspenseList`);case 0:case 15:return Ve(e.type,!1);case 11:return Ve(e.type.render,!1);case 1:return Ve(e.type,!0);case 31:return ze(`Activity`);case 30:return ze(`ViewTransition`);default:return``}}function Ue(e){try{var t=``,n=null;do t+=He(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Re=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Le(n):``}function Be(e,t){switch(e.tag){case 26:case 27:case 5:return Le(e.type);case 16:return Le(`Lazy`);case 13:return e.child!==t&&t!==null?Le(`Suspense Fallback`):Le(`Suspense`);case 19:return Le(`SuspenseList`);case 0:case 15:return ze(e.type,!1);case 11:return ze(e.type.render,!1);case 1:return ze(e.type,!0);case 31:return Le(`Activity`);case 30:return Le(`ViewTransition`);default:return``}}function Ve(e){try{var t=``,n=null;do t+=Be(e,n),n=e,e=e.return;while(e);return t}catch(e){return` Error generating stack: `+e.message+` -`+e.stack}}var We=Object.prototype.hasOwnProperty,Ge=t.unstable_scheduleCallback,Ke=t.unstable_cancelCallback,qe=t.unstable_shouldYield,Je=t.unstable_requestPaint,Ye=t.unstable_now,Xe=t.unstable_getCurrentPriorityLevel,Ze=t.unstable_ImmediatePriority,Qe=t.unstable_UserBlockingPriority,$e=t.unstable_NormalPriority,et=t.unstable_LowPriority,tt=t.unstable_IdlePriority,nt=t.log,rt=t.unstable_setDisableYieldValue,it=null,at=null;function ot(e){if(typeof nt==`function`&&rt(e),at&&typeof at.setStrictMode==`function`)try{at.setStrictMode(it,e)}catch{}}var st=Math.clz32?Math.clz32:ut,ct=Math.log,lt=Math.LN2;function ut(e){return e>>>=0,e===0?32:31-(ct(e)/lt|0)|0}var dt=256,ft=262144,pt=4194304;function mt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function ht(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=mt(n))):i=mt(o):i=mt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=mt(n))):i=mt(o)):i=mt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function gt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function _t(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function xt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function St(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0=xr),wr=` `,Tr=!1;function Er(e,t){switch(e){case`keyup`:return yr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Dr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Or=!1;function kr(e,t){switch(e){case`compositionend`:return Dr(t);case`keypress`:return t.which===32?(Tr=!0,wr):null;case`textInput`:return e=t.data,e===wr&&Tr?null:e;default:return null}}function Ar(e,t){if(Or)return e===`compositionend`||!br&&Er(e,t)?(e=Hn(),Vn=Bn=zn=null,Or=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=$r(n)}}function ti(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ti(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ni(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Qr(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Qr(e.document)}return t}function ri(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var ii=In&&`documentMode`in document&&11>=document.documentMode,ai=null,oi=null,si=null,ci=!1;function li(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ci||ai==null||ai!==Qr(r)||(r=ai,`selectionStart`in r&&ri(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),si&&Zr(si,r)||(si=r,r=Jf(oi,`onSelect`),0>=o,i-=o,aa=1<<32-st(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),o=a(_,o,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),M&&sa(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),o=a(y,o,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),M&&sa(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(o=a(v,o,g),d===null?u=v:d.sibling=v,d=v);return M&&sa(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),o=a(v,o,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),M&&sa(i,g),u}function _(e,r,a,c){if(typeof a==`object`&&a&&a.type===ce&&a.key===null&&a.props.ref===void 0&&(a=a.props.children),typeof a==`object`&&a){switch(a.$$typeof){case oe:a:{for(var l=a.key;r!==null;){if(r.key===l){if(l=a.type,l===ce){if(r.tag===7){n(e,r.sibling),c=i(r,a.props.children),go(c,a),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ge&&co(l)===r.type){n(e,r.sibling),c=i(r,a.props),go(c,a),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}a.type===ce?(c=Ki(a.props.children,e.mode,c,a.key),go(c,a),c.return=e,e=c):(c=Gi(a.type,a.key,a.props,null,e.mode,c),go(c,a),c.return=e,e=c)}return o(e);case se:a:{for(l=a.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===a.containerInfo&&r.stateNode.implementation===a.implementation){n(e,r.sibling),c=i(r,a.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Yi(a,e.mode,c),c.return=e,e=c}return o(e);case ge:return a=co(a),_(e,r,a,c)}if(Ce(a))return h(e,r,a,c);if(E(a)){if(l=E(a),typeof l!=`function`)throw Error(s(150));return a=l.call(a),g(e,r,a,c)}if(typeof a.then==`function`)return _(e,r,ho(a),c);if(a.$$typeof===fe)return _(e,r,Pa(e,a),c);_o(e,a)}return typeof a==`string`&&a!==``||typeof a==`number`||typeof a==`bigint`?(a=``+a,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,a),c.return=e,e=c):(n(e,r),c=qi(a,e.mode,c),c.return=e,e=c),o(e)):n(e,r)}return function(e,t,n,r){try{mo=0;var i=_(e,t,n,r);return po=null,i}catch(t){if(t===no||t===io)throw t;var a=Vi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var yo=vo(!0),bo=vo(!1),xo=!1;function So(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Co(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function wo(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function To(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,W&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Ri(e),Li(e,null,n),t}return Pi(e,r,t,n),Ri(e)}function Eo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,wt(e,n)}}function Do(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Oo=!1;function ko(){if(Oo){var e=qa;if(e!==null)throw e}}function Ao(e,t,n,r){Oo=!1;var i=e.updateQueue;xo=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(q&f)===f:(r&f)===f){f!==0&&f===Ka&&(Oo=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=S({},d,f);break a;case 2:xo=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),sd|=o,e.lanes=o,e.memoizedState=d}}function jo(e,t){if(typeof e!=`function`)throw Error(s(191,e));e.call(t)}function Mo(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=D.T,s={};s.types=o===null?null:o.types,D.T=s,hc(e,!1,t,n);try{var c=i(),l=D.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?mc(e,t,Xa(c,r),jd(e)):mc(e,t,r,jd(e))}catch(n){mc(e,t,{then:function(){},status:`rejected`,reason:n},jd())}finally{O.p=a,o!==null&&s.types!==null&&(o.types=s.types),D.T=o}}function ic(){}function ac(e,t,n,r){if(e.tag!==5)throw Error(s(476));var i=oc(e).queue;rc(e,i,t,we,n===null?ic:function(){return sc(e),n(r)})}function oc(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:we,baseState:we,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:gs,lastRenderedState:we},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:gs,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function sc(e){var t=oc(e);t.next===null&&(t=e.alternate.memoizedState),mc(e,t.next.queue,{},jd())}function cc(){return Na(sh)}function lc(){return R().memoizedState}function uc(){return R().memoizedState}function dc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=jd();e=wo(n);var r=To(t,e,n);r!==null&&(Pd(r,t,n),Eo(r,t,n)),t={cache:za()},e.payload=t;return}t=t.return}}function fc(e,t,n){var r=jd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},gc(e)?_c(t,n):(n=Fi(e,t,n,r),n!==null&&(Pd(n,e,r),vc(n,t,r)))}function pc(e,t,n){mc(e,t,n,jd())}function mc(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(gc(e))_c(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Xr(s,o))return Pi(e,t,i,0),G===null&&Ni(),!1}catch{}if(n=Fi(e,t,i,r),n!==null)return Pd(n,e,r),vc(n,t,r),!0}return!1}function hc(e,t,n,r){if(r={lane:2,revertLane:Pf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},gc(e)){if(t)throw Error(s(479))}else t=Fi(e,n,r,2),t!==null&&Pd(t,e,2)}function gc(e){var t=e.alternate;return e===P||t!==null&&t===P}function _c(e,t){Zo=Xo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,wt(e,n)}}var yc={readContext:Na,use:ms,useCallback:L,useContext:L,useEffect:L,useImperativeHandle:L,useLayoutEffect:L,useInsertionEffect:L,useMemo:L,useReducer:L,useRef:L,useState:L,useDebugValue:L,useDeferredValue:L,useTransition:L,useSyncExternalStore:L,useId:L,useHostTransitionStatus:L,useFormState:L,useActionState:L,useOptimistic:L,useMemoCache:L,useCacheRefresh:L,useEffectEvent:L},bc={readContext:Na,use:ms,useCallback:function(e,t){return ds().memoizedState=[e,t===void 0?null:t],e},useContext:Na,useEffect:Ws,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Hs(4194308,4,Xs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Hs(4194308,4,e,t)},useInsertionEffect:function(e,t){Hs(4,2,e,t)},useMemo:function(e,t){var n=ds();t=t===void 0?null:t;var r=e();if(Qo){ot(!0);try{e()}finally{ot(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ds();if(n!==void 0){var i=n(t);if(Qo){ot(!0);try{n(t)}finally{ot(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=fc.bind(null,P,e),[r.memoizedState,e]},useRef:function(e){var t=ds();return e={current:e},t.memoizedState=e},useState:function(e){e=Es(e);var t=e.queue,n=pc.bind(null,P,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Qs,useDeferredValue:function(e,t){return tc(ds(),e,t)},useTransition:function(){var e=Es(!1);return e=rc.bind(null,P,e.queue,!0,!1),ds().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=P,i=ds();if(M){if(n===void 0)throw Error(s(407));n=n()}else{if(n=t(),G===null)throw Error(s(349));q&127||xs(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,Ws(Cs.bind(null,r,a,e),[e]),r.flags|=2048,Bs(9,{destroy:void 0},Ss.bind(null,r,a,n,t),null),n},useId:function(){var e=ds(),t=G.identifierPrefix;if(M){var n=oa,r=aa;n=(r&~(1<<32-st(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=$o++,0<\/script>`,a=a.removeChild(a.firstChild);break;case`select`:a=typeof r.is==`string`?o.createElement(`select`,{is:r.is}):o.createElement(`select`),r.multiple?a.multiple=!0:r.size&&(a.size=r.size);break;default:a=typeof r.is==`string`?o.createElement(i,{is:r.is}):o.createElement(i)}}a[jt]=t,a[Mt]=r;a:for(o=t.child;o!==null;){if(o.tag===5||o.tag===6)a.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===t)break a;for(;o.sibling===null;){if(o.return===null||o.return===t)break a;o=o.return}o.sibling.return=o.return,o=o.sibling}t.stateNode=a;a:switch(np(a,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&gl(t)}}return V(t),t.subtreeFlags&=-33554433,_l(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&gl(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(s(166));if(e=je.current,ya(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=fa,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[jt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||ep(e.nodeValue,n)),e||ga(t,!0)}else e=lp(e).createTextNode(r),e[jt]=t,t.stateNode=e}return V(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=ya(t),n!==null){if(e===null){if(!r)throw Error(s(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(s(557));e[jt]=t}else ba(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;V(t),e=!1}else n=xa(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Wo(t),t):(Wo(t),null);if(t.flags&128)throw Error(s(558))}return V(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=ya(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(s(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(s(317));i[jt]=t}else ba(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;V(t),i=!1}else i=xa(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(Wo(t),t):(Wo(t),null)}return Wo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),a=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(a=r.memoizedState.cachePool.pool),a!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),yl(t,t.updateQueue),V(t),null);case 4:return Pe(),e===null&&Wf(t.stateNode.containerInfo),t.flags|=67108864,V(t),null;case 10:return Da(t.type),V(t),null;case 19:if(qo(t),r=t.memoizedState,r===null)return V(t),null;if(i=!!(t.flags&128),a=r.rendering,a===null){if(i)bl(r,!1);else{if(Y!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(a=Jo(e),a!==null){for(t.flags|=128,bl(r,!1),e=a.updateQueue,t.updateQueue=e,yl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Wi(n,e),n=n.sibling;return Ko(t,Go.current&1|2),M&&sa(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ye()>_d&&(t.flags|=128,i=!0,bl(r,!1),t.lanes=4194304)}}else{if(!i){if(e=Jo(a),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,yl(t,e),bl(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!a.alternate&&!M)return V(t),null}else 2*Ye()-r.renderingStartTime>_d&&n!==536870912&&(t.flags|=128,i=!0,bl(r,!1),t.lanes=4194304)}r.isBackwards?(a.sibling=t.child,t.child=a):(e=r.last,e===null?t.child=a:e.sibling=a,r.last=a)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ye(),e.sibling=null,a=Go.current,a=i?a&1|2:a&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||M?Ko(t,a):(n=a,k(Ro,t),k(Go,n),zo===null&&(zo=t)),M&&sa(t,r.treeForkCount),e}return V(t),null;case 22:case 23:return Wo(t),Lo(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(V(t),t.subtreeFlags&6&&(t.flags|=8192)):V(t),n=t.updateQueue,n!==null&&yl(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&Oe(Qa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Da(N),V(t),null;case 25:return null;case 30:return t.flags|=33554432,V(t),null}throw Error(s(156,t.tag))}function Sl(e,t){switch(ua(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Da(N),Pe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ie(t),null;case 31:if(t.memoizedState!==null){if(Wo(t),t.alternate===null)throw Error(s(340));ba()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Wo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));ba()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return qo(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Pe(),null;case 10:return Da(t.type),null;case 22:case 23:return Wo(t),Lo(),e!==null&&Oe(Qa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Da(N),null;case 25:return null;default:return null}}function Cl(e,t){switch(ua(t),t.tag){case 3:Da(N),Pe();break;case 26:case 27:case 5:Ie(t);break;case 4:Pe();break;case 31:t.memoizedState!==null&&Wo(t);break;case 13:Wo(t);break;case 19:qo(t);break;case 10:Da(t.type);break;case 22:case 23:Wo(t),Lo(),e!==null&&Oe(Qa);break;case 24:Da(N)}}function wl(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Tl(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function El(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Mo(t,n)}catch(t){Z(e,e.return,t)}}}function Dl(e,t,n){n.props=Dc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function Ol(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:var i=e.stateNode,a=Ei(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Pp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Fp(e);h(e.child,!1,Qp,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function kl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}}function Al(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),np(r,t,n),r[jt]=e,Gt(r),t=r;break a;case`link`:if(a=Gm(`link`,`href`,i).get(t+(n.href||``))){for(o=0;og&&(o=g,g=h,h=o);var _=ei(s,h),v=ei(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,D.T=null,n=wd,wd=null;var a=bd,o=Sd;if(X=0,xd=bd=null,Sd=0,W&6)throw Error(s(331));var c=W;if(W|=4,Zu(a.current),Uu(a,a.current,o,n),W=c,Df(0,!1),at&&typeof at.onPostCommitFiberRoot==`function`)try{at.onPostCommitFiberRoot(it,a)}catch{}return!0}finally{O.p=i,D.T=r,uf(e,t)}}function pf(e,t,n){t=Zi(n,t),t=Nc(e.stateNode,t,2),e=To(e,t,2),e!==null&&(xt(e,2),Ef(e))}function Z(e,t,n){if(e.tag===3)pf(e,e,n);else for(;t!==null;){if(t.tag===3){pf(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(yd===null||!yd.has(r))){e=Zi(n,e),n=Pc(2),r=To(t,n,2),r!==null&&(Fc(n,r,t,e),xt(r,2),Ef(r));break}}t=t.return}}function mf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new td;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(ad=!0,i.add(n),e=hf.bind(null,e,t,n),t.then(e,e))}function hf(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,G===e&&(q&n)===n&&(Y===4||Y===3&&(q&62914560)===q&&300>Ye()-hd?W&2?ld|=n:Vd(e,0):ld|=n,dd===q&&(dd=0)),Ef(e)}function gf(e,t){t===0&&(t=yt()),e=Ii(e,t),e!==null&&(xt(e,t),Ef(e))}function _f(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),gf(e,n)}function vf(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(s(314))}r!==null&&r.delete(t),gf(e,n)}function yf(e,t){return Ge(e,t)}var bf=null,xf=null,Sf=!1,Cf=!1,wf=!1,Tf=0;function Ef(e){e!==xf&&e.next===null&&(xf===null?bf=xf=e:xf=xf.next=e),Cf=!0,Sf||(Sf=!0,Nf())}function Df(e,t){if(!wf&&Cf){wf=!0;do for(var n=!1,r=bf;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-st(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,Mf(r,a))}else a=q,a=ht(r,r===G?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||gt(r,a)||(n=!0,Mf(r,a))}r=r.next}while(n);wf=!1}}function Of(){kf()}function kf(){Cf=Sf=!1;var e=0;Tf!==0&&hp()&&(e=Tf);for(var t=Ye(),n=null,r=bf;r!==null;){var i=r.next,a=Af(r,t);a===0?(r.next=null,n===null?bf=i:n.next=i,i===null&&(xf=n)):(n=r,(e!==0||a&3)&&(Cf=!0)),r=i}X!==0&&X!==5||Df(e,!1),Tf!==0&&(Tf=0)}function Af(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&ap(d)&&(c=c.responseEnd,o+=u*(c$m){s.length=o;break}f=new Promise(jp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Tm(e,t,n){var r=wm;if(r&&typeof t==`string`&&t){var i=fn(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),ym.has(i)||(ym.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),np(t,`link`,e),Gt(t),r.head.appendChild(t)))}}function Em(e){xm.D(e),Tm(`dns-prefetch`,e,null)}function Dm(e,t){xm.C(e,t),Tm(`preconnect`,e,t)}function Om(e,t,n){xm.L(e,t,n);var r=wm;if(r&&e&&t){var i=`link[rel="preload"][as="`+fn(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+fn(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+fn(n.imageSizes)+`"]`)):i+=`[href="`+fn(e)+`"]`;var a=i;switch(t){case`style`:a=Pm(e);break;case`script`:a=Rm(e)}if(!(vm.has(a)||(e=S({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vm.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Fm(a))||t===`script`&&r.querySelector(zm(a))))){var o=r.createElement(`link`);np(o,`link`,e),t===`style`&&(o[zt]=!0,o.onload=o.onerror=function(){Kt(o)}),Gt(o),r.head.appendChild(o)}}}function km(e,t){xm.m(e,t);var n=wm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+fn(r)+`"][href="`+fn(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rm(e)}if(!vm.has(a)&&(e=S({rel:`modulepreload`,href:e},t),vm.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zm(a)))return}r=n.createElement(`link`),np(r,`link`,e),Gt(r),n.head.appendChild(r)}}}function Am(e,t,n){xm.S(e,t,n);var r=wm;if(r&&e){var i=Wt(r).hoistableStyles,a=Pm(e);t=t||`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Fm(a)))s.loading=5;else{e=S({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vm.get(a))&&Hm(e,n);var c=o=r.createElement(`link`);Gt(c),np(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jm(e,t){xm.X(e,t);var n=wm;if(n&&e){var r=Wt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=S({src:e,async:!0},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Gt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mm(e,t){xm.M(e,t);var n=wm;if(n&&e){var r=Wt(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=S({src:e,async:!0,type:`module`},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Gt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nm(e,t,n,r){var i=(i=je.current)?bm(i):null;if(!i)throw Error(s(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Pm(n.href),t=Wt(i).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pm(n.href);var a=Wt(i).hoistableStyles,o=a.get(e);if(o||(i=i.ownerDocument||i,o={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},a.set(e,o),(a=i.querySelector(Fm(e)))?a._p||(o.instance=a,o.state.loading=5):(a=vm.get(e),a||(a={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vm.set(e,a)),Lm(i,e,a,o.state))),t&&r===null)throw Error(s(528,``));return o}if(t&&r!==null)throw Error(s(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Rm(n),t=Wt(i).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(s(444,e))}}function Pm(e){return`href="`+fn(e)+`"`}function Fm(e){return`link[rel="stylesheet"][`+e+`]`}function Im(e){return S({},e,{"data-precedence":e.precedence,precedence:null})}function Lm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[zt]){r.loading=1;return}}else t=e.createElement(`link`),t[zt]=!0,t.onload=t.onerror=Kt.bind(null,t),np(t,`link`,n),Gt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Rm(e){return`[src="`+fn(e)+`"]`}function zm(e){return`script[async]`+e}function Bm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+fn(n.href)+`"]`);if(r)return t.instance=r,Gt(r),r;var i=S({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Gt(r),np(r,`style`,i),Vm(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Pm(n.href);var a=e.querySelector(Fm(i));if(a)return t.state.loading|=4,t.instance=a,Gt(a),a;r=Im(n),(i=vm.get(i))&&Hm(r,i),a=(e.ownerDocument||e).createElement(`link`),Gt(a);var o=a;return o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),t.state.loading|=4,Vm(a,n.precedence,e),t.instance=a;case`script`:return a=Rm(n.src),(i=e.querySelector(zm(a)))?(t.instance=i,Gt(i),i):(r=n,(i=vm.get(a))&&(r=S({},n),Um(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Gt(i),np(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(s(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vm(r,n.precedence,e));return t.instance}function Vm(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qm(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jm(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function Ym(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Xm(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function Zm(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=Xm(t),e.suspenseyImages.push(t)),e=rh.bind(e),t.decode().then(e,e))}function Qm(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pm(r.href),a=t.querySelector(Fm(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=nh.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Gt(a);return}a=t.ownerDocument||t,r=Im(r),(i=vm.get(i))&&Hm(r,i),a=a.createElement(`link`),Gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=nh.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $m=0;function eh(e,t){return e.stylesheets&&e.count===0&&ah(e,e.stylesheets),0$m?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function th(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)ah(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function nh(){this.count--,th(this)}function rh(){this.imgCount--,th(this)}var ih=null;function ah(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ih=new Map,t.forEach(oh,e),ih=null,nh.call(e))}function oh(e,t){if(!(t.state.loading&4)){var n=ih.get(e);if(n)var r=n.get(null);else{n=new Map,ih.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=s()})),l=n(),u=c(),d=window.Telegram?.WebApp;function f(){return d?.initData??``}function p(e){try{e===`tap`?d?.HapticFeedback?.selectionChanged():d?.HapticFeedback?.notificationOccurred(e)}catch{}}function m(e){return new Promise(t=>{d&&d.isVersionAtLeast(`6.2`)?d.showConfirm(e,t):t(window.confirm(e))})}function h(e){d?d.openLink(e):window.open(e,`_blank`,`noopener`)}function g(e){d?d.openTelegramLink(e):window.open(e,`_blank`,`noopener`)}async function _(e){try{return await navigator.clipboard.writeText(e),!0}catch{let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t),t.select();let n=!1;try{n=document.execCommand(`copy`)}catch{n=!1}return t.remove(),n}}var v=class extends Error{constructor(e,t,n,r=!1){super(n),this.status=e,this.code=t,this.upgradable=r}};async function y(e,t,n){let r;try{r=await fetch(`/app/api/`+t,{method:e,headers:{Authorization:`tma `+f(),...n===void 0?{}:{"Content-Type":`application/json`}},body:n===void 0?void 0:JSON.stringify(n)})}catch{throw new v(0,`network`,``)}let i=null;try{i=await r.json()}catch{i=null}if(!r.ok){let e=i??{};throw new v(r.status,e.error??`internal`,e.message??``,e.upgradable??!1)}return i}var b={},ee=`en`,te=new Intl.PluralRules(`en`);function ne(e){try{return Intl.NumberFormat.supportedLocalesOf([e])[0]??`en`}catch{return`en`}}function re(e){b=e.messages,ee=ne(e.lang),te=new Intl.PluralRules(ee),document.documentElement.lang=e.lang,document.documentElement.dir=e.dir}function x(e,t){let n=b[e];return n===void 0?e:(typeof n!=`string`&&(n=n[te.select(Number(t?.Count??0))]??n.other??``),n.replace(/\{(\w+)\}/g,(e,n)=>t&&n in t?String(t[n]):``))}function ie(e){return new Intl.NumberFormat(ee).format(e)}function S(e){return x(`unit.sats`,{Count:e,N:ie(e)})}function ae(e){return new Intl.NumberFormat(ee,{style:`percent`,maximumFractionDigits:0}).format(e)}function oe(e){let t=(e,t)=>new Intl.NumberFormat(ee,{minimumFractionDigits:0,maximumFractionDigits:t}).format(e),n=1024;if(e=100?0:1)+` MB`}return t(e/(n*n*n),2)+` GB`}function se(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=e=>String(e).padStart(2,`0`);return n>0?`${n}:${i(r)}:${i(t%60)}`:`${r}:${i(t%60)}`}function ce(e){return e<60?x(`unit.seconds`,{Count:Math.max(1,Math.round(e))}):e<3600?x(`unit.minutes`,{Count:Math.round(e/60)}):x(`unit.hours`,{Count:Math.round(e/3600)})}function le(e){return new Intl.DateTimeFormat(ee,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(e))}function ue(e){return new Intl.DateTimeFormat(ee,{dateStyle:`medium`}).format(new Date(e))}function de(e){return e===`best`?x(`btn.best`):/^\d+$/.test(e)?x(`btn.res`,{Height:e}):e===`mp3`||e===`m4a`||e===`thumb`?x(`btn.`+e):e.startsWith(`subs:`)?x(`btn.subs`,{Lang:e.slice(5)}):e}var fe=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),C=e(((e,t)=>{t.exports=fe()}))(),pe=(0,l.createContext)(null);function me(){let e=(0,l.useContext)(pe);if(!e)throw Error(`no app context`);return e}function he(e){if(e instanceof v){if(e.message)return e.message;if(e.code===`network`)return x(`app.error.network`)}return x(`app.error.generic`)}function ge(e,t,n=0){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(!0),[u,d]=(0,l.useState)(0),f=(0,l.useRef)(e);return f.current=e,(0,l.useEffect)(()=>{let e=!0,t,r=()=>{f.current().then(t=>{e&&(i(t),o(null))}).catch(t=>e&&o(t)).finally(()=>{e&&(c(!1),n>0&&(t=window.setTimeout(a,n)))})},a=()=>{document.hidden?t=window.setTimeout(a,n):r()};return r(),()=>{e=!1,window.clearTimeout(t)}},[...t,u,n]),{data:r,error:a,loading:s,reload:()=>d(e=>e+1),set:i}}var _e=[],ve=!1;function ye(){d&&(ve||(d.BackButton.onClick(()=>_e[_e.length-1]?.current?.()),ve=!0),_e.length>0?d.BackButton.show():d.BackButton.hide())}function be(e){let t=(0,l.useRef)(e);t.current=e;let n=e!==null;(0,l.useEffect)(()=>{if(n)return _e.push(t),ye(),()=>{let e=_e.indexOf(t);e>=0&&_e.splice(e,1),ye()}},[n])}function w(e){return(0,C.jsxs)(`section`,{className:`section`,children:[(e.title||e.action)&&(0,C.jsxs)(`div`,{className:`section-title`,children:[(0,C.jsx)(`span`,{children:e.title}),e.action]}),(0,C.jsx)(`div`,{className:`card`,children:e.children}),e.note&&(0,C.jsx)(`div`,{className:`note`,children:e.note})]})}function T(e){let t=(0,C.jsxs)(C.Fragment,{children:[e.before,(0,C.jsxs)(`div`,{className:`cell-body`,children:[(0,C.jsx)(`div`,{className:`cell-title`+(e.wrap?` wrap`:``),children:e.title}),e.sub&&(0,C.jsx)(`div`,{className:`cell-sub`,children:e.sub})]}),(e.after||e.chevron)&&(0,C.jsxs)(`div`,{className:`cell-after`,children:[e.after,e.chevron&&(0,C.jsx)(`span`,{className:`chevron`})]})]});return e.onClick?(0,C.jsx)(`button`,{className:`cell`,onClick:e.onClick,children:t}):(0,C.jsx)(`div`,{className:`cell`,children:t})}function E(e){let[t,n]=(0,l.useState)(!1),r=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{r.current=!1},[]);let i=()=>{if(t||!e.onClick)return;p(`tap`);let i=e.onClick();i instanceof Promise&&(n(!0),i.finally(()=>r.current&&n(!1)))},a=[`btn`,e.kind&&e.kind!==`primary`?e.kind:``,e.small?`small`:``,e.wide?`wide`:``];return(0,C.jsx)(`button`,{className:a.filter(Boolean).join(` `),onClick:i,disabled:e.disabled||t,children:t?(0,C.jsx)(`span`,{className:`spinner`}):e.children})}function xe(e){return(0,C.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":e.checked,"aria-label":e.label,onClick:()=>{p(`tap`),e.onChange(!e.checked)}})}function Se(e){return(0,C.jsx)(`select`,{className:`select`+(e.compact?` compact`:``),"aria-label":e.label,disabled:e.disabled,value:e.value,onChange:t=>e.onChange(t.target.value),children:e.options.map(e=>(0,C.jsx)(`option`,{value:e.value,children:e.label},e.value))})}function Ce(e){return(0,C.jsx)(`div`,{className:`segmented`,role:`tablist`,children:e.options.map(t=>(0,C.jsx)(`button`,{role:`tab`,"aria-selected":t.value===e.value,onClick:()=>e.onChange(t.value),children:t.label},t.value))})}function D(e){let t=Math.max(0,Math.min(1,e.value))*100;return(0,C.jsx)(`div`,{className:`meter`+(e.busy?` busy`:``),children:(0,C.jsx)(`div`,{style:{width:t+`%`}})})}function O(){return(0,C.jsx)(`div`,{className:`spinner`,role:`progressbar`})}function we(e){return(0,C.jsx)(`div`,{className:`empty`,children:e.children})}function Te(e){let{data:t,error:n,loading:r,reload:i}=e.of;return t===null?r?(0,C.jsx)(O,{}):(0,C.jsxs)(we,{children:[(0,C.jsx)(`p`,{children:he(n)}),(0,C.jsx)(E,{kind:`soft`,onClick:i,children:x(`app.retry`)})]}):(0,C.jsx)(C.Fragment,{children:e.children(t)})}function Ee(e){return(0,C.jsx)(`div`,{className:`sheet-back`,onClick:e.onClose,children:(0,C.jsx)(`div`,{className:`sheet`,role:`dialog`,"aria-modal":`true`,onClick:e=>e.stopPropagation(),children:e.children})})}function De(){let{me:e,go:t}=me(),n=ge(()=>y(`GET`,`history?limit=5`),[]),r=e.pass_until>Date.now(),i=e.limits;return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(w,{children:[(0,C.jsxs)(`div`,{className:`pad`,children:[(0,C.jsx)(`div`,{className:`hint`,children:x(`app.home.hello`,{Name:e.name})}),(0,C.jsx)(`div`,{className:`big`,children:x(r?`app.home.pass_active`:`app.home.plan_free`)}),(0,C.jsx)(`div`,{className:`hint`,children:r?x(`app.pass_until`,{Until:le(e.pass_until)}):x(`app.home.plan_free_hint`)})]}),(0,C.jsx)(T,{title:x(`app.home.balance`),after:(0,C.jsx)(`b`,{children:S(e.balance)}),chevron:e.payments,onClick:e.payments?()=>t({tab:`buy`}):void 0})]}),(0,C.jsx)(w,{title:x(`app.home.today`),children:(0,C.jsxs)(`div`,{className:`pad stack`,children:[(0,C.jsx)(Oe,{label:x(`app.home.downloads`),used:e.usage.downloads,max:i.daily_downloads,format:ie}),(0,C.jsx)(Oe,{label:x(`app.home.volume`),used:e.usage.bytes,max:i.daily_bytes,format:oe})]})}),(0,C.jsx)(ke,{}),(0,C.jsx)(w,{title:x(`app.home.recent`),action:(0,C.jsx)(E,{kind:`plain`,onClick:()=>t({tab:`home`,page:`history`}),children:x(`app.home.all_history`)}),children:n.data&&n.data.items.length>0?n.data.items.map(e=>(0,C.jsx)(k,{item:e},e.id)):(0,C.jsx)(`div`,{className:`empty`,children:n.loading?``:x(`app.history.empty`)})})]})}function Oe(e){let t=e.max<=0;return(0,C.jsxs)(`div`,{children:[(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`span`,{className:`grow`,children:e.label}),(0,C.jsx)(`span`,{className:`hint`,children:t?x(`app.home.used_unlimited`,{Used:e.format(e.used)}):x(`app.home.used_of`,{Used:e.format(e.used),Max:e.format(e.max)})})]}),(0,C.jsx)(D,{value:t?0:e.used/e.max})]})}function k(e){let{notify:t,fail:n}=me(),r=e.item;return(0,C.jsx)(T,{title:r.title||x(`app.untitled`),sub:[de(r.profile),r.size>0?oe(r.size):``,le(r.at)].filter(Boolean).join(` · `),after:(0,C.jsx)(E,{small:!0,kind:`soft`,onClick:async()=>{try{await y(`POST`,`history/`+r.id+`/resend`),t(x(`app.sent_to_chat`))}catch(e){n(e)}},children:x(`app.history.resend`)})})}function ke(){let{go:e,notify:t}=me(),[n,r]=(0,l.useState)(``),[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(null),c=e=>s({text:he(e),upgradable:e instanceof v&&e.upgradable}),u=async()=>{s(null),a(null);try{a(await y(`POST`,`probe`,{url:n.trim()}))}catch(e){c(e)}},d=async n=>{if(i){s(null);try{await y(`POST`,`download`,{url:i.url,profile:n}),a(null),r(``),t(x(`app.sent_to_chat`)),e({tab:`queue`})}catch(e){c(e)}}};return(0,C.jsx)(w,{title:x(`app.home.paste_title`),children:(0,C.jsxs)(`div`,{className:`pad stack`,children:[(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`input`,{className:`input grow`,type:`url`,inputMode:`url`,autoCapitalize:`off`,autoCorrect:`off`,spellCheck:!1,dir:`ltr`,placeholder:x(`app.home.paste_placeholder`),value:n,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&n.trim()&&u()}}),(0,C.jsx)(E,{onClick:u,disabled:!n.trim(),children:x(`app.home.look_up`)})]}),o&&(0,C.jsxs)(`div`,{className:`stack`,children:[(0,C.jsx)(`div`,{className:`error`,children:o.text}),o.upgradable&&(0,C.jsx)(E,{kind:`soft`,onClick:()=>e({tab:`buy`}),children:x(`app.see_plans`)})]}),i&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`div`,{className:`cell-title wrap`,children:i.title||x(`app.untitled`)}),(0,C.jsx)(`div`,{className:`hint`,children:[i.uploader,i.duration>0?se(i.duration):``,i.site].filter(Boolean).join(` · `)})]}),(0,C.jsx)(`div`,{className:`row wrap`,children:i.options.map(e=>(0,C.jsx)(E,{kind:`soft`,onClick:()=>d(e.profile),children:e.size?x(`btn.with_size`,{Label:de(e.profile),Size:oe(e.size)}):de(e.profile)},e.profile))})]})]})})}function Ae(e){let{notify:t,fail:n,reload:r}=me(),[i,a]=(0,l.useState)(e.purchase),[o,s]=(0,l.useState)(Date.now()),c=(0,l.useRef)(e.onPaid);c.current=e.onPaid,(0,l.useEffect)(()=>{if(i.status!==`pending`)return;let e=!0,t=window.setInterval(()=>{document.hidden||y(`GET`,`purchase/`+i.id).then(t=>{e&&t.status!==`pending`&&(a(e=>({...e,...t})),t.status===`paid`&&(p(`success`),r(),c.current?.(t)))}).catch(()=>void 0)},2500),n=window.setInterval(()=>s(Date.now()),1e3);return()=>{e=!1,window.clearInterval(t),window.clearInterval(n)}},[i.id,i.status,r]);let u=x(`product.`+i.product);if(i.status===`paid`)return(0,C.jsxs)(`div`,{className:`stack center`,children:[(0,C.jsx)(`div`,{className:`paid-mark`,children:`✓`}),(0,C.jsx)(`div`,{className:`big`,children:x(`app.invoice.paid`)}),(0,C.jsx)(`div`,{children:x(`app.invoice.paid_text`,{Product:u,Amount:S(i.amount)})}),i.pass_until?(0,C.jsx)(`div`,{className:`hint`,children:x(`app.pass_until`,{Until:le(i.pass_until)})}):null,i.balance!==void 0&&(0,C.jsx)(`div`,{className:`hint`,children:x(`app.balance_is`,{Balance:S(i.balance)})}),(0,C.jsx)(E,{wide:!0,onClick:e.onDone,children:x(`app.done`)})]});if(i.status!==`pending`)return(0,C.jsxs)(`div`,{className:`stack center`,children:[(0,C.jsx)(`div`,{className:`big`,children:x(`app.invoice.`+i.status)}),(0,C.jsx)(`div`,{className:`hint`,children:x(`app.invoice.closed_text`)}),(0,C.jsx)(E,{wide:!0,onClick:e.onDone,children:x(`app.close`)})]});let d=Math.max(0,Math.floor((i.expires_at-o)/1e3)),f=i.bolt11??``;return(0,C.jsxs)(`div`,{className:`stack`,children:[(0,C.jsxs)(`div`,{className:`center`,children:[(0,C.jsx)(`div`,{className:`hint`,children:u}),(0,C.jsx)(`div`,{className:`big`,children:S(i.amount)})]}),i.qr&&(0,C.jsx)(`img`,{className:`qr`,src:i.qr,alt:x(`app.invoice.qr_alt`)}),(0,C.jsxs)(`div`,{className:`mono hint center`,children:[f.slice(0,24),`…`,f.slice(-12)]}),(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,kind:`soft`,onClick:async()=>{await _(f)?t(x(`app.copied`)):n(null)},children:x(`app.invoice.copy`)})}),(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,onClick:()=>h(window.location.origin+`/pay/`+i.id),children:x(`btn.open_wallet`)})})]}),(0,C.jsx)(`div`,{className:`center hint`,role:`timer`,children:d>0?x(`app.invoice.waiting`,{Time:se(d)}):x(`app.invoice.checking`)}),(0,C.jsx)(`div`,{className:`center`,children:(0,C.jsx)(E,{kind:`plain`,onClick:async()=>{try{await y(`POST`,`purchase/`+i.id+`/cancel`)}catch{}e.onDone()},children:x(`app.invoice.cancel`)})})]})}function je(){let{notify:e,fail:t}=me(),n=ge(()=>y(`GET`,`queue`),[],2e3),[r,i]=(0,l.useState)(null),a=async r=>{if(await m(x(`app.queue.cancel_confirm`,{Title:r.title||x(`app.untitled`)}))){try{await y(`POST`,`queue/`+r.id+`/cancel`),e(x(`app.queue.cancelled`))}catch(e){t(e)}n.reload()}},o=async r=>{try{let t=await y(`POST`,`queue/`+r.id+`/prioritize`);t.done?e(x(`app.queue.prioritized`)):t.purchase&&i(t.purchase)}catch(e){t(e)}n.reload()};return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(w,{title:x(`app.queue.title`),note:x(`app.queue.note`),children:(0,C.jsx)(Te,{of:n,children:e=>e.jobs.length===0?(0,C.jsx)(we,{children:x(`app.queue.empty`)}):e.jobs.map(e=>(0,C.jsx)(Ne,{job:e,onCancel:()=>a(e),onPrioritize:()=>o(e)},e.id))})}),r&&(0,C.jsx)(Ee,{onClose:()=>i(null),children:(0,C.jsx)(Ae,{purchase:r,onPaid:()=>n.reload(),onDone:()=>{i(null),n.reload()}})})]})}function Me(e){return e.status===`queued`?x(`app.queue.waiting`,{Position:e.position??1,Wait:ce(e.wait_seconds??0)}):e.status===`delivering`||e.stage===`uploading`?x(`app.queue.sending`):e.stage===`processing`?x(`app.queue.processing`):e.progress>0?x(`app.queue.downloading_pct`,{Percent:ae(e.progress)}):x(`app.queue.downloading`)}function Ne(e){let t=e.job,n=t.status!==`queued`&&(t.progress<=0||t.stage===`processing`||t.status===`delivering`);return(0,C.jsx)(`div`,{className:`cell`,children:(0,C.jsxs)(`div`,{className:`cell-body`,children:[(0,C.jsx)(`div`,{className:`cell-title`,children:t.title||x(`app.untitled`)}),(0,C.jsxs)(`div`,{className:`cell-sub`,children:[de(t.profile),` · `,Me(t)]}),t.status!==`queued`&&(0,C.jsx)(D,{value:t.progress,busy:n}),(t.can_cancel||t.can_prioritize)&&(0,C.jsxs)(`div`,{className:`row`,style:{marginBlockStart:8},children:[t.can_prioritize&&(0,C.jsx)(E,{small:!0,onClick:e.onPrioritize,children:x(`app.queue.prioritize`,{Price:S(t.skip_price??0)})}),t.can_cancel&&(0,C.jsx)(E,{small:!0,kind:`danger`,onClick:e.onCancel,children:x(`btn.cancel`)})]})]})})}function Pe(e){let{me:t,go:n,back:r,fail:i}=me(),a=ge(()=>y(`GET`,`products`),[]),o=ge(()=>y(`GET`,`groups`),[]),[s,c]=(0,l.useState)(e.target??null),[u,d]=(0,l.useState)(null),[f,p]=(0,l.useState)(!1),m=u?3:s?2:1;be(m===2&&!e.target?()=>c(null):m===3&&u?.status!==`pending`?()=>d(null):null);let h=async(e,t)=>{if(!f){p(!0);try{d(await y(`POST`,`purchase`,{target:s,product:e,amount:t}))}catch(e){i(e)}p(!1)}},g=o.data?.groups.find(e=>e.id===s),_=s===`me`?x(`app.buy.for_me`):g?.title??x(`app.buy.for_group`);return(0,C.jsx)(Te,{of:a,children:i=>i.enabled?(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`div`,{className:`steps`,"aria-label":x(`app.buy.step`,{Step:m,Total:3}),children:[1,2,3].map(e=>(0,C.jsx)(`span`,{className:e<=m?`on`:``},e))}),m===1&&(0,C.jsxs)(w,{title:x(`app.buy.target_title`),note:x(`app.buy.target_note`),children:[(0,C.jsx)(T,{title:x(`app.buy.for_me`),sub:x(`app.balance_is`,{Balance:S(t.balance)}),chevron:!0,onClick:()=>c(`me`)}),o.data?.groups.map(e=>(0,C.jsx)(T,{title:e.title,sub:x(`app.balance_is`,{Balance:S(e.balance)}),chevron:!0,onClick:()=>c(e.id)},e.id))]}),m===2&&(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(w,{title:x(`app.buy.pass_title`,{Target:_}),note:x(`app.buy.pass_note`),children:i.passes.map(e=>(0,C.jsx)(T,{title:x(`product.`+e.product),after:(0,C.jsx)(`b`,{children:S(e.price)}),chevron:!0,onClick:()=>h(e.product,0)},e.product))}),(0,C.jsx)(w,{title:x(`app.buy.credits_title`),note:x(`app.buy.credits_note`,{Price:S(i.credit_per_download)}),children:i.credit_packs.map(e=>(0,C.jsx)(T,{title:S(e),sub:i.credit_per_download>0?x(`app.buy.credits_downloads`,{Count:Math.floor(e/i.credit_per_download)}):void 0,chevron:!0,onClick:()=>h(`credits`,e)},e))}),(0,C.jsxs)(w,{title:x(`app.buy.paid_title`),children:[(0,C.jsx)(T,{title:x(`app.limit.size`),after:Fe(i.paid.max_size,oe)}),(0,C.jsx)(T,{title:x(`app.limit.duration`),after:Fe(i.paid.max_duration,se)}),(0,C.jsx)(T,{title:x(`app.limit.per_day`),after:Fe(i.paid.daily_downloads,ie)}),(0,C.jsx)(T,{title:x(`app.limit.at_once`),after:Fe(i.paid.active_jobs,ie)})]})]}),m===3&&u&&(0,C.jsx)(w,{children:(0,C.jsx)(`div`,{className:`pad`,children:(0,C.jsx)(Ae,{purchase:u,onPaid:e=>d(t=>t&&{...t,...e}),onDone:()=>{d(null),e.target?r():n({tab:`home`})}})})})]}):(0,C.jsx)(we,{children:x(`app.buy.unavailable`)})})}function Fe(e,t){return e>0?t(e):x(`app.limit.none`)}function Ie(){let e=ge(()=>y(`GET`,`history`),[]);return(0,C.jsx)(w,{title:x(`app.history.title`),note:x(`app.history.note`),children:(0,C.jsx)(Te,{of:e,children:e=>e.items.length===0?(0,C.jsx)(we,{children:x(`app.history.empty`)}):e.items.map(e=>(0,C.jsx)(k,{item:e},e.id))})})}function Le(){let{go:e}=me(),t=ge(()=>y(`GET`,`groups`),[]);return(0,C.jsx)(w,{title:x(`app.groups.title`),note:x(`app.groups.note`),children:(0,C.jsx)(Te,{of:t,children:t=>t.groups.length===0?(0,C.jsx)(we,{children:x(`app.groups.empty`)}):t.groups.map(t=>(0,C.jsx)(T,{title:t.title,sub:[x(`app.balance_is`,{Balance:S(t.balance)}),t.pass_until>Date.now()?x(`app.pass_until`,{Until:ue(t.pass_until)}):x(`app.groups.no_pass`)].join(` · `),chevron:!0,onClick:()=>e({tab:`groups`,group:t.id})},t.id))})})}var Re=[`overview`,`settings`,`wallet`,`usage`],ze=[``,`best`,`1080`,`720`,`480`,`mp3`];function Be(e){return ze.map(t=>({value:t,label:t===``?e:de(t)}))}function Ve(e){let[t,n]=(0,l.useState)(e.view),r=ge(()=>y(`GET`,`groups/`+e.id),[e.id]);return(0,C.jsx)(Te,{of:r,children:e=>(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(`div`,{className:`section-title`,children:(0,C.jsx)(`span`,{children:e.title})}),(0,C.jsx)(Ce,{value:t,onChange:n,options:Re.map(e=>({value:e,label:x(`app.group.tab.`+e)}))}),t===`overview`&&(0,C.jsx)(We,{group:e,open:n}),t===`settings`&&(0,C.jsx)(Je,{group:e,onSaved:t=>r.set({...e,settings:t})}),t===`wallet`&&(0,C.jsx)(Ye,{group:e,onSaved:t=>r.set({...e,settings:t})}),t===`usage`&&(0,C.jsx)(Xe,{id:e.id})]})})}function He(e){return x(`settings.who_`+e.who_can_use)}function Ue(e){return x(`settings.spend_`+e.spend_rule)}function We(e){let t=e.group,n=t.settings,r=t.pass_until>Date.now();return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(`div`,{className:`stats section`,children:[(0,C.jsxs)(`div`,{className:`stat`,children:[(0,C.jsx)(`div`,{className:`hint`,children:x(`app.group.balance`)}),(0,C.jsx)(`div`,{className:`value`,children:S(t.balance)})]}),(0,C.jsxs)(`div`,{className:`stat`,children:[(0,C.jsx)(`div`,{className:`hint`,children:x(`app.group.pass`)}),(0,C.jsx)(`div`,{className:`value`,children:x(r?`app.group.pass_on`:`app.group.pass_off`)}),r&&(0,C.jsx)(`div`,{className:`hint`,children:x(`app.pass_until`,{Until:le(t.pass_until)})})]})]}),(0,C.jsxs)(w,{children:[(0,C.jsx)(T,{title:x(`settings.enabled`),after:n.enabled?x(`app.on`):x(`app.off`)}),(0,C.jsx)(T,{title:x(`settings.who`),after:He(n)}),(0,C.jsx)(T,{title:x(`settings.auto_detect`),after:n.auto_detect?x(`app.on`):x(`app.off`)}),(0,C.jsx)(T,{title:x(`settings.spend`),after:Ue(n)})]}),(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,kind:`soft`,onClick:()=>e.open(`settings`),children:x(`app.group.tab.settings`)})}),(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,onClick:()=>e.open(`wallet`),children:x(`app.group.tab.wallet`)})})]})]})}function Ge(e,t){let{notify:n,fail:r}=me(),[i,a]=(0,l.useState)(e.settings);return(0,l.useEffect)(()=>a(e.settings),[e.settings]),{draft:i,set:(e,t)=>a(n=>({...n,[e]:t})),dirty:JSON.stringify(i)!==JSON.stringify(e.settings),save:async()=>{try{t((await y(`PUT`,`groups/`+e.id+`/settings`,i)).settings),n(x(`app.saved`))}catch(e){r(e)}}}}function Ke(e){return(0,C.jsx)(`input`,{className:`input compact number`,type:`number`,inputMode:`numeric`,min:0,max:e.max,"aria-label":e.label,value:e.value===0?``:e.value,placeholder:`0`,onChange:t=>{let n=Math.max(0,Math.floor(Number(t.target.value)||0));e.onChange(e.max&&n>e.max?e.max:n)}})}function qe(e){let[t,n]=(0,l.useState)(``),r=()=>{let r=t.trim().toLowerCase().replace(/^[a-z]+:\/\//,``).replace(/\/.*$/,``).replace(/^www\./,``);r&&!e.value.includes(r)&&e.onChange([...e.value,r]),n(``)};return(0,C.jsx)(w,{title:e.title,note:e.note,children:(0,C.jsxs)(`div`,{className:`pad stack`,children:[e.value.length>0&&(0,C.jsx)(`div`,{className:`chips`,children:e.value.map(t=>(0,C.jsxs)(`button`,{className:`chip`,dir:`ltr`,"aria-label":x(`app.group.remove_site`,{Site:t}),onClick:()=>e.onChange(e.value.filter(e=>e!==t)),children:[t,` ×`]},t))}),(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`input`,{className:`input grow`,dir:`ltr`,autoCapitalize:`off`,autoCorrect:`off`,spellCheck:!1,placeholder:x(`app.group.site_placeholder`),value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&r()}}),(0,C.jsx)(E,{kind:`soft`,onClick:r,disabled:!t.trim(),children:x(`app.add`)})]})]})})}function Je(e){let{me:t}=me(),{draft:n,set:r,dirty:i,save:a}=Ge(e.group,e.onSaved),o=e.group;return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(w,{children:[(0,C.jsx)(T,{title:x(`settings.enabled`),after:(0,C.jsx)(xe,{label:x(`settings.enabled`),checked:n.enabled,onChange:e=>r(`enabled`,e)})}),(0,C.jsx)(T,{title:x(`settings.auto_detect`),sub:x(`app.group.auto_detect_hint`),wrap:!0,after:(0,C.jsx)(xe,{label:x(`settings.auto_detect`),checked:n.auto_detect,onChange:e=>r(`auto_detect`,e)})}),(0,C.jsx)(T,{title:x(`settings.delete_commands`),wrap:!0,after:(0,C.jsx)(xe,{label:x(`settings.delete_commands`),checked:n.delete_commands,onChange:e=>r(`delete_commands`,e)})})]}),(0,C.jsxs)(w,{children:[(0,C.jsx)(T,{title:x(`settings.who`),after:(0,C.jsx)(Se,{compact:!0,label:x(`settings.who`),value:n.who_can_use,onChange:e=>r(`who_can_use`,e),options:[`everyone`,`pass_holders`,`admins`].map(e=>({value:e,label:x(`settings.who_`+e)}))})}),(0,C.jsx)(T,{title:x(`settings.quality`),after:(0,C.jsx)(Se,{compact:!0,label:x(`settings.quality`),value:n.quality,onChange:e=>r(`quality`,e),options:Be(x(`quality.ask`))})}),(0,C.jsx)(T,{title:x(`app.group.language`),after:(0,C.jsx)(Se,{compact:!0,label:x(`app.group.language`),value:n.lang,onChange:e=>r(`lang`,e),options:[{value:``,label:x(`settings.lang_auto`)},...t.languages.map(e=>({value:e.code,label:e.name}))]})})]}),(0,C.jsxs)(w,{title:x(`app.group.caps_title`),note:x(`app.group.caps_note`,{Size:oe(o.tier_max_size_mb*1048576)}),children:[(0,C.jsx)(T,{title:x(`app.group.max_size`),wrap:!0,after:(0,C.jsx)(Ke,{label:x(`app.group.max_size`),value:n.max_size_mb,max:o.tier_max_size_mb||void 0,onChange:e=>r(`max_size_mb`,e)})}),(0,C.jsx)(T,{title:x(`app.group.max_minutes`),wrap:!0,after:(0,C.jsx)(Ke,{label:x(`app.group.max_minutes`),value:Math.round(n.max_duration/60),max:o.tier_max_duration?Math.floor(o.tier_max_duration/60):void 0,onChange:e=>r(`max_duration`,e*60)})})]}),(0,C.jsx)(qe,{title:x(`app.group.allowed_title`),note:x(`app.group.allowed_note`),value:n.allowed,onChange:e=>r(`allowed`,e)}),(0,C.jsx)(qe,{title:x(`app.group.blocked_title`),note:x(`app.group.blocked_note`),value:n.blocked,onChange:e=>r(`blocked`,e)}),(0,C.jsx)(E,{wide:!0,onClick:a,disabled:!i,children:x(`app.save`)})]})}function Ye(e){let{go:t,me:n}=me(),{draft:r,set:i,dirty:a,save:o}=Ge(e.group,e.onSaved),s=e.group,c=s.pass_until>Date.now();return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsx)(w,{children:(0,C.jsxs)(`div`,{className:`pad stack`,children:[(0,C.jsxs)(`div`,{children:[(0,C.jsx)(`div`,{className:`hint`,children:x(`app.group.balance`)}),(0,C.jsx)(`div`,{className:`big`,children:S(s.balance)}),(0,C.jsx)(`div`,{className:`hint`,children:c?x(`app.pass_until`,{Until:le(s.pass_until)}):x(`app.groups.no_pass`)})]}),n.payments&&(0,C.jsx)(E,{wide:!0,onClick:()=>t({tab:`buy`,target:s.id}),children:x(`app.group.top_up`)})]})}),(0,C.jsxs)(w,{title:x(`app.group.rules_title`),note:x(`app.group.rules_note`),children:[(0,C.jsx)(T,{title:x(`settings.spend`),after:(0,C.jsx)(Se,{compact:!0,label:x(`settings.spend`),value:r.spend_rule,onChange:e=>i(`spend_rule`,e),options:[`admins`,`anyone`,`capped`].map(e=>({value:e,label:x(`settings.spend_`+e)}))})}),r.spend_rule===`capped`&&(0,C.jsx)(T,{title:x(`app.group.spend_cap`),wrap:!0,after:(0,C.jsx)(Ke,{label:x(`app.group.spend_cap`),value:r.spend_cap,onChange:e=>i(`spend_cap`,e)})}),(0,C.jsx)(T,{title:x(`app.group.daily_cap`),wrap:!0,after:(0,C.jsx)(Ke,{label:x(`app.group.daily_cap`),value:r.daily_cap,onChange:e=>i(`daily_cap`,e)})})]}),(0,C.jsx)(E,{wide:!0,onClick:o,disabled:!a,children:x(`app.save`)})]})}function Xe(e){let t=ge(()=>y(`GET`,`groups/`+e.id+`/usage`),[e.id]);return(0,C.jsx)(Te,{of:t,children:e=>(0,C.jsx)(w,{title:x(`app.group.usage_title`,{Count:e.days}),children:e.members.length===0?(0,C.jsx)(we,{children:x(`app.group.usage_empty`)}):(0,C.jsxs)(`table`,{className:`table`,children:[(0,C.jsx)(`thead`,{children:(0,C.jsxs)(`tr`,{children:[(0,C.jsx)(`th`,{children:x(`app.group.col_member`)}),(0,C.jsx)(`th`,{children:x(`app.group.col_downloads`)}),(0,C.jsx)(`th`,{children:x(`app.group.col_volume`)}),(0,C.jsx)(`th`,{children:x(`app.group.col_spent`)})]})}),(0,C.jsx)(`tbody`,{children:e.members.map((e,t)=>(0,C.jsxs)(`tr`,{children:[(0,C.jsx)(`td`,{children:e.name}),(0,C.jsx)(`td`,{children:ie(e.downloads)}),(0,C.jsx)(`td`,{children:oe(e.bytes)}),(0,C.jsx)(`td`,{children:S(e.sats)})]},t))})]})})})}function Ze(){let{me:e,go:t,notify:n,fail:r,reload:i}=me(),a=async e=>{try{await y(`PUT`,`me`,e),await i(),n(x(`app.saved`))}catch(e){r(e)}},o=e.quality===`mp3`,s=e.support.startsWith(`@`)?`https://t.me/`+e.support.slice(1):``;return(0,C.jsxs)(C.Fragment,{children:[(0,C.jsxs)(w,{title:x(`app.me.downloads_title`),note:x(`app.me.quality_note`),children:[(0,C.jsx)(T,{title:x(`settings.quality`),after:(0,C.jsx)(Se,{compact:!0,label:x(`settings.quality`),disabled:o,value:o?`fit`:e.quality,onChange:e=>void a({quality:e}),options:[{value:`fit`,label:x(`quality.fit`)},...Be(x(`quality.ask`)).filter(e=>e.value!==`mp3`)]})}),(0,C.jsx)(T,{title:x(`app.me.audio_only`),sub:x(`app.me.audio_only_hint`),wrap:!0,after:(0,C.jsx)(xe,{label:x(`app.me.audio_only`),checked:o,onChange:e=>void a({quality:e?`mp3`:`fit`})})})]}),(0,C.jsx)(w,{title:x(`app.me.language_title`),children:(0,C.jsx)(T,{title:x(`app.me.language`),after:(0,C.jsx)(Se,{compact:!0,label:x(`app.me.language`),value:e.lang_override,onChange:e=>void a({lang:e||`auto`}),options:[{value:``,label:x(`language.auto`)},...e.languages.map(e=>({value:e.code,label:e.name}))]})})}),(0,C.jsxs)(w,{title:x(`app.me.referral_title`),note:e.referral_reward>0?x(`app.me.referral_note`,{Reward:S(e.referral_reward)}):void 0,children:[(0,C.jsxs)(`div`,{className:`pad stack`,children:[(0,C.jsx)(`div`,{className:`mono`,children:e.referral_link}),(0,C.jsxs)(`div`,{className:`row`,children:[(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,kind:`soft`,onClick:async()=>{await _(e.referral_link)?n(x(`app.copied`)):r(null)},children:x(`app.me.copy_link`)})}),(0,C.jsx)(`div`,{className:`grow`,children:(0,C.jsx)(E,{wide:!0,onClick:()=>g(`https://t.me/share/url?url=`+encodeURIComponent(e.referral_link)+`&text=`+encodeURIComponent(x(`referral.share_text`))),children:x(`app.me.share`)})})]}),e.referral_qr&&(0,C.jsxs)(`details`,{className:`qr-toggle`,children:[(0,C.jsx)(`summary`,{children:x(`app.me.qr`)}),(0,C.jsx)(`img`,{className:`qr`,src:e.referral_qr,alt:x(`app.me.qr`)})]})]}),(0,C.jsx)(T,{title:x(`app.me.invited`),after:x(`app.me.invited_count`,{Count:e.referral_count})}),(0,C.jsx)(T,{title:x(`app.me.converted`),after:String(e.referral_converted)}),(0,C.jsx)(T,{title:x(`app.me.earned`),after:S(e.referral_earned)}),e.referral_pending>0&&(0,C.jsx)(T,{title:x(`app.me.pending`),after:S(e.referral_pending)})]}),(0,C.jsxs)(w,{children:[(0,C.jsx)(T,{title:x(`app.history.title`),chevron:!0,onClick:()=>t({tab:`home`,page:`history`})}),(0,C.jsx)(T,{title:x(`app.me.support`),after:e.support,chevron:s!==``,onClick:s?()=>g(s):void 0})]})]})}var Qe={home:`M3 11.5 12 4l9 7.5M5.5 10v9.5h13V10`,queue:`M12 4v11m0 0-4-4m4 4 4-4M5 20h14`,buy:`M13 3 5 13.5h6L10 21l9-11h-6.5L13 3Z`,groups:`M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.5 19c.5-3 2.6-5 5.5-5s5 2 5.5 5M16.5 11.5a2.5 2.5 0 1 0 0-5M17 14.2c2 .3 3.3 1.9 3.7 4.3`,me:`M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM4.5 20c.7-3.5 3.7-6 7.5-6s6.8 2.5 7.5 6`},$e=[`home`,`queue`,`buy`,`groups`,`me`];function et(e){let t=new URLSearchParams(window.location.search).get(`page`)??e;return t.startsWith(`group_`)?{tab:`groups`,group:t.slice(6),view:`settings`}:t===`buy`?{tab:`buy`}:t===`queue`?{tab:`queue`}:{tab:`home`}}function tt(){let[e,t]=(0,l.useState)(null),[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)([{tab:`home`}]),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(0),d=(0,l.useRef)(void 0),f=(0,l.useRef)(!1),m=(0,l.useCallback)(async()=>{let[e,n]=await Promise.all([y(`GET`,`me`),y(`GET`,`i18n`)]);return re(n),document.title=x(`app.title`),t(e),e},[]);(0,l.useEffect)(()=>{f.current||(f.current=!0,m().then(e=>a([et(e.start_param)])).catch(r))},[m]),(0,l.useEffect)(()=>{if(!e)return;let t=!0,n=()=>{document.hidden||y(`GET`,`queue`).then(e=>t&&u(e.jobs.length)).catch(()=>void 0)};n();let r=window.setInterval(n,5e3);return()=>{t=!1,window.clearInterval(r)}},[e]);let h=i[i.length-1],g=(0,l.useCallback)((e,t=!1)=>{window.clearTimeout(d.current),s({text:e,bad:t}),p(t?`error`:`success`),d.current=window.setTimeout(()=>s(null),3500)},[]),_=(0,l.useMemo)(()=>e?{me:e,route:h,go:e=>{let t=`page`in e||`group`in e||`target`in e;a(n=>t?[...n,e]:[e]),window.scrollTo(0,0)},back:()=>a(e=>e.length>1?e.slice(0,-1):[{tab:e[0].tab}]),notify:g,fail:e=>g(he(e),!0),reload:async()=>{await m()}}:null,[e,h,g,m]);if(be(_&&i.length>1?_.back:null),n){let e=n instanceof v?n.message:``;return(0,C.jsx)(`div`,{className:`app`,children:(0,C.jsxs)(`div`,{className:`empty`,children:[(0,C.jsx)(`p`,{className:`big`,children:`:(`}),(0,C.jsx)(`p`,{children:e}),!(n instanceof v&&n.status===401)&&(0,C.jsx)(`button`,{className:`btn soft`,"aria-label":`retry`,onClick:()=>window.location.reload(),children:`↻`})]})})}if(!_)return(0,C.jsx)(`div`,{className:`app`,children:(0,C.jsx)(O,{})});let b;return b=`group`in h?(0,C.jsx)(Ve,{id:h.group,view:h.view??`overview`},h.group):`page`in h?(0,C.jsx)(Ie,{}):h.tab===`queue`?(0,C.jsx)(je,{}):h.tab===`buy`?(0,C.jsx)(Pe,{target:`target`in h?h.target:void 0},`target`in h?h.target:`me`):h.tab===`groups`?(0,C.jsx)(Le,{}):h.tab===`me`?(0,C.jsx)(Ze,{}):(0,C.jsx)(De,{}),(0,C.jsxs)(pe.Provider,{value:_,children:[(0,C.jsx)(`main`,{className:`app`,children:b}),o&&(0,C.jsx)(`div`,{className:`toast`+(o.bad?` bad`:``),role:`status`,children:o.text}),(0,C.jsx)(`nav`,{className:`tabs`,children:$e.map(e=>(0,C.jsxs)(`button`,{"aria-current":h.tab===e?`page`:void 0,onClick:()=>_.go({tab:e}),children:[(0,C.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,C.jsx)(`path`,{d:Qe[e]})}),x(`app.tab.`+e),e===`queue`&&c>0&&(0,C.jsx)(`span`,{className:`badge`,children:c})]},e))})]})}d?.ready(),d?.expand(),(0,u.createRoot)(document.getElementById(`root`)).render((0,C.jsx)(l.StrictMode,{children:(0,C.jsx)(tt,{})})); \ No newline at end of file +`+e.stack}}var He=Object.prototype.hasOwnProperty,Ue=t.unstable_scheduleCallback,We=t.unstable_cancelCallback,Ge=t.unstable_shouldYield,Ke=t.unstable_requestPaint,qe=t.unstable_now,Je=t.unstable_getCurrentPriorityLevel,Ye=t.unstable_ImmediatePriority,Xe=t.unstable_UserBlockingPriority,Ze=t.unstable_NormalPriority,Qe=t.unstable_LowPriority,$e=t.unstable_IdlePriority,et=t.log,tt=t.unstable_setDisableYieldValue,nt=null,rt=null;function it(e){if(typeof et==`function`&&tt(e),rt&&typeof rt.setStrictMode==`function`)try{rt.setStrictMode(nt,e)}catch{}}var at=Math.clz32?Math.clz32:ct,ot=Math.log,st=Math.LN2;function ct(e){return e>>>=0,e===0?32:31-(ot(e)/st|0)|0}var lt=256,ut=262144,dt=4194304;function ft(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function pt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=ft(n))):i=ft(o):i=ft(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=ft(n))):i=ft(o)):i=ft(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function mt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function ht(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function yt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function bt(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0=yr),Sr=` `,Cr=!1;function wr(e,t){switch(e){case`keyup`:return _r.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Tr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Er=!1;function Dr(e,t){switch(e){case`compositionend`:return Tr(t);case`keypress`:return t.which===32?(Cr=!0,Sr):null;case`textInput`:return e=t.data,e===Sr&&Cr?null:e;default:return null}}function Or(e,t){if(Er)return e===`compositionend`||!vr&&wr(e,t)?(e=Bn(),zn=Rn=Ln=null,Er=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Zr(n)}}function $r(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?$r(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ei(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Xr(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Xr(e.document)}return t}function ti(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var ni=Pn&&`documentMode`in document&&11>=document.documentMode,ri=null,ii=null,ai=null,oi=!1;function si(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;oi||ri==null||ri!==Xr(r)||(r=ri,`selectionStart`in r&&ti(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ai&&Yr(ai,r)||(ai=r,r=Jf(ii,`onSelect`),0>=o,i-=o,ra=1<<32-at(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),o=a(_,o,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),P&&aa(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),o=a(y,o,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),P&&aa(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(o=a(v,o,g),d===null?u=v:d.sibling=v,d=v);return P&&aa(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),o=a(v,o,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),P&&aa(i,g),u}function _(e,r,a,c){if(typeof a==`object`&&a&&a.type===oe&&a.key===null&&a.props.ref===void 0&&(a=a.props.children),typeof a==`object`&&a){switch(a.$$typeof){case ie:a:{for(var l=a.key;r!==null;){if(r.key===l){if(l=a.type,l===oe){if(r.tag===7){n(e,r.sibling),c=i(r,a.props.children),mo(c,a),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===me&&oo(l)===r.type){n(e,r.sibling),c=i(r,a.props),mo(c,a),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}a.type===oe?(c=Wi(a.props.children,e.mode,c,a.key),mo(c,a),c.return=e,e=c):(c=Ui(a.type,a.key,a.props,null,e.mode,c),mo(c,a),c.return=e,e=c)}return o(e);case ae:a:{for(l=a.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===a.containerInfo&&r.stateNode.implementation===a.implementation){n(e,r.sibling),c=i(r,a.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=qi(a,e.mode,c),c.return=e,e=c}return o(e);case me:return a=oo(a),_(e,r,a,c)}if(xe(a))return h(e,r,a,c);if(E(a)){if(l=E(a),typeof l!=`function`)throw Error(s(150));return a=l.call(a),g(e,r,a,c)}if(typeof a.then==`function`)return _(e,r,po(a),c);if(a.$$typeof===ue)return _(e,r,Ma(e,a),c);ho(e,a)}return typeof a==`string`&&a!==``||typeof a==`number`||typeof a==`bigint`?(a=``+a,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,a),c.return=e,e=c):(n(e,r),c=Gi(a,e.mode,c),c.return=e,e=c),o(e)):n(e,r)}return function(e,t,n,r){try{fo=0;var i=_(e,t,n,r);return uo=null,i}catch(t){if(t===eo||t===no)throw t;var a=zi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var _o=go(!0),vo=go(!1),yo=!1;function bo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function xo(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function So(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Co(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,W&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Ii(e),Fi(e,null,n),t}return Mi(e,r,t,n),Ii(e)}function wo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,St(e,n)}}function To(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Eo=!1;function Do(){if(Eo){var e=Ga;if(e!==null)throw e}}function Oo(e,t,n,r){Eo=!1;var i=e.updateQueue;yo=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(q&f)===f:(r&f)===f){f!==0&&f===Wa&&(Eo=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=C({},d,f);break a;case 2:yo=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),sd|=o,e.lanes=o,e.memoizedState=d}}function ko(e,t){if(typeof e!=`function`)throw Error(s(191,e));e.call(t)}function Ao(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=k.T,s={};s.types=o===null?null:o.types,k.T=s,pc(e,!1,t,n);try{var c=i(),l=k.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?fc(e,t,Ja(c,r),jd(e)):fc(e,t,r,jd(e))}catch(n){fc(e,t,{then:function(){},status:`rejected`,reason:n},jd())}finally{A.p=a,o!==null&&s.types!==null&&(o.types=s.types),k.T=o}}function nc(){}function rc(e,t,n,r){if(e.tag!==5)throw Error(s(476));var i=ic(e).queue;tc(e,i,t,Se,n===null?nc:function(){return ac(e),n(r)})}function ic(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:Se,baseState:Se,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ms,lastRenderedState:Se},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ms,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function ac(e){var t=ic(e);t.next===null&&(t=e.alternate.memoizedState),fc(e,t.next.queue,{},jd())}function oc(){return ja(sh)}function sc(){return B().memoizedState}function cc(){return B().memoizedState}function lc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=jd();e=So(n);var r=Co(t,e,n);r!==null&&(Pd(r,t,n),wo(r,t,n)),t={cache:La()},e.payload=t;return}t=t.return}}function uc(e,t,n){var r=jd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},mc(e)?hc(t,n):(n=Ni(e,t,n,r),n!==null&&(Pd(n,e,r),gc(n,t,r)))}function dc(e,t,n){fc(e,t,n,jd())}function fc(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(mc(e))hc(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Jr(s,o))return Mi(e,t,i,0),G===null&&ji(),!1}catch{}if(n=Ni(e,t,i,r),n!==null)return Pd(n,e,r),gc(n,t,r),!0}return!1}function pc(e,t,n,r){if(r={lane:2,revertLane:Pf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},mc(e)){if(t)throw Error(s(479))}else t=Ni(e,n,r,2),t!==null&&Pd(t,e,2)}function mc(e){var t=e.alternate;return e===I||t!==null&&t===I}function hc(e,t){Yo=Jo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function gc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,St(e,n)}}var _c={readContext:ja,use:fs,useCallback:z,useContext:z,useEffect:z,useImperativeHandle:z,useLayoutEffect:z,useInsertionEffect:z,useMemo:z,useReducer:z,useRef:z,useState:z,useDebugValue:z,useDeferredValue:z,useTransition:z,useSyncExternalStore:z,useId:z,useHostTransitionStatus:z,useFormState:z,useActionState:z,useOptimistic:z,useMemoCache:z,useCacheRefresh:z,useEffectEvent:z},vc={readContext:ja,use:fs,useCallback:function(e,t){return ls().memoizedState=[e,t===void 0?null:t],e},useContext:ja,useEffect:Hs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Bs(4194308,4,Js.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Bs(4194308,4,e,t)},useInsertionEffect:function(e,t){Bs(4,2,e,t)},useMemo:function(e,t){var n=ls();t=t===void 0?null:t;var r=e();if(Xo){it(!0);try{e()}finally{it(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ls();if(n!==void 0){var i=n(t);if(Xo){it(!0);try{n(t)}finally{it(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=uc.bind(null,I,e),[r.memoizedState,e]},useRef:function(e){var t=ls();return e={current:e},t.memoizedState=e},useState:function(e){e=ws(e);var t=e.queue,n=dc.bind(null,I,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Xs,useDeferredValue:function(e,t){return $s(ls(),e,t)},useTransition:function(){var e=ws(!1);return e=tc.bind(null,I,e.queue,!0,!1),ls().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=I,i=ls();if(P){if(n===void 0)throw Error(s(407));n=n()}else{if(n=t(),G===null)throw Error(s(349));q&127||ys(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,Hs(xs.bind(null,r,a,e),[e]),r.flags|=2048,Rs(9,{destroy:void 0},bs.bind(null,r,a,n,t),null),n},useId:function(){var e=ls(),t=G.identifierPrefix;if(P){var n=ia,r=ra;n=(r&~(1<<32-at(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=Zo++,0<\/script>`,a=a.removeChild(a.firstChild);break;case`select`:a=typeof r.is==`string`?o.createElement(`select`,{is:r.is}):o.createElement(`select`),r.multiple?a.multiple=!0:r.size&&(a.size=r.size);break;default:a=typeof r.is==`string`?o.createElement(i,{is:r.is}):o.createElement(i)}}a[kt]=t,a[At]=r;a:for(o=t.child;o!==null;){if(o.tag===5||o.tag===6)a.appendChild(o.stateNode);else if(o.tag!==4&&o.tag!==27&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===t)break a;for(;o.sibling===null;){if(o.return===null||o.return===t)break a;o=o.return}o.sibling.return=o.return,o=o.sibling}t.stateNode=a;a:switch(np(a,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&gl(t)}}return V(t),t.subtreeFlags&=-33554433,_l(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&gl(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(s(166));if(e=ke.current,_a(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=ua,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[kt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||ep(e.nodeValue,n)),e||ma(t,!0)}else e=lp(e).createTextNode(r),e[kt]=t,t.stateNode=e}return V(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=_a(t),n!==null){if(e===null){if(!r)throw Error(s(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(s(557));e[kt]=t}else va(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;V(t),e=!1}else n=ya(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Ho(t),t):(Ho(t),null);if(t.flags&128)throw Error(s(558))}return V(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=_a(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(s(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(s(317));i[kt]=t}else va(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;V(t),i=!1}else i=ya(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(Ho(t),t):(Ho(t),null)}return Ho(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),a=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(a=r.memoizedState.cachePool.pool),a!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),yl(t,t.updateQueue),V(t),null);case 4:return Me(),e===null&&Wf(t.stateNode.containerInfo),t.flags|=67108864,V(t),null;case 10:return Ta(t.type),V(t),null;case 19:if(Go(t),r=t.memoizedState,r===null)return V(t),null;if(i=!!(t.flags&128),a=r.rendering,a===null){if(i)bl(r,!1);else{if(Y!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(a=Ko(e),a!==null){for(t.flags|=128,bl(r,!1),e=a.updateQueue,t.updateQueue=e,yl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Hi(n,e),n=n.sibling;return Wo(t,Uo.current&1|2),P&&aa(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&qe()>_d&&(t.flags|=128,i=!0,bl(r,!1),t.lanes=4194304)}}else{if(!i){if(e=Ko(a),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,yl(t,e),bl(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!a.alternate&&!P)return V(t),null}else 2*qe()-r.renderingStartTime>_d&&n!==536870912&&(t.flags|=128,i=!0,bl(r,!1),t.lanes=4194304)}r.isBackwards?(a.sibling=t.child,t.child=a):(e=r.last,e===null?t.child=a:e.sibling=a,r.last=a)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=qe(),e.sibling=null,a=Uo.current,a=i?a&1|2:a&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||P?Wo(t,a):(n=a,j(Io,t),j(Uo,n),Lo===null&&(Lo=t)),P&&aa(t,r.treeForkCount),e}return V(t),null;case 22:case 23:return Ho(t),Fo(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(V(t),t.subtreeFlags&6&&(t.flags|=8192)):V(t),n=t.updateQueue,n!==null&&yl(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&Ee(Xa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ta(F),V(t),null;case 25:return null;case 30:return t.flags|=33554432,V(t),null}throw Error(s(156,t.tag))}function Sl(e,t){switch(ca(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ta(F),Me(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Pe(t),null;case 31:if(t.memoizedState!==null){if(Ho(t),t.alternate===null)throw Error(s(340));va()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Ho(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));va()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Go(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Me(),null;case 10:return Ta(t.type),null;case 22:case 23:return Ho(t),Fo(),e!==null&&Ee(Xa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ta(F),null;case 25:return null;default:return null}}function Cl(e,t){switch(ca(t),t.tag){case 3:Ta(F),Me();break;case 26:case 27:case 5:Pe(t);break;case 4:Me();break;case 31:t.memoizedState!==null&&Ho(t);break;case 13:Ho(t);break;case 19:Go(t);break;case 10:Ta(t.type);break;case 22:case 23:Ho(t),Fo(),e!==null&&Ee(Xa);break;case 24:Ta(F)}}function wl(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Z(t,t.return,e)}}function Tl(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Z(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Z(t,t.return,e)}}function El(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ao(t,n)}catch(t){Z(e,e.return,t)}}}function Dl(e,t,n){n.props=Tc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Z(e,t,n)}}function Ol(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:var i=e.stateNode,a=wi(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Pp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Fp(e);h(e.child,!1,Qp,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Z(e,t,n)}}function kl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Z(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Z(e,t,n)}else n.current=null}}function Al(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),np(r,t,n),r[kt]=e,Ut(r),t=r;break a;case`link`:if(a=Gm(`link`,`href`,i).get(t+(n.href||``))){for(o=0;og&&(o=g,g=h,h=o);var _=Qr(s,h),v=Qr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,k.T=null,n=wd,wd=null;var a=bd,o=Sd;if(X=0,xd=bd=null,Sd=0,W&6)throw Error(s(331));var c=W;if(W|=4,Zu(a.current),Uu(a,a.current,o,n),W=c,Df(0,!1),rt&&typeof rt.onPostCommitFiberRoot==`function`)try{rt.onPostCommitFiberRoot(nt,a)}catch{}return!0}finally{A.p=i,k.T=r,uf(e,t)}}function pf(e,t,n){t=Yi(n,t),t=jc(e.stateNode,t,2),e=Co(e,t,2),e!==null&&(yt(e,2),Ef(e))}function Z(e,t,n){if(e.tag===3)pf(e,e,n);else for(;t!==null;){if(t.tag===3){pf(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(yd===null||!yd.has(r))){e=Yi(n,e),n=Mc(2),r=Co(t,n,2),r!==null&&(Nc(n,r,t,e),yt(r,2),Ef(r));break}}t=t.return}}function mf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new td;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(ad=!0,i.add(n),e=hf.bind(null,e,t,n),t.then(e,e))}function hf(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,G===e&&(q&n)===n&&(Y===4||Y===3&&(q&62914560)===q&&300>qe()-hd?W&2?ld|=n:Vd(e,0):ld|=n,dd===q&&(dd=0)),Ef(e)}function gf(e,t){t===0&&(t=_t()),e=Pi(e,t),e!==null&&(yt(e,t),Ef(e))}function _f(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),gf(e,n)}function vf(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(s(314))}r!==null&&r.delete(t),gf(e,n)}function yf(e,t){return Ue(e,t)}var bf=null,xf=null,Sf=!1,Cf=!1,wf=!1,Tf=0;function Ef(e){e!==xf&&e.next===null&&(xf===null?bf=xf=e:xf=xf.next=e),Cf=!0,Sf||(Sf=!0,Nf())}function Df(e,t){if(!wf&&Cf){wf=!0;do for(var n=!1,r=bf;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-at(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,Mf(r,a))}else a=q,a=pt(r,r===G?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||mt(r,a)||(n=!0,Mf(r,a))}r=r.next}while(n);wf=!1}}function Of(){kf()}function kf(){Cf=Sf=!1;var e=0;Tf!==0&&hp()&&(e=Tf);for(var t=qe(),n=null,r=bf;r!==null;){var i=r.next,a=Af(r,t);a===0?(r.next=null,n===null?bf=i:n.next=i,i===null&&(xf=n)):(n=r,(e!==0||a&3)&&(Cf=!0)),r=i}X!==0&&X!==5||Df(e,!1),Tf!==0&&(Tf=0)}function Af(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&ap(d)&&(c=c.responseEnd,o+=u*(c$m){s.length=o;break}f=new Promise(jp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Tm(e,t,n){var r=wm;if(r&&typeof t==`string`&&t){var i=un(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),ym.has(i)||(ym.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),np(t,`link`,e),Ut(t),r.head.appendChild(t)))}}function Em(e){xm.D(e),Tm(`dns-prefetch`,e,null)}function Dm(e,t){xm.C(e,t),Tm(`preconnect`,e,t)}function Om(e,t,n){xm.L(e,t,n);var r=wm;if(r&&e&&t){var i=`link[rel="preload"][as="`+un(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+un(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+un(n.imageSizes)+`"]`)):i+=`[href="`+un(e)+`"]`;var a=i;switch(t){case`style`:a=Pm(e);break;case`script`:a=Rm(e)}if(!(vm.has(a)||(e=C({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),vm.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Fm(a))||t===`script`&&r.querySelector(zm(a))))){var o=r.createElement(`link`);np(o,`link`,e),t===`style`&&(o[Lt]=!0,o.onload=o.onerror=function(){Wt(o)}),Ut(o),r.head.appendChild(o)}}}function km(e,t){xm.m(e,t);var n=wm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+un(r)+`"][href="`+un(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Rm(e)}if(!vm.has(a)&&(e=C({rel:`modulepreload`,href:e},t),vm.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(zm(a)))return}r=n.createElement(`link`),np(r,`link`,e),Ut(r),n.head.appendChild(r)}}}function Am(e,t,n){xm.S(e,t,n);var r=wm;if(r&&e){var i=Ht(r).hoistableStyles,a=Pm(e);t=t||`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Fm(a)))s.loading=5;else{e=C({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=vm.get(a))&&Hm(e,n);var c=o=r.createElement(`link`);Ut(c),np(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Vm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function jm(e,t){xm.X(e,t);var n=wm;if(n&&e){var r=Ht(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=C({src:e,async:!0},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Ut(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mm(e,t){xm.M(e,t);var n=wm;if(n&&e){var r=Ht(n).hoistableScripts,i=Rm(e),a=r.get(i);a||(a=n.querySelector(zm(i)),a||(e=C({src:e,async:!0,type:`module`},t),(t=vm.get(i))&&Um(e,t),a=n.createElement(`script`),Ut(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Nm(e,t,n,r){var i=(i=ke.current)?bm(i):null;if(!i)throw Error(s(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Pm(n.href),t=Ht(i).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Pm(n.href);var a=Ht(i).hoistableStyles,o=a.get(e);if(o||(i=i.ownerDocument||i,o={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},a.set(e,o),(a=i.querySelector(Fm(e)))?a._p||(o.instance=a,o.state.loading=5):(a=vm.get(e),a||(a={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},vm.set(e,a)),Lm(i,e,a,o.state))),t&&r===null)throw Error(s(528,``));return o}if(t&&r!==null)throw Error(s(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Rm(n),t=Ht(i).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(s(444,e))}}function Pm(e){return`href="`+un(e)+`"`}function Fm(e){return`link[rel="stylesheet"][`+e+`]`}function Im(e){return C({},e,{"data-precedence":e.precedence,precedence:null})}function Lm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[Lt]){r.loading=1;return}}else t=e.createElement(`link`),t[Lt]=!0,t.onload=t.onerror=Wt.bind(null,t),np(t,`link`,n),Ut(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Rm(e){return`[src="`+un(e)+`"]`}function zm(e){return`script[async]`+e}function Bm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+un(n.href)+`"]`);if(r)return t.instance=r,Ut(r),r;var i=C({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Ut(r),np(r,`style`,i),Vm(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Pm(n.href);var a=e.querySelector(Fm(i));if(a)return t.state.loading|=4,t.instance=a,Ut(a),a;r=Im(n),(i=vm.get(i))&&Hm(r,i),a=(e.ownerDocument||e).createElement(`link`),Ut(a);var o=a;return o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),t.state.loading|=4,Vm(a,n.precedence,e),t.instance=a;case`script`:return a=Rm(n.src),(i=e.querySelector(zm(a)))?(t.instance=i,Ut(i),i):(r=n,(i=vm.get(a))&&(r=C({},n),Um(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Ut(i),np(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(s(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Vm(r,n.precedence,e));return t.instance}function Vm(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function qm(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Jm(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function Ym(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Xm(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function Zm(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=Xm(t),e.suspenseyImages.push(t)),e=rh.bind(e),t.decode().then(e,e))}function Qm(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Pm(r.href),a=t.querySelector(Fm(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=nh.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Ut(a);return}a=t.ownerDocument||t,r=Im(r),(i=vm.get(i))&&Hm(r,i),a=a.createElement(`link`),Ut(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=nh.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $m=0;function eh(e,t){return e.stylesheets&&e.count===0&&ah(e,e.stylesheets),0$m?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function th(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)ah(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function nh(){this.count--,th(this)}function rh(){this.imgCount--,th(this)}var ih=null;function ah(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ih=new Map,t.forEach(oh,e),ih=null,nh.call(e))}function oh(e,t){if(!(t.state.loading&4)){var n=ih.get(e);if(n)var r=n.get(null);else{n=new Map,ih.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=s()})),l=n(),u=c(),d=window.Telegram?.WebApp;function f(){return d?.initData??``}function p(e){try{e===`tap`?d?.HapticFeedback?.selectionChanged():d?.HapticFeedback?.notificationOccurred(e)}catch{}}function m(e){return new Promise(t=>{d&&d.isVersionAtLeast(`6.2`)?d.showConfirm(e,t):t(window.confirm(e))})}function h(e){d?d.openLink(e):window.open(e,`_blank`,`noopener`)}function g(e,t){d?.openInvoice?d.openInvoice(e,t):d?d.openTelegramLink(e):window.open(e,`_blank`)}function _(e){d?d.openTelegramLink(e):window.open(e,`_blank`,`noopener`)}async function v(e){try{return await navigator.clipboard.writeText(e),!0}catch{let t=document.createElement(`textarea`);t.value=e,t.style.position=`fixed`,t.style.opacity=`0`,document.body.appendChild(t),t.select();let n=!1;try{n=document.execCommand(`copy`)}catch{n=!1}return t.remove(),n}}var y=class extends Error{constructor(e,t,n,r=!1){super(n),this.status=e,this.code=t,this.upgradable=r}};async function b(e,t,n){let r;try{r=await fetch(`/app/api/`+t,{method:e,headers:{Authorization:`tma `+f(),...n===void 0?{}:{"Content-Type":`application/json`}},body:n===void 0?void 0:JSON.stringify(n)})}catch{throw new y(0,`network`,``)}let i=null;try{i=await r.json()}catch{i=null}if(!r.ok){let e=i??{};throw new y(r.status,e.error??`internal`,e.message??``,e.upgradable??!1)}return i}var ee={},te=`en`,ne=new Intl.PluralRules(`en`);function re(e){try{return Intl.NumberFormat.supportedLocalesOf([e])[0]??`en`}catch{return`en`}}function x(e){ee=e.messages,te=re(e.lang),ne=new Intl.PluralRules(te),document.documentElement.lang=e.lang,document.documentElement.dir=e.dir}function S(e,t){let n=ee[e];return n===void 0?e:(typeof n!=`string`&&(n=n[ne.select(Number(t?.Count??0))]??n.other??``),n.replace(/\{(\w+)\}/g,(e,n)=>t&&n in t?String(t[n]):``))}function C(e){return new Intl.NumberFormat(te).format(e)}function w(e){return S(`unit.sats`,{Count:e,N:C(e)})}function ie(e){return S(`unit.stars`,{Count:e,N:C(e)})}function ae(e){return new Intl.NumberFormat(te,{style:`percent`,maximumFractionDigits:0}).format(e)}function oe(e){let t=(e,t)=>new Intl.NumberFormat(te,{minimumFractionDigits:0,maximumFractionDigits:t}).format(e),n=1024;if(e=100?0:1)+` MB`}return t(e/(n*n*n),2)+` GB`}function se(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=e=>String(e).padStart(2,`0`);return n>0?`${n}:${i(r)}:${i(t%60)}`:`${r}:${i(t%60)}`}function ce(e){return e<60?S(`unit.seconds`,{Count:Math.max(1,Math.round(e))}):e<3600?S(`unit.minutes`,{Count:Math.round(e/60)}):S(`unit.hours`,{Count:Math.round(e/3600)})}function le(e){return new Intl.DateTimeFormat(te,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(e))}function ue(e){return new Intl.DateTimeFormat(te,{dateStyle:`medium`}).format(new Date(e))}function de(e){return e===`best`?S(`btn.best`):/^\d+$/.test(e)?S(`btn.res`,{Height:e}):e===`mp3`||e===`m4a`||e===`thumb`?S(`btn.`+e):e.startsWith(`subs:`)?S(`btn.subs`,{Lang:e.slice(5)}):e}var fe=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),T=e(((e,t)=>{t.exports=fe()}))(),pe=(0,l.createContext)(null);function me(){let e=(0,l.useContext)(pe);if(!e)throw Error(`no app context`);return e}function he(e){if(e instanceof y){if(e.message)return e.message;if(e.code===`network`)return S(`app.error.network`)}return S(`app.error.generic`)}function ge(e,t,n=0){let[r,i]=(0,l.useState)(null),[a,o]=(0,l.useState)(null),[s,c]=(0,l.useState)(!0),[u,d]=(0,l.useState)(0),f=(0,l.useRef)(e);return f.current=e,(0,l.useEffect)(()=>{let e=!0,t,r=()=>{f.current().then(t=>{e&&(i(t),o(null))}).catch(t=>e&&o(t)).finally(()=>{e&&(c(!1),n>0&&(t=window.setTimeout(a,n)))})},a=()=>{document.hidden?t=window.setTimeout(a,n):r()};return r(),()=>{e=!1,window.clearTimeout(t)}},[...t,u,n]),{data:r,error:a,loading:s,reload:()=>d(e=>e+1),set:i}}var _e=[],ve=!1;function ye(){d&&(ve||(d.BackButton.onClick(()=>_e[_e.length-1]?.current?.()),ve=!0),_e.length>0?d.BackButton.show():d.BackButton.hide())}function be(e){let t=(0,l.useRef)(e);t.current=e;let n=e!==null;(0,l.useEffect)(()=>{if(n)return _e.push(t),ye(),()=>{let e=_e.indexOf(t);e>=0&&_e.splice(e,1),ye()}},[n])}function E(e){return(0,T.jsxs)(`section`,{className:`section`,children:[(e.title||e.action)&&(0,T.jsxs)(`div`,{className:`section-title`,children:[(0,T.jsx)(`span`,{children:e.title}),e.action]}),(0,T.jsx)(`div`,{className:`card`,children:e.children}),e.note&&(0,T.jsx)(`div`,{className:`note`,children:e.note})]})}function D(e){let t=(0,T.jsxs)(T.Fragment,{children:[e.before,(0,T.jsxs)(`div`,{className:`cell-body`,children:[(0,T.jsx)(`div`,{className:`cell-title`+(e.wrap?` wrap`:``),children:e.title}),e.sub&&(0,T.jsx)(`div`,{className:`cell-sub`,children:e.sub})]}),(e.after||e.chevron)&&(0,T.jsxs)(`div`,{className:`cell-after`,children:[e.after,e.chevron&&(0,T.jsx)(`span`,{className:`chevron`})]})]});return e.onClick?(0,T.jsx)(`button`,{className:`cell`,onClick:e.onClick,children:t}):(0,T.jsx)(`div`,{className:`cell`,children:t})}function O(e){let[t,n]=(0,l.useState)(!1),r=(0,l.useRef)(!0);(0,l.useEffect)(()=>()=>{r.current=!1},[]);let i=()=>{if(t||!e.onClick)return;p(`tap`);let i=e.onClick();i instanceof Promise&&(n(!0),i.finally(()=>r.current&&n(!1)))},a=[`btn`,e.kind&&e.kind!==`primary`?e.kind:``,e.small?`small`:``,e.wide?`wide`:``];return(0,T.jsx)(`button`,{className:a.filter(Boolean).join(` `),onClick:i,disabled:e.disabled||t,children:t?(0,T.jsx)(`span`,{className:`spinner`}):e.children})}function xe(e){return(0,T.jsx)(`button`,{className:`switch`,role:`switch`,"aria-checked":e.checked,"aria-label":e.label,onClick:()=>{p(`tap`),e.onChange(!e.checked)}})}function k(e){return(0,T.jsx)(`select`,{className:`select`+(e.compact?` compact`:``),"aria-label":e.label,disabled:e.disabled,value:e.value,onChange:t=>e.onChange(t.target.value),children:e.options.map(e=>(0,T.jsx)(`option`,{value:e.value,children:e.label},e.value))})}function A(e){return(0,T.jsx)(`div`,{className:`segmented`,role:`tablist`,children:e.options.map(t=>(0,T.jsx)(`button`,{role:`tab`,"aria-selected":t.value===e.value,onClick:()=>e.onChange(t.value),children:t.label},t.value))})}function Se(e){let t=Math.max(0,Math.min(1,e.value))*100;return(0,T.jsx)(`div`,{className:`meter`+(e.busy?` busy`:``),children:(0,T.jsx)(`div`,{style:{width:t+`%`}})})}function Ce(){return(0,T.jsx)(`div`,{className:`spinner`,role:`progressbar`})}function we(e){return(0,T.jsx)(`div`,{className:`empty`,children:e.children})}function Te(e){let{data:t,error:n,loading:r,reload:i}=e.of;return t===null?r?(0,T.jsx)(Ce,{}):(0,T.jsxs)(we,{children:[(0,T.jsx)(`p`,{children:he(n)}),(0,T.jsx)(O,{kind:`soft`,onClick:i,children:S(`app.retry`)})]}):(0,T.jsx)(T.Fragment,{children:e.children(t)})}function Ee(e){return(0,T.jsx)(`div`,{className:`sheet-back`,onClick:e.onClose,children:(0,T.jsx)(`div`,{className:`sheet`,role:`dialog`,"aria-modal":`true`,onClick:e=>e.stopPropagation(),children:e.children})})}function j(){let{me:e,go:t}=me(),n=ge(()=>b(`GET`,`history?limit=5`),[]),r=e.pass_until>Date.now(),i=e.limits;return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(E,{children:[(0,T.jsxs)(`div`,{className:`pad`,children:[(0,T.jsx)(`div`,{className:`hint`,children:S(`app.home.hello`,{Name:e.name})}),(0,T.jsx)(`div`,{className:`big`,children:S(r?`app.home.pass_active`:`app.home.plan_free`)}),(0,T.jsx)(`div`,{className:`hint`,children:r?S(`app.pass_until`,{Until:le(e.pass_until)}):S(`app.home.plan_free_hint`)})]}),(0,T.jsx)(D,{title:S(`app.home.balance`),after:(0,T.jsx)(`b`,{children:w(e.balance)}),chevron:e.payments,onClick:e.payments?()=>t({tab:`buy`}):void 0})]}),(0,T.jsx)(E,{title:S(`app.home.today`),children:(0,T.jsxs)(`div`,{className:`pad stack`,children:[(0,T.jsx)(De,{label:S(`app.home.downloads`),used:e.usage.downloads,max:i.daily_downloads,format:C}),(0,T.jsx)(De,{label:S(`app.home.volume`),used:e.usage.bytes,max:i.daily_bytes,format:oe})]})}),(0,T.jsx)(ke,{}),(0,T.jsx)(E,{title:S(`app.home.recent`),action:(0,T.jsx)(O,{kind:`plain`,onClick:()=>t({tab:`home`,page:`history`}),children:S(`app.home.all_history`)}),children:n.data&&n.data.items.length>0?n.data.items.map(e=>(0,T.jsx)(Oe,{item:e},e.id)):(0,T.jsx)(`div`,{className:`empty`,children:n.loading?``:S(`app.history.empty`)})})]})}function De(e){let t=e.max<=0;return(0,T.jsxs)(`div`,{children:[(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`span`,{className:`grow`,children:e.label}),(0,T.jsx)(`span`,{className:`hint`,children:t?S(`app.home.used_unlimited`,{Used:e.format(e.used)}):S(`app.home.used_of`,{Used:e.format(e.used),Max:e.format(e.max)})})]}),(0,T.jsx)(Se,{value:t?0:e.used/e.max})]})}function Oe(e){let{notify:t,fail:n}=me(),r=e.item;return(0,T.jsx)(D,{title:r.title||S(`app.untitled`),sub:[de(r.profile),r.size>0?oe(r.size):``,le(r.at)].filter(Boolean).join(` · `),after:(0,T.jsx)(O,{small:!0,kind:`soft`,onClick:async()=>{try{await b(`POST`,`history/`+r.id+`/resend`),t(S(`app.sent_to_chat`))}catch(e){n(e)}},children:S(`app.history.resend`)})})}function ke(){let{go:e,notify:t}=me(),[n,r]=(0,l.useState)(``),[i,a]=(0,l.useState)(null),[o,s]=(0,l.useState)(null),c=e=>s({text:he(e),upgradable:e instanceof y&&e.upgradable}),u=async()=>{s(null),a(null);try{a(await b(`POST`,`probe`,{url:n.trim()}))}catch(e){c(e)}},d=async n=>{if(i){s(null);try{await b(`POST`,`download`,{url:i.url,profile:n}),a(null),r(``),t(S(`app.sent_to_chat`)),e({tab:`queue`})}catch(e){c(e)}}};return(0,T.jsx)(E,{title:S(`app.home.paste_title`),children:(0,T.jsxs)(`div`,{className:`pad stack`,children:[(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`input`,{className:`input grow`,type:`url`,inputMode:`url`,autoCapitalize:`off`,autoCorrect:`off`,spellCheck:!1,dir:`ltr`,placeholder:S(`app.home.paste_placeholder`),value:n,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&n.trim()&&u()}}),(0,T.jsx)(O,{onClick:u,disabled:!n.trim(),children:S(`app.home.look_up`)})]}),o&&(0,T.jsxs)(`div`,{className:`stack`,children:[(0,T.jsx)(`div`,{className:`error`,children:o.text}),o.upgradable&&(0,T.jsx)(O,{kind:`soft`,onClick:()=>e({tab:`buy`}),children:S(`app.see_plans`)})]}),i&&(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`cell-title wrap`,children:i.title||S(`app.untitled`)}),(0,T.jsx)(`div`,{className:`hint`,children:[i.uploader,i.duration>0?se(i.duration):``,i.site].filter(Boolean).join(` · `)})]}),(0,T.jsx)(`div`,{className:`row wrap`,children:i.options.map(e=>(0,T.jsx)(O,{kind:`soft`,onClick:()=>d(e.profile),children:e.size?S(`btn.with_size`,{Label:de(e.profile),Size:oe(e.size)}):de(e.profile)},e.profile))})]})]})})}function Ae(e){let{notify:t,fail:n,reload:r}=me(),[i,a]=(0,l.useState)(e.purchase),[o,s]=(0,l.useState)(Date.now()),c=(0,l.useRef)(e.onPaid);c.current=e.onPaid,(0,l.useEffect)(()=>{if(i.status!==`pending`)return;let e=!0,t=window.setInterval(()=>{document.hidden||b(`GET`,`purchase/`+i.id).then(t=>{e&&t.status!==`pending`&&(a(e=>({...e,...t})),t.status===`paid`&&(p(`success`),r(),c.current?.(t)))}).catch(()=>void 0)},2500),n=window.setInterval(()=>s(Date.now()),1e3);return()=>{e=!1,window.clearInterval(t),window.clearInterval(n)}},[i.id,i.status,r]);let u=S(`product.`+i.product),d=i.method===`stars`?ie(i.stars):w(i.amount);if(i.status===`paid`)return(0,T.jsxs)(`div`,{className:`stack center`,children:[(0,T.jsx)(`div`,{className:`paid-mark`,children:`✓`}),(0,T.jsx)(`div`,{className:`big`,children:S(`app.invoice.paid`)}),(0,T.jsx)(`div`,{children:S(`app.invoice.paid_text`,{Product:u,Amount:d})}),i.pass_until?(0,T.jsx)(`div`,{className:`hint`,children:S(`app.pass_until`,{Until:le(i.pass_until)})}):null,i.balance!==void 0&&(0,T.jsx)(`div`,{className:`hint`,children:S(`app.balance_is`,{Balance:w(i.balance)})}),(0,T.jsx)(O,{wide:!0,onClick:e.onDone,children:S(`app.done`)})]});if(i.status!==`pending`)return(0,T.jsxs)(`div`,{className:`stack center`,children:[(0,T.jsx)(`div`,{className:`big`,children:S(`app.invoice.`+i.status)}),(0,T.jsx)(`div`,{className:`hint`,children:S(`app.invoice.closed_text`)}),(0,T.jsx)(O,{wide:!0,onClick:e.onDone,children:S(`app.close`)})]});if(i.method===`stars`)return(0,T.jsxs)(`div`,{className:`stack center`,children:[(0,T.jsx)(`div`,{className:`hint`,children:u}),(0,T.jsx)(`div`,{className:`big`,children:d}),(0,T.jsx)(`div`,{className:`hint`,role:`status`,children:S(`app.invoice.stars_waiting`)}),i.invoice_link&&(0,T.jsx)(O,{wide:!0,onClick:()=>g(i.invoice_link??``,()=>void 0),children:S(`app.invoice.stars_pay`)}),(0,T.jsx)(O,{kind:`plain`,onClick:async()=>{try{await b(`POST`,`purchase/`+i.id+`/cancel`)}catch{}e.onDone()},children:S(`app.invoice.cancel`)})]});let f=Math.max(0,Math.floor((i.expires_at-o)/1e3)),m=i.bolt11??``;return(0,T.jsxs)(`div`,{className:`stack`,children:[(0,T.jsxs)(`div`,{className:`center`,children:[(0,T.jsx)(`div`,{className:`hint`,children:u}),(0,T.jsx)(`div`,{className:`big`,children:w(i.amount)})]}),i.qr&&(0,T.jsx)(`img`,{className:`qr`,src:i.qr,alt:S(`app.invoice.qr_alt`)}),(0,T.jsxs)(`div`,{className:`mono hint center`,children:[m.slice(0,24),`…`,m.slice(-12)]}),(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,kind:`soft`,onClick:async()=>{await v(m)?t(S(`app.copied`)):n(null)},children:S(`app.invoice.copy`)})}),(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,onClick:()=>h(window.location.origin+`/pay/`+i.id),children:S(`btn.open_wallet`)})})]}),(0,T.jsx)(`div`,{className:`center hint`,role:`timer`,children:f>0?S(`app.invoice.waiting`,{Time:se(f)}):S(`app.invoice.checking`)}),(0,T.jsx)(`div`,{className:`center`,children:(0,T.jsx)(O,{kind:`plain`,onClick:async()=>{try{await b(`POST`,`purchase/`+i.id+`/cancel`)}catch{}e.onDone()},children:S(`app.invoice.cancel`)})})]})}function je(){let{notify:e,fail:t}=me(),n=ge(()=>b(`GET`,`queue`),[],2e3),[r,i]=(0,l.useState)(null),a=async r=>{if(await m(S(`app.queue.cancel_confirm`,{Title:r.title||S(`app.untitled`)}))){try{await b(`POST`,`queue/`+r.id+`/cancel`),e(S(`app.queue.cancelled`))}catch(e){t(e)}n.reload()}},o=async r=>{try{let t=await b(`POST`,`queue/`+r.id+`/prioritize`);t.done?e(S(`app.queue.prioritized`)):t.purchase&&i(t.purchase)}catch(e){t(e)}n.reload()};return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(E,{title:S(`app.queue.title`),note:S(`app.queue.note`),children:(0,T.jsx)(Te,{of:n,children:e=>e.jobs.length===0?(0,T.jsx)(we,{children:S(`app.queue.empty`)}):e.jobs.map(e=>(0,T.jsx)(Ne,{job:e,onCancel:()=>a(e),onPrioritize:()=>o(e)},e.id))})}),r&&(0,T.jsx)(Ee,{onClose:()=>i(null),children:(0,T.jsx)(Ae,{purchase:r,onPaid:()=>n.reload(),onDone:()=>{i(null),n.reload()}})})]})}function Me(e){return e.status===`queued`?S(`app.queue.waiting`,{Position:e.position??1,Wait:ce(e.wait_seconds??0)}):e.status===`delivering`||e.stage===`uploading`?S(`app.queue.sending`):e.stage===`processing`?S(`app.queue.processing`):e.progress>0?S(`app.queue.downloading_pct`,{Percent:ae(e.progress)}):S(`app.queue.downloading`)}function Ne(e){let t=e.job,n=t.status!==`queued`&&(t.progress<=0||t.stage===`processing`||t.status===`delivering`);return(0,T.jsx)(`div`,{className:`cell`,children:(0,T.jsxs)(`div`,{className:`cell-body`,children:[(0,T.jsx)(`div`,{className:`cell-title`,children:t.title||S(`app.untitled`)}),(0,T.jsxs)(`div`,{className:`cell-sub`,children:[de(t.profile),` · `,Me(t)]}),t.status!==`queued`&&(0,T.jsx)(Se,{value:t.progress,busy:n}),(t.can_cancel||t.can_prioritize)&&(0,T.jsxs)(`div`,{className:`row`,style:{marginBlockStart:8},children:[t.can_prioritize&&(0,T.jsx)(O,{small:!0,onClick:e.onPrioritize,children:S(`app.queue.prioritize`,{Price:w(t.skip_price??0)})}),t.can_cancel&&(0,T.jsx)(O,{small:!0,kind:`danger`,onClick:e.onCancel,children:S(`btn.cancel`)})]})]})})}function Pe(e){let{me:t,go:n,back:r,fail:i}=me(),a=ge(()=>b(`GET`,`products`),[]),o=ge(()=>b(`GET`,`groups`),[]),[s,c]=(0,l.useState)(e.target??null),[u,d]=(0,l.useState)(null),[f,p]=(0,l.useState)(!1),[m,h]=(0,l.useState)(null),_=m??(a.data&&!a.data.lightning?`stars`:`lightning`),v=u?3:s?2:1;be(v===2&&!e.target?()=>c(null):v===3&&u?.status!==`pending`?()=>d(null):null);let y=async(e,t)=>{if(!f){p(!0);try{let n=await b(`POST`,`purchase`,{target:s,product:e,amount:t,method:_});d(n),n.method===`stars`&&n.invoice_link&&g(n.invoice_link,e=>{(e===`cancelled`||e===`failed`)&&(b(`POST`,`purchase/`+n.id+`/cancel`).catch(()=>void 0),d(null),e===`failed`&&i(null))})}catch(e){i(e)}p(!1)}},ee=o.data?.groups.find(e=>e.id===s),te=s===`me`?S(`app.buy.for_me`):ee?.title??S(`app.buy.for_group`);return(0,T.jsx)(Te,{of:a,children:i=>i.enabled?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`div`,{className:`steps`,"aria-label":S(`app.buy.step`,{Step:v,Total:3}),children:[1,2,3].map(e=>(0,T.jsx)(`span`,{className:e<=v?`on`:``},e))}),v===1&&(0,T.jsxs)(E,{title:S(`app.buy.target_title`),note:S(`app.buy.target_note`),children:[(0,T.jsx)(D,{title:S(`app.buy.for_me`),sub:S(`app.balance_is`,{Balance:w(t.balance)}),chevron:!0,onClick:()=>c(`me`)}),o.data?.groups.map(e=>(0,T.jsx)(D,{title:e.title,sub:S(`app.balance_is`,{Balance:w(e.balance)}),chevron:!0,onClick:()=>c(e.id)},e.id))]}),v===2&&(0,T.jsxs)(T.Fragment,{children:[i.lightning&&i.stars&&(0,T.jsx)(A,{value:_,onChange:h,options:[{value:`lightning`,label:S(`app.buy.method_lightning`)},{value:`stars`,label:S(`app.buy.method_stars`)}]}),(0,T.jsx)(E,{title:S(`app.buy.pass_title`,{Target:te}),note:S(`app.buy.pass_note`),children:i.passes.filter(e=>_===`lightning`||e.stars>0).map(e=>(0,T.jsx)(D,{title:S(`product.`+e.product),after:(0,T.jsx)(`b`,{children:_===`stars`?ie(e.stars):w(e.price)}),chevron:!0,onClick:()=>y(e.product,0)},e.product))}),(0,T.jsx)(E,{title:S(`app.buy.credits_title`),note:S(`app.buy.credits_note`,{Price:w(i.credit_per_download)}),children:(_===`stars`?i.stars_packs:i.credit_packs.map(e=>({amount:e,stars:0}))).map(e=>(0,T.jsx)(D,{title:w(e.amount),sub:i.credit_per_download>0?S(`app.buy.credits_downloads`,{Count:Math.floor(e.amount/i.credit_per_download)}):void 0,after:_===`stars`?(0,T.jsx)(`b`,{children:ie(e.stars)}):void 0,chevron:!0,onClick:()=>y(`credits`,e.amount)},e.amount))}),(0,T.jsxs)(E,{title:S(`app.buy.paid_title`),children:[(0,T.jsx)(D,{title:S(`app.limit.size`),after:Fe(i.paid.max_size,oe)}),(0,T.jsx)(D,{title:S(`app.limit.duration`),after:Fe(i.paid.max_duration,se)}),(0,T.jsx)(D,{title:S(`app.limit.per_day`),after:Fe(i.paid.daily_downloads,C)}),(0,T.jsx)(D,{title:S(`app.limit.at_once`),after:Fe(i.paid.active_jobs,C)})]})]}),v===3&&u&&(0,T.jsx)(E,{children:(0,T.jsx)(`div`,{className:`pad`,children:(0,T.jsx)(Ae,{purchase:u,onPaid:e=>d(t=>t&&{...t,...e}),onDone:()=>{d(null),e.target?r():n({tab:`home`})}})})})]}):(0,T.jsx)(we,{children:S(`app.buy.unavailable`)})})}function Fe(e,t){return e>0?t(e):S(`app.limit.none`)}function Ie(){let e=ge(()=>b(`GET`,`history`),[]);return(0,T.jsx)(E,{title:S(`app.history.title`),note:S(`app.history.note`),children:(0,T.jsx)(Te,{of:e,children:e=>e.items.length===0?(0,T.jsx)(we,{children:S(`app.history.empty`)}):e.items.map(e=>(0,T.jsx)(Oe,{item:e},e.id))})})}function Le(){let{go:e}=me(),t=ge(()=>b(`GET`,`groups`),[]);return(0,T.jsx)(E,{title:S(`app.groups.title`),note:S(`app.groups.note`),children:(0,T.jsx)(Te,{of:t,children:t=>t.groups.length===0?(0,T.jsx)(we,{children:S(`app.groups.empty`)}):t.groups.map(t=>(0,T.jsx)(D,{title:t.title,sub:[S(`app.balance_is`,{Balance:w(t.balance)}),t.pass_until>Date.now()?S(`app.pass_until`,{Until:ue(t.pass_until)}):S(`app.groups.no_pass`)].join(` · `),chevron:!0,onClick:()=>e({tab:`groups`,group:t.id})},t.id))})})}var Re=[`overview`,`settings`,`wallet`,`usage`],ze=[``,`best`,`1080`,`720`,`480`,`mp3`];function Be(e){return ze.map(t=>({value:t,label:t===``?e:de(t)}))}function Ve(e){let[t,n]=(0,l.useState)(e.view),r=ge(()=>b(`GET`,`groups/`+e.id),[e.id]);return(0,T.jsx)(Te,{of:r,children:e=>(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`div`,{className:`section-title`,children:(0,T.jsx)(`span`,{children:e.title})}),(0,T.jsx)(A,{value:t,onChange:n,options:Re.map(e=>({value:e,label:S(`app.group.tab.`+e)}))}),t===`overview`&&(0,T.jsx)(We,{group:e,open:n}),t===`settings`&&(0,T.jsx)(Je,{group:e,onSaved:t=>r.set({...e,settings:t})}),t===`wallet`&&(0,T.jsx)(Ye,{group:e,onSaved:t=>r.set({...e,settings:t})}),t===`usage`&&(0,T.jsx)(Xe,{id:e.id})]})})}function He(e){return S(`settings.who_`+e.who_can_use)}function Ue(e){return S(`settings.spend_`+e.spend_rule)}function We(e){let t=e.group,n=t.settings,r=t.pass_until>Date.now();return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(`div`,{className:`stats section`,children:[(0,T.jsxs)(`div`,{className:`stat`,children:[(0,T.jsx)(`div`,{className:`hint`,children:S(`app.group.balance`)}),(0,T.jsx)(`div`,{className:`value`,children:w(t.balance)})]}),(0,T.jsxs)(`div`,{className:`stat`,children:[(0,T.jsx)(`div`,{className:`hint`,children:S(`app.group.pass`)}),(0,T.jsx)(`div`,{className:`value`,children:S(r?`app.group.pass_on`:`app.group.pass_off`)}),r&&(0,T.jsx)(`div`,{className:`hint`,children:S(`app.pass_until`,{Until:le(t.pass_until)})})]})]}),(0,T.jsxs)(E,{children:[(0,T.jsx)(D,{title:S(`settings.enabled`),after:n.enabled?S(`app.on`):S(`app.off`)}),(0,T.jsx)(D,{title:S(`settings.who`),after:He(n)}),(0,T.jsx)(D,{title:S(`settings.auto_detect`),after:n.auto_detect?S(`app.on`):S(`app.off`)}),(0,T.jsx)(D,{title:S(`settings.spend`),after:Ue(n)})]}),(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,kind:`soft`,onClick:()=>e.open(`settings`),children:S(`app.group.tab.settings`)})}),(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,onClick:()=>e.open(`wallet`),children:S(`app.group.tab.wallet`)})})]})]})}function Ge(e,t){let{notify:n,fail:r}=me(),[i,a]=(0,l.useState)(e.settings);return(0,l.useEffect)(()=>a(e.settings),[e.settings]),{draft:i,set:(e,t)=>a(n=>({...n,[e]:t})),dirty:JSON.stringify(i)!==JSON.stringify(e.settings),save:async()=>{try{t((await b(`PUT`,`groups/`+e.id+`/settings`,i)).settings),n(S(`app.saved`))}catch(e){r(e)}}}}function Ke(e){return(0,T.jsx)(`input`,{className:`input compact number`,type:`number`,inputMode:`numeric`,min:0,max:e.max,"aria-label":e.label,value:e.value===0?``:e.value,placeholder:`0`,onChange:t=>{let n=Math.max(0,Math.floor(Number(t.target.value)||0));e.onChange(e.max&&n>e.max?e.max:n)}})}function qe(e){let[t,n]=(0,l.useState)(``),r=()=>{let r=t.trim().toLowerCase().replace(/^[a-z]+:\/\//,``).replace(/\/.*$/,``).replace(/^www\./,``);r&&!e.value.includes(r)&&e.onChange([...e.value,r]),n(``)};return(0,T.jsx)(E,{title:e.title,note:e.note,children:(0,T.jsxs)(`div`,{className:`pad stack`,children:[e.value.length>0&&(0,T.jsx)(`div`,{className:`chips`,children:e.value.map(t=>(0,T.jsxs)(`button`,{className:`chip`,dir:`ltr`,"aria-label":S(`app.group.remove_site`,{Site:t}),onClick:()=>e.onChange(e.value.filter(e=>e!==t)),children:[t,` ×`]},t))}),(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`input`,{className:`input grow`,dir:`ltr`,autoCapitalize:`off`,autoCorrect:`off`,spellCheck:!1,placeholder:S(`app.group.site_placeholder`),value:t,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&r()}}),(0,T.jsx)(O,{kind:`soft`,onClick:r,disabled:!t.trim(),children:S(`app.add`)})]})]})})}function Je(e){let{me:t}=me(),{draft:n,set:r,dirty:i,save:a}=Ge(e.group,e.onSaved),o=e.group;return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(E,{children:[(0,T.jsx)(D,{title:S(`settings.enabled`),after:(0,T.jsx)(xe,{label:S(`settings.enabled`),checked:n.enabled,onChange:e=>r(`enabled`,e)})}),(0,T.jsx)(D,{title:S(`settings.auto_detect`),sub:S(`app.group.auto_detect_hint`),wrap:!0,after:(0,T.jsx)(xe,{label:S(`settings.auto_detect`),checked:n.auto_detect,onChange:e=>r(`auto_detect`,e)})}),(0,T.jsx)(D,{title:S(`settings.delete_commands`),wrap:!0,after:(0,T.jsx)(xe,{label:S(`settings.delete_commands`),checked:n.delete_commands,onChange:e=>r(`delete_commands`,e)})})]}),(0,T.jsxs)(E,{children:[(0,T.jsx)(D,{title:S(`settings.who`),after:(0,T.jsx)(k,{compact:!0,label:S(`settings.who`),value:n.who_can_use,onChange:e=>r(`who_can_use`,e),options:[`everyone`,`pass_holders`,`admins`].map(e=>({value:e,label:S(`settings.who_`+e)}))})}),(0,T.jsx)(D,{title:S(`settings.quality`),after:(0,T.jsx)(k,{compact:!0,label:S(`settings.quality`),value:n.quality,onChange:e=>r(`quality`,e),options:Be(S(`quality.ask`))})}),(0,T.jsx)(D,{title:S(`app.group.language`),after:(0,T.jsx)(k,{compact:!0,label:S(`app.group.language`),value:n.lang,onChange:e=>r(`lang`,e),options:[{value:``,label:S(`settings.lang_auto`)},...t.languages.map(e=>({value:e.code,label:e.name}))]})})]}),(0,T.jsxs)(E,{title:S(`app.group.caps_title`),note:S(`app.group.caps_note`,{Size:oe(o.tier_max_size_mb*1048576)}),children:[(0,T.jsx)(D,{title:S(`app.group.max_size`),wrap:!0,after:(0,T.jsx)(Ke,{label:S(`app.group.max_size`),value:n.max_size_mb,max:o.tier_max_size_mb||void 0,onChange:e=>r(`max_size_mb`,e)})}),(0,T.jsx)(D,{title:S(`app.group.max_minutes`),wrap:!0,after:(0,T.jsx)(Ke,{label:S(`app.group.max_minutes`),value:Math.round(n.max_duration/60),max:o.tier_max_duration?Math.floor(o.tier_max_duration/60):void 0,onChange:e=>r(`max_duration`,e*60)})})]}),(0,T.jsx)(qe,{title:S(`app.group.allowed_title`),note:S(`app.group.allowed_note`),value:n.allowed,onChange:e=>r(`allowed`,e)}),(0,T.jsx)(qe,{title:S(`app.group.blocked_title`),note:S(`app.group.blocked_note`),value:n.blocked,onChange:e=>r(`blocked`,e)}),(0,T.jsx)(O,{wide:!0,onClick:a,disabled:!i,children:S(`app.save`)})]})}function Ye(e){let{go:t,me:n}=me(),{draft:r,set:i,dirty:a,save:o}=Ge(e.group,e.onSaved),s=e.group,c=s.pass_until>Date.now();return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(E,{children:(0,T.jsxs)(`div`,{className:`pad stack`,children:[(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`hint`,children:S(`app.group.balance`)}),(0,T.jsx)(`div`,{className:`big`,children:w(s.balance)}),(0,T.jsx)(`div`,{className:`hint`,children:c?S(`app.pass_until`,{Until:le(s.pass_until)}):S(`app.groups.no_pass`)})]}),n.payments&&(0,T.jsx)(O,{wide:!0,onClick:()=>t({tab:`buy`,target:s.id}),children:S(`app.group.top_up`)})]})}),(0,T.jsxs)(E,{title:S(`app.group.rules_title`),note:S(`app.group.rules_note`),children:[(0,T.jsx)(D,{title:S(`settings.spend`),after:(0,T.jsx)(k,{compact:!0,label:S(`settings.spend`),value:r.spend_rule,onChange:e=>i(`spend_rule`,e),options:[`admins`,`anyone`,`capped`].map(e=>({value:e,label:S(`settings.spend_`+e)}))})}),r.spend_rule===`capped`&&(0,T.jsx)(D,{title:S(`app.group.spend_cap`),wrap:!0,after:(0,T.jsx)(Ke,{label:S(`app.group.spend_cap`),value:r.spend_cap,onChange:e=>i(`spend_cap`,e)})}),(0,T.jsx)(D,{title:S(`app.group.daily_cap`),wrap:!0,after:(0,T.jsx)(Ke,{label:S(`app.group.daily_cap`),value:r.daily_cap,onChange:e=>i(`daily_cap`,e)})})]}),(0,T.jsx)(O,{wide:!0,onClick:o,disabled:!a,children:S(`app.save`)})]})}function Xe(e){let t=ge(()=>b(`GET`,`groups/`+e.id+`/usage`),[e.id]);return(0,T.jsx)(Te,{of:t,children:e=>(0,T.jsx)(E,{title:S(`app.group.usage_title`,{Count:e.days}),children:e.members.length===0?(0,T.jsx)(we,{children:S(`app.group.usage_empty`)}):(0,T.jsxs)(`table`,{className:`table`,children:[(0,T.jsx)(`thead`,{children:(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`th`,{children:S(`app.group.col_member`)}),(0,T.jsx)(`th`,{children:S(`app.group.col_downloads`)}),(0,T.jsx)(`th`,{children:S(`app.group.col_volume`)}),(0,T.jsx)(`th`,{children:S(`app.group.col_spent`)})]})}),(0,T.jsx)(`tbody`,{children:e.members.map((e,t)=>(0,T.jsxs)(`tr`,{children:[(0,T.jsx)(`td`,{children:e.name}),(0,T.jsx)(`td`,{children:C(e.downloads)}),(0,T.jsx)(`td`,{children:oe(e.bytes)}),(0,T.jsx)(`td`,{children:w(e.sats)})]},t))})]})})})}function Ze(){let{me:e,go:t,notify:n,fail:r,reload:i}=me(),a=async e=>{try{await b(`PUT`,`me`,e),await i(),n(S(`app.saved`))}catch(e){r(e)}},o=e.quality===`mp3`,s=e.support.startsWith(`@`)?`https://t.me/`+e.support.slice(1):``;return(0,T.jsxs)(T.Fragment,{children:[(0,T.jsxs)(E,{title:S(`app.me.downloads_title`),note:S(`app.me.quality_note`),children:[(0,T.jsx)(D,{title:S(`settings.quality`),after:(0,T.jsx)(k,{compact:!0,label:S(`settings.quality`),disabled:o,value:o?`fit`:e.quality,onChange:e=>void a({quality:e}),options:[{value:`fit`,label:S(`quality.fit`)},...Be(S(`quality.ask`)).filter(e=>e.value!==`mp3`)]})}),(0,T.jsx)(D,{title:S(`app.me.audio_only`),sub:S(`app.me.audio_only_hint`),wrap:!0,after:(0,T.jsx)(xe,{label:S(`app.me.audio_only`),checked:o,onChange:e=>void a({quality:e?`mp3`:`fit`})})})]}),(0,T.jsx)(E,{title:S(`app.me.language_title`),children:(0,T.jsx)(D,{title:S(`app.me.language`),after:(0,T.jsx)(k,{compact:!0,label:S(`app.me.language`),value:e.lang_override,onChange:e=>void a({lang:e||`auto`}),options:[{value:``,label:S(`language.auto`)},...e.languages.map(e=>({value:e.code,label:e.name}))]})})}),(0,T.jsxs)(E,{title:S(`app.me.referral_title`),note:e.referral_reward>0?S(`app.me.referral_note`,{Reward:w(e.referral_reward)}):void 0,children:[(0,T.jsxs)(`div`,{className:`pad stack`,children:[(0,T.jsx)(`div`,{className:`mono`,children:e.referral_link}),(0,T.jsxs)(`div`,{className:`row`,children:[(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,kind:`soft`,onClick:async()=>{await v(e.referral_link)?n(S(`app.copied`)):r(null)},children:S(`app.me.copy_link`)})}),(0,T.jsx)(`div`,{className:`grow`,children:(0,T.jsx)(O,{wide:!0,onClick:()=>_(`https://t.me/share/url?url=`+encodeURIComponent(e.referral_link)+`&text=`+encodeURIComponent(S(`referral.share_text`))),children:S(`app.me.share`)})})]}),e.referral_qr&&(0,T.jsxs)(`details`,{className:`qr-toggle`,children:[(0,T.jsx)(`summary`,{children:S(`app.me.qr`)}),(0,T.jsx)(`img`,{className:`qr`,src:e.referral_qr,alt:S(`app.me.qr`)})]})]}),(0,T.jsx)(D,{title:S(`app.me.invited`),after:S(`app.me.invited_count`,{Count:e.referral_count})}),(0,T.jsx)(D,{title:S(`app.me.converted`),after:String(e.referral_converted)}),(0,T.jsx)(D,{title:S(`app.me.earned`),after:w(e.referral_earned)}),e.referral_pending>0&&(0,T.jsx)(D,{title:S(`app.me.pending`),after:w(e.referral_pending)})]}),(0,T.jsxs)(E,{children:[(0,T.jsx)(D,{title:S(`app.history.title`),chevron:!0,onClick:()=>t({tab:`home`,page:`history`})}),(0,T.jsx)(D,{title:S(`app.me.support`),after:e.support,chevron:s!==``,onClick:s?()=>_(s):void 0})]})]})}var Qe={home:`M3 11.5 12 4l9 7.5M5.5 10v9.5h13V10`,queue:`M12 4v11m0 0-4-4m4 4 4-4M5 20h14`,buy:`M13 3 5 13.5h6L10 21l9-11h-6.5L13 3Z`,groups:`M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.5 19c.5-3 2.6-5 5.5-5s5 2 5.5 5M16.5 11.5a2.5 2.5 0 1 0 0-5M17 14.2c2 .3 3.3 1.9 3.7 4.3`,me:`M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8ZM4.5 20c.7-3.5 3.7-6 7.5-6s6.8 2.5 7.5 6`},$e=[`home`,`queue`,`buy`,`groups`,`me`];function et(e){let t=new URLSearchParams(window.location.search).get(`page`)??e;return t.startsWith(`group_`)?{tab:`groups`,group:t.slice(6),view:`settings`}:t===`buy`?{tab:`buy`}:t===`queue`?{tab:`queue`}:{tab:`home`}}function tt(){let[e,t]=(0,l.useState)(null),[n,r]=(0,l.useState)(null),[i,a]=(0,l.useState)([{tab:`home`}]),[o,s]=(0,l.useState)(null),[c,u]=(0,l.useState)(0),d=(0,l.useRef)(void 0),f=(0,l.useRef)(!1),m=(0,l.useCallback)(async()=>{let[e,n]=await Promise.all([b(`GET`,`me`),b(`GET`,`i18n`)]);return x(n),document.title=S(`app.title`),t(e),e},[]);(0,l.useEffect)(()=>{f.current||(f.current=!0,m().then(e=>a([et(e.start_param)])).catch(r))},[m]),(0,l.useEffect)(()=>{if(!e)return;let t=!0,n=()=>{document.hidden||b(`GET`,`queue`).then(e=>t&&u(e.jobs.length)).catch(()=>void 0)};n();let r=window.setInterval(n,5e3);return()=>{t=!1,window.clearInterval(r)}},[e]);let h=i[i.length-1],g=(0,l.useCallback)((e,t=!1)=>{window.clearTimeout(d.current),s({text:e,bad:t}),p(t?`error`:`success`),d.current=window.setTimeout(()=>s(null),3500)},[]),_=(0,l.useMemo)(()=>e?{me:e,route:h,go:e=>{let t=`page`in e||`group`in e||`target`in e;a(n=>t?[...n,e]:[e]),window.scrollTo(0,0)},back:()=>a(e=>e.length>1?e.slice(0,-1):[{tab:e[0].tab}]),notify:g,fail:e=>g(he(e),!0),reload:async()=>{await m()}}:null,[e,h,g,m]);if(be(_&&i.length>1?_.back:null),n){let e=n instanceof y?n.message:``;return(0,T.jsx)(`div`,{className:`app`,children:(0,T.jsxs)(`div`,{className:`empty`,children:[(0,T.jsx)(`p`,{className:`big`,children:`:(`}),(0,T.jsx)(`p`,{children:e}),!(n instanceof y&&n.status===401)&&(0,T.jsx)(`button`,{className:`btn soft`,"aria-label":`retry`,onClick:()=>window.location.reload(),children:`↻`})]})})}if(!_)return(0,T.jsx)(`div`,{className:`app`,children:(0,T.jsx)(Ce,{})});let v;return v=`group`in h?(0,T.jsx)(Ve,{id:h.group,view:h.view??`overview`},h.group):`page`in h?(0,T.jsx)(Ie,{}):h.tab===`queue`?(0,T.jsx)(je,{}):h.tab===`buy`?(0,T.jsx)(Pe,{target:`target`in h?h.target:void 0},`target`in h?h.target:`me`):h.tab===`groups`?(0,T.jsx)(Le,{}):h.tab===`me`?(0,T.jsx)(Ze,{}):(0,T.jsx)(j,{}),(0,T.jsxs)(pe.Provider,{value:_,children:[(0,T.jsx)(`main`,{className:`app`,children:v}),o&&(0,T.jsx)(`div`,{className:`toast`+(o.bad?` bad`:``),role:`status`,children:o.text}),(0,T.jsx)(`nav`,{className:`tabs`,children:$e.map(e=>(0,T.jsxs)(`button`,{"aria-current":h.tab===e?`page`:void 0,onClick:()=>_.go({tab:e}),children:[(0,T.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,T.jsx)(`path`,{d:Qe[e]})}),S(`app.tab.`+e),e===`queue`&&c>0&&(0,T.jsx)(`span`,{className:`badge`,children:c})]},e))})]})}d?.ready(),d?.expand(),(0,u.createRoot)(document.getElementById(`root`)).render((0,T.jsx)(l.StrictMode,{children:(0,T.jsx)(tt,{})})); \ No newline at end of file diff --git a/web/miniapp/dist/source.sha256 b/web/miniapp/dist/source.sha256 index 7b40ae2..d3d0866 100644 --- a/web/miniapp/dist/source.sha256 +++ b/web/miniapp/dist/source.sha256 @@ -1 +1 @@ -76674362440fe3a7ff1521135372c7f8ff3e06523cb9d2d3fded859c9d170e7f +3c98bec15c044f90e699f7a6b50fb1e6b1bb05928f40e22039c610dcbde14a31 diff --git a/web/miniapp/src/Invoice.tsx b/web/miniapp/src/Invoice.tsx index 5204f9e..edff871 100644 --- a/web/miniapp/src/Invoice.tsx +++ b/web/miniapp/src/Invoice.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { api, type Purchase } from "./api"; -import { clock, dateTime, sats, t } from "./i18n"; -import { copyText, haptic, openExternal } from "./tg"; +import { clock, dateTime, sats, stars, t } from "./i18n"; +import { copyText, haptic, openExternal, openInvoice } from "./tg"; import { Button, useApp } from "./ui"; // Invoice shows a Lightning invoice and waits for it to be paid. It asks @@ -40,13 +40,14 @@ export function Invoice(props: { purchase: Purchase; onDone(): void; onPaid?(p: }, [p.id, p.status, reload]); const title = t("product." + p.product); + const price = p.method === "stars" ? stars(p.stars) : sats(p.amount); if (p.status === "paid") { return (
✓
{t("app.invoice.paid")}
-
{t("app.invoice.paid_text", { Product: title, Amount: sats(p.amount) })}
+
{t("app.invoice.paid_text", { Product: title, Amount: price })}
{p.pass_until ?
{t("app.pass_until", { Until: dateTime(p.pass_until) })}
: null} {p.balance !== undefined &&
{t("app.balance_is", { Balance: sats(p.balance) })}
} + )} + +
+ ); + } + const left = Math.max(0, Math.floor((p.expires_at - now) / 1000)); const bolt11 = p.bolt11 ?? ""; diff --git a/web/miniapp/src/api.ts b/web/miniapp/src/api.ts index 5e9da2e..2e40384 100644 --- a/web/miniapp/src/api.ts +++ b/web/miniapp/src/api.ts @@ -120,7 +120,10 @@ export interface HistoryItem { export interface Products { enabled: boolean; - passes: { product: string; price: number }[]; + lightning: boolean; + stars: boolean; + passes: { product: string; price: number; stars: number }[]; + stars_packs: { amount: number; stars: number }[]; credit_packs: number[]; credit_per_download: number; paid: Tier; @@ -131,9 +134,12 @@ export interface Purchase { id: string; product: string; amount: number; - status: "pending" | "paid" | "expired" | "cancelled"; + status: "pending" | "paid" | "expired" | "cancelled" | "refunded"; expires_at: number; paid_at: number; + method: "lightning" | "stars"; + stars: number; + invoice_link?: string; bolt11?: string; qr?: string; balance?: number; diff --git a/web/miniapp/src/i18n.ts b/web/miniapp/src/i18n.ts index e0b522d..7c255d1 100644 --- a/web/miniapp/src/i18n.ts +++ b/web/miniapp/src/i18n.ts @@ -50,6 +50,11 @@ export function sats(n: number): string { return t("unit.sats", { Count: n, N: num(n) }); } +// stars formats an amount of Telegram Stars with its unit. +export function stars(n: number): string { + return t("unit.stars", { Count: n, N: num(n) }); +} + export function percent(fraction: number): string { return new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(fraction); } diff --git a/web/miniapp/src/pages/Buy.tsx b/web/miniapp/src/pages/Buy.tsx index 7720fbf..b4580cb 100644 --- a/web/miniapp/src/pages/Buy.tsx +++ b/web/miniapp/src/pages/Buy.tsx @@ -1,8 +1,11 @@ import { useState } from "react"; import { api, type Group, type Products, type Purchase } from "../api"; -import { clock, num, sats, size, t } from "../i18n"; +import { clock, num, sats, size, stars, t } from "../i18n"; import { Invoice } from "../Invoice"; -import { Cell, Empty, Loading, Section, useApp, useBack, useLoad } from "../ui"; +import { openInvoice } from "../tg"; +import { Cell, Empty, Loading, Section, Segmented, useApp, useBack, useLoad } from "../ui"; + +type Method = "lightning" | "stars"; // Buy is three steps: who it is for, what to buy, and the invoice. The // price of a product is set by the core when the invoice is made; the @@ -14,6 +17,9 @@ export function Buy(props: { target?: string }) { const [target, setTarget] = useState(props.target ?? null); const [purchase, setPurchase] = useState(null); const [busy, setBusy] = useState(false); + const [chosen, setChosen] = useState(null); + // Lightning first, when it is set up. + const method: Method = chosen ?? (products.data && !products.data.lightning ? "stars" : "lightning"); const step = purchase ? 3 : target ? 2 : 1; // Inside the flow the back button walks the steps before it leaves. @@ -29,7 +35,19 @@ export function Buy(props: { target?: string }) { if (busy) return; setBusy(true); try { - setPurchase(await api("POST", "purchase", { target, product, amount })); + const p = await api("POST", "purchase", { target, product, amount, method }); + setPurchase(p); + if (p.method === "stars" && p.invoice_link) { + // Telegram's payment sheet takes over; the core hears about the + // payment from Telegram and the invoice view asks the core. + openInvoice(p.invoice_link, (status) => { + if (status === "cancelled" || status === "failed") { + void api("POST", "purchase/" + p.id + "/cancel").catch(() => undefined); + setPurchase(null); + if (status === "failed") fail(null); + } + }); + } } catch (e) { fail(e); } @@ -74,34 +92,49 @@ export function Buy(props: { target?: string }) { {step === 2 && ( <> + {p.lightning && p.stars && ( + + value={method} + onChange={setChosen} + options={[ + { value: "lightning", label: t("app.buy.method_lightning") }, + { value: "stars", label: t("app.buy.method_stars") }, + ]} + /> + )}
- {p.passes.map((x) => ( - {sats(x.price)}} - chevron - onClick={() => buy(x.product, 0)} - /> - ))} + {p.passes + .filter((x) => method === "lightning" || x.stars > 0) + .map((x) => ( + {method === "stars" ? stars(x.stars) : sats(x.price)}} + chevron + onClick={() => buy(x.product, 0)} + /> + ))}
- {p.credit_packs.map((amount) => ( - 0 - ? t("app.buy.credits_downloads", { Count: Math.floor(amount / p.credit_per_download) }) - : undefined - } - chevron - onClick={() => buy("credits", amount)} - /> - ))} + {(method === "stars" ? p.stars_packs : p.credit_packs.map((amount) => ({ amount, stars: 0 }))).map( + (pack) => ( + 0 + ? t("app.buy.credits_downloads", { Count: Math.floor(pack.amount / p.credit_per_download) }) + : undefined + } + after={method === "stars" ? {stars(pack.stars)} : undefined} + chevron + onClick={() => buy("credits", pack.amount)} + /> + ), + )}
diff --git a/web/miniapp/src/tg.ts b/web/miniapp/src/tg.ts index f6730a2..8911d19 100644 --- a/web/miniapp/src/tg.ts +++ b/web/miniapp/src/tg.ts @@ -26,6 +26,7 @@ export interface WebApp { close(): void; openLink(url: string): void; openTelegramLink(url: string): void; + openInvoice?(url: string, cb?: (status: "paid" | "cancelled" | "failed" | "pending") => void): void; showConfirm(message: string, cb: (ok: boolean) => void): void; BackButton: BackButton; HapticFeedback: Haptics; @@ -60,6 +61,15 @@ export function openExternal(url: string): void { else window.open(url, "_blank", "noopener"); } +// openInvoice opens a Stars invoice link in Telegram's payment sheet. The +// status it reports is only a hint for the screen: the core learns about +// the payment from Telegram itself, and the app asks the core. +export function openInvoice(url: string, cb: (status: "paid" | "cancelled" | "failed" | "pending") => void): void { + if (tg?.openInvoice) tg.openInvoice(url, cb); + else if (tg) tg.openTelegramLink(url); + else window.open(url, "_blank"); +} + // openTelegram opens a t.me link inside Telegram. export function openTelegram(url: string): void { if (tg) tg.openTelegramLink(url);