diff --git a/.env.example b/.env.example index 40d53fc..b50cc94 100644 --- a/.env.example +++ b/.env.example @@ -209,8 +209,14 @@ PRICE_SKIP_QUEUE=50 # Top-up and tip amounts offered as buttons. CREDIT_PACKS=1000,5000,20000 DONATION_AMOUNTS=500,2100,10000 -# Credited to the inviter on an invited user's first purchase. 0 turns it off. -REFERRAL_REWARD=200 +# --- Referrals (Lightning) ------------------------------------------------------ +# Credited to the inviter when somebody they invited settles a first +# Lightning purchase. 0 turns the reward off. (The older name +# REFERRAL_REWARD still works; this one wins when both are set.) +REFERRAL_REWARD_SATS=200 +# The most one inviter earns per day (UTC), in sats. Rewards above it wait +# and are paid on a later day. 0 means no cap. +REFERRAL_DAILY_CAP=2000 # --- Rate limits ------------------------------------------------------------ # Links per minute. 0 means no limit. diff --git a/config.example.toml b/config.example.toml index 5d9130a..ad53836 100644 --- a/config.example.toml +++ b/config.example.toml @@ -26,6 +26,11 @@ multi_link_max = 5 # A "via @botname" line under file captions. caption_attribution = true +# Lightning referrals: the reward for a first settled purchase of somebody +# you invited, and the most one inviter earns per day (0 means no cap). +referral_reward_sats = 200 +referral_daily_cap = 2000 + [telegram] api_url = "https://api.telegram.org" mode = "polling" # polling or webhook @@ -128,7 +133,7 @@ one_off_per_100mb = 50 skip_queue = 50 credit_packs = [1000, 5000, 20000] donation_amounts = [500, 2100, 10000] -referral_reward = 200 +# referral_reward = 200 (older name of referral_reward_sats above) [rate] user_per_minute = 10 diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index eef7889..1d45e5b 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -1028,3 +1028,45 @@ the affiliate program. What was found and planned is in scripted walk through the bot in English, Spanish and Dutch. It is generated by the language test (`DLBOT_SCREENS=$PWD/docs/SCREENS.md go test ./internal/app -run TestEveryScreen`). + +### Phase 3: own referral system (sats) + +- **Codes.** A code is 8 characters of RFC 4648 base32 (A to Z, 2 to 7) + from 40 random bits, made when a user first needs a link and stored in + `users.ref_code` under a unique index (migration 00008). A clash is + retried with a new code. Codes are matched in upper case. +- **Links** are `https://t.me/?start=rf_`, with the username + from `getMe`. Old links (`?start=ref_`) still record the + inviter, but no screen shows them any more. The new prefix is `rf_` + rather than `ref_`, because a code can be all digits, like an old ID. +- **Who can be referred.** Only somebody who is new to the bot (the + first update from them is the /start with the link) can be referred, + once, and never by themselves. That covers "the same Telegram account": + one account cannot be credited for referring itself. An unknown or + broken code is ignored and the welcome is shown as usual. +- **Rewards.** + - The reward is `REFERRAL_REWARD_SATS` (the older `REFERRAL_REWARD` + still works). It is paid when the invited user settles their first + purchase, inside the same database transaction as the settlement. + An unpaid invoice earns nothing. + - Donations do not count. In Phase 4 only Lightning purchases count. + - Each invited user earns their inviter one reward, ever: a row in + `referral_rewards`, keyed by the invited user. Credits go through + the ledger with a dedupe key. Repeated webhooks and polls cannot pay + twice, because settlement itself is idempotent. +- **Daily cap.** `REFERRAL_DAILY_CAP` (default 2000 sats; 0 means no cap) + limits what one inviter is paid per UTC day. A reward over the cap is + recorded as pending and paid by the billing loop (about once a + minute) on a later day, as the cap allows, oldest first. Rewards paid + before this round were copied from the ledger into the new table, as + paid. +- **Stats.** /referral shows: + - Invited: users with this inviter. + - Bought something: rewards recorded. + - Earned: sats paid. + - Waiting: sats pending. + + The buttons are Share (Telegram's share URL with a line of text), Copy + 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. diff --git a/docs/SCREENS.md b/docs/SCREENS.md index 29593eb..838523d 100644 --- a/docs/SCREENS.md +++ b/docs/SCREENS.md @@ -42,7 +42,7 @@ editMessageCaption ``` Test Video -Sending it to Telegram… +Downloading… [Cancel] ``` @@ -50,7 +50,7 @@ editMessageCaption ``` Test Video -Downloading… +Sending it to Telegram… [Cancel] ``` @@ -244,6 +244,12 @@ This content is private or for members only. [Open app] ``` +sendMessage + +``` +Looking up the link… +``` + editMessageText ``` @@ -251,12 +257,6 @@ The site is limiting requests right now. Please try again in a few minutes. [Try again] ``` -sendMessage - -``` -Looking up the link… -``` - editMessageText ``` @@ -360,11 +360,16 @@ editMessageText ``` Invite friends -Share your link. When somebody you invited makes a first purchase, you get 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_CW5AYJM3 -You invited 0 people so far. +Invited: 0 · Bought something: 0 +Earned: 0 sats · Waiting: 0 sats + +You earn at most 2,000 sats a day. Rewards above that wait for the next day. +[Share] [Copy link] +[QR code] [Back] ``` @@ -567,11 +572,16 @@ sendMessage ``` Invite friends -Share your link. When somebody you invited makes a first purchase, you get 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_CW5AYJM3 -You invited 0 people so far. +Invited: 0 · Bought something: 0 +Earned: 0 sats · Waiting: 0 sats + +You earn at most 2,000 sats a day. Rewards above that wait for the next day. +[Share] [Copy link] +[QR code] ``` sendMessage @@ -859,7 +869,7 @@ sendPhoto ``` Day pass · 700 sats -lnbc7000n1fake9e41f41fd5cc828364d5339ff5a3c5c9cb74029e2a942757aba2c50ecf40f117 +lnbc7000n1fake932bb5fc424d32f8967f5a103ec1aa9b323d60cf969ac292033fe465b6058e60 Scan the code or tap the invoice to copy it. Valid for 10 minutes. [Open in wallet] @@ -904,7 +914,7 @@ editMessageCaption ``` Test Video -Enviándolo a Telegram… +Descargando… [Cancelar] ``` @@ -912,7 +922,7 @@ editMessageCaption ``` Test Video -Descargando… +Enviándolo a Telegram… [Cancelar] ``` @@ -1114,6 +1124,13 @@ Buscando el enlace… editMessageText +``` +El sitio está limitando los pedidos por ahora. Vuelve a intentar en unos minutos. +[Reintentar] +``` + +editMessageText + ``` Test Video Descargando… @@ -1128,13 +1145,6 @@ No funcionó. El archivo supera tu límite. Prueba con una calidad más baja. [Calidad menor] [Mejorar mi plan] ``` -editMessageText - -``` -El sitio está limitando los pedidos por ahora. Vuelve a intentar en unos minutos. -[Reintentar] -``` - sendMessage ``` @@ -1222,11 +1232,16 @@ editMessageText ``` Invita a tus amigos -Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_MXZGYTEK -Hasta ahora invitaste a 0 personas. +Invitados: 0 · Compraron algo: 0 +Ganado: 0 sats · En espera: 0 sats + +Ganas como máximo 2.000 sats al día. Lo que pase de eso espera al día siguiente. +[Compartir] [Copiar enlace] +[Código QR] [Volver] ``` @@ -1429,11 +1444,16 @@ sendMessage ``` Invita a tus amigos -Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_MXZGYTEK -Hasta ahora invitaste a 0 personas. +Invitados: 0 · Compraron algo: 0 +Ganado: 0 sats · En espera: 0 sats + +Ganas como máximo 2.000 sats al día. Lo que pase de eso espera al día siguiente. +[Compartir] [Copiar enlace] +[Código QR] ``` sendMessage @@ -1721,7 +1741,7 @@ sendPhoto ``` Pase de un día · 700 sats -lnbc7000n1fakee5e71ffd20cc9a72502b3121b9023ef84aaacb3bd8df64c5ebdb282615265645 +lnbc7000n1fake5bb91054d0d2b0cbcc9f5394928a595cf2ccba08d4a09432f7db5063c88ffd85 Escanea el código o toca la factura para copiarla. Vale por 10 minutos. [Abrir en la billetera] @@ -1869,6 +1889,14 @@ Downloaden… editMessageText +``` +Test Video +Naar Telegram sturen… +[Annuleren] +``` + +editMessageText + ``` Test Video Naar Telegram sturen… @@ -2076,11 +2104,16 @@ editMessageText ``` Nodig vrienden uit -Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_4VIFLSDC -Je hebt tot nu toe 0 mensen uitgenodigd. +Uitgenodigd: 0 · Iets gekocht: 0 +Verdiend: 0 sats · Wacht nog: 0 sats + +Je verdient maximaal 2.000 sats per dag. Wat daarboven komt, wacht tot de volgende dag. +[Delen] [Link kopiëren] +[QR-code] [Terug] ``` @@ -2283,11 +2316,16 @@ sendMessage ``` Nodig vrienden uit -Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij 200 sats. +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=ref_501 +https://t.me/nr_dl_test_bot?start=rf_4VIFLSDC -Je hebt tot nu toe 0 mensen uitgenodigd. +Uitgenodigd: 0 · Iets gekocht: 0 +Verdiend: 0 sats · Wacht nog: 0 sats + +Je verdient maximaal 2.000 sats per dag. Wat daarboven komt, wacht tot de volgende dag. +[Delen] [Link kopiëren] +[QR-code] ``` sendMessage @@ -2575,7 +2613,7 @@ sendPhoto ``` Dagpas · 700 sats -lnbc7000n1fake958d96c95c5e5aca4a2e7070e86b91a77c9f3c2f0701cf5d697aff726aa60632 +lnbc7000n1fake2279497394e085369465914011a009430187243aabd22a7b3642440c8ec67831 Scan de code of tik op de factuur om hem te kopiëren. Geldig voor 10 minuten. [Openen in wallet] diff --git a/docs/UPDATE_NOTES.md b/docs/UPDATE_NOTES.md index 2348dca..f7919d1 100644 --- a/docs/UPDATE_NOTES.md +++ b/docs/UPDATE_NOTES.md @@ -32,8 +32,10 @@ work changes. Decisions made on the way are recorded in wallet and ledger per user or group, passes, credits, one-off payments, gift codes and Cashu. - **Referrals** store the inviter's Telegram ID from `/start ref_`. - Only the count is shown and nothing is rewarded yet, although the - `REFERRAL_REWARD` setting exists. + Billing credits `REFERRAL_REWARD` sats to the inviter when an invited + user settles a first purchase, inside the settlement transaction. The + link shows the raw Telegram ID, and only the number of invited users + is shown. There is no daily cap. - **Mini App** (`web/miniapp`, React and Vite, built into `dist/` and embedded). Pages: Home, Queue, History, Buy, Me (`Profile.tsx`), Groups. The API is in `internal/api/miniapp.go`. diff --git a/internal/api/miniapp.go b/internal/api/miniapp.go index 6438cf1..547dd14 100644 --- a/internal/api/miniapp.go +++ b/internal/api/miniapp.go @@ -219,7 +219,16 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { } st, _ := m.Billing.State(ctx, db.OwnerUser, s.user.ID) usage, _ := m.Service.Usage(ctx, s.user.ID) - refs, _ := m.Store.CountReferrals(ctx, s.user.ID) + refStats, _ := m.Bot.ReferralStats(ctx, s.user.ID) + refLink, err := m.Bot.ReferralLink(ctx, s.user.ID) + if err != nil { + m.explain(w, s, err) + return + } + refQR := "" + if png, err := m.Bot.ReferralQR(ctx, s.user.ID); err == nil { + refQR = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + } var langs []map[string]string for _, l := range m.I18n.Langs() { if !m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID) { @@ -247,9 +256,14 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { DailyDownloads: dec.Limits.DailyDownloads, DailyBytes: dec.Limits.DailyBytes, }, "payments": m.Billing.Enabled(), - "referral_link": "https://t.me/" + m.Bot.Username() + "?start=ref_" + strconv.FormatInt(s.user.ID, 10), - "referral_count": refs, - "referral_reward": m.Cfg.Prices.ReferralReward, + "referral_link": refLink, + "referral_count": refStats.Invited, + "referral_converted": refStats.Converted, + "referral_earned": refStats.Earned, + "referral_pending": refStats.Pending, + "referral_qr": refQR, + "referral_reward": m.Cfg.Prices.ReferralReward, + "referral_daily_cap": m.Cfg.ReferralDailyCap, "support": support, "start_param": s.init.StartParam, "bot": m.Bot.Username(), @@ -327,7 +341,7 @@ func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { // appTables are the catalog tables the Mini App reads. Its own texts are // under "app"; names it shares with the chat (products, units, button and // setting labels) are not written twice. -var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language"} +var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language", "referral"} // messages returns the Mini App's texts in the user's language, from the // same catalogs the bot uses. Keys keep their full name: "app.tab.home". diff --git a/internal/app/miniapp_test.go b/internal/app/miniapp_test.go index 39a38e1..6fe5e53 100644 --- a/internal/app/miniapp_test.go +++ b/internal/app/miniapp_test.go @@ -694,7 +694,9 @@ func TestMiniAppPreferences(t *testing.T) { } me := h.must(alice, "GET", "me", nil) - if !strings.HasSuffix(me.str("referral_link"), "?start=ref_42") || len(me.list("languages")) == 0 { + code, _ := h.app.Store.RefCode(ctx, alice) + if me.str("referral_link") != "https://t.me/"+fakeserver.BotUsername+"?start=rf_"+code || len(me.list("languages")) == 0 || + !strings.HasPrefix(me.str("referral_qr"), "data:image/png;base64,") || me.num("referral_earned") != 0 { t.Fatalf("me = %s", me.Raw) } } diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 5e29999..1c2b816 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -7,6 +7,7 @@ import ( "io" "net" "net/http" + "net/url" "strings" "testing" "time" @@ -948,24 +949,47 @@ func TestReferralRewardEndToEnd(t *testing.T) { seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/referral") ref := h.wait(seq, "sendMessage", textHas("Invite friends")) - link := fmt.Sprintf("https://t.me/%s?start=ref_%d", fakeserver.BotUsername, alice) - if !strings.Contains(ref.Text(), link) || !strings.Contains(ref.Text(), "you get 200 sats") || - !strings.Contains(ref.Text(), "You invited 0 people") { + code, err := h.app.Store.RefCode(context.Background(), alice) + if err != nil { + t.Fatal(err) + } + link := fmt.Sprintf("https://t.me/%s?start=rf_%s", fakeserver.BotUsername, code) + // The link carries a random code, never the Telegram user ID. + if !strings.Contains(ref.Text(), link) || strings.Contains(ref.Text(), fmt.Sprint(alice)) || + !strings.Contains(ref.Text(), "you get 200 sats") || !strings.Contains(ref.Text(), "Invited: 0") || + !strings.Contains(ref.Text(), "at most 2,000 sats a day") { t.Fatalf("referral text = %q", ref.Text()) } + share, _ := ref.Button("") + if !strings.HasPrefix(share.URL, "https://t.me/share/url?url="+url.QueryEscape(link)) { + t.Fatalf("share button = %+v", share) + } + if !strings.Contains(ref.Params["reply_markup"], `"copy_text":{"text":"`+link+`"}`) { + t.Fatalf("no copy button with the link: %s", ref.Params["reply_markup"]) + } + seq = h.press(alice, alice, ref, "rq") + if qr := h.wait(seq, "sendPhoto", nil); qr.Files["photo"].Size == 0 || !strings.Contains(qr.Text(), link) { + t.Fatalf("QR = %+v", qr.Params) + } // Bob is new and arrives through the link. seq = h.srv.Seq() - h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice)) + h.srv.PushMessage(bob, bob, "/start rf_"+code) h.wait(seq, "sendMessage", textHas("welcome")) - // Alice already knows the bot: a link to herself or from bob does nothing. - h.srv.PushMessage(alice, alice, fmt.Sprintf("/start ref_%d", bob)) + // Alice already knows the bot: a link from bob, or her own, does nothing. + bobCode, _ := h.app.Store.RefCode(context.Background(), bob) + h.srv.PushMessage(alice, alice, "/start rf_"+bobCode) + h.srv.PushMessage(alice, alice, "/start rf_"+code) seq = h.srv.Seq() h.srv.PushMessage(bob, bob, "/credits") menu := h.wait(seq, "sendMessage", textHas("Your balance")) seq = h.press(bob, bob, menu, "by:credits:1000") inv, _ := h.invoice(seq, 1) + // Not paid yet: nothing for alice. + if got := h.balance(alice); got != 0 { + t.Fatalf("inviter balance before payment = %d", got) + } h.pay(inv) h.wait(seq, "editMessageCaption", textHas("Paid.")) @@ -977,7 +1001,7 @@ func TestReferralRewardEndToEnd(t *testing.T) { } seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/referral") - h.wait(seq, "sendMessage", textHas("You invited 1 person so far")) + h.wait(seq, "sendMessage", textHas("Invited: 1 · Bought something: 1\nEarned: 200 sats · Waiting: 0 sats")) u, _ := h.app.Store.GetUser(context.Background(), alice) if u.ReferredBy != 0 { t.Fatalf("an existing user was referred: %+v", u) @@ -985,6 +1009,30 @@ func TestReferralRewardEndToEnd(t *testing.T) { h.booksBalance() } +func TestOldReferralLinksStillWork(t *testing.T) { + h := startMoney(t, nil, nil) + h.askEveryTime(alice) // alice exists + seq := h.srv.Seq() + h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice)) + h.wait(seq, "sendMessage", textHas("welcome")) + if u, _ := h.app.Store.GetUser(context.Background(), bob); u.ReferredBy != alice { + t.Fatalf("bob was not referred by the old link: %+v", u) + } + // A newcomer cannot refer themselves, with either kind of link. + seq = h.srv.Seq() + h.srv.PushMessage(carol, carol, fmt.Sprintf("/start ref_%d", carol)) + h.wait(seq, "sendMessage", textHas("welcome")) + if u, _ := h.app.Store.GetUser(context.Background(), carol); u.ReferredBy != 0 { + t.Fatalf("self-referral stored: %+v", u) + } + // Broken or unknown links do not get in the way of the welcome. + for _, p := range []string{"rf_", "rf_ZZZZZZZZ", "ref_", "ref_abc", "rf_" + strings.Repeat("A", 60)} { + seq = h.srv.Seq() + h.srv.PushMessage(44+int64(len(p)), 44+int64(len(p)), "/start "+p) + h.wait(seq, "sendMessage", textHas("welcome")) + } +} + func TestDonate(t *testing.T) { h := startMoney(t, nil, nil) seq := h.srv.Seq() diff --git a/internal/billing/billing.go b/internal/billing/billing.go index 6f4cb22..b78ee40 100644 --- a/internal/billing/billing.go +++ b/internal/billing/billing.go @@ -497,35 +497,119 @@ func (b *Billing) Settle(ctx context.Context, purchaseID string) (bool, error) { return true, nil } -// rewardReferrer credits the inviter on the invited user's first real -// purchase. The dedupe key allows one reward per invited user, ever. +// rewardReferrer pays the inviter of a user who settled their first +// purchase. Our referral program covers Lightning purchases only: +// purchases paid in Telegram Stars earn affiliates a commission through +// Telegram's own affiliate program, so paying sats for them as well would +// reward the same purchase twice. Donations are not purchases. +// +// The reward is recorded once per invited user (the referral_rewards key) +// and credited through the ledger with a dedupe key. Over the inviter's +// daily cap it is recorded as pending and paid by PayPendingReferrals on +// a later day. func (b *Billing) rewardReferrer(ctx context.Context, tx *db.Store, p *db.Purchase, now int64) error { reward := b.cfg.Prices.ReferralReward - if reward <= 0 || p.Product == ProductDonation { + if reward <= 0 || p.Product == ProductDonation || !countsForReferral(p) { return nil } u, err := tx.GetUser(ctx, p.UserID) if errors.Is(err, db.ErrNotFound) { return nil } - if err != nil || u.ReferredBy == 0 { + if err != nil || u.ReferredBy == 0 || u.ReferredBy == u.ID { return err } - n, err := tx.CountPaidPurchases(ctx, p.UserID) + n, err := tx.CountReferralPurchases(ctx, p.UserID) if err != nil || n != 1 { + return err // not the first one + } + day := utcDay(time.UnixMilli(now)) + r := &db.ReferralReward{ + InviteeID: p.UserID, ReferrerID: u.ReferredBy, PurchaseID: p.ID, Amount: reward, + Status: db.RewardPending, CreatedAt: now, + } + ok, err := b.underCap(ctx, tx, u.ReferredBy, day, reward) + if err != nil { return err } - w, err := tx.EnsureWallet(ctx, db.OwnerUser, u.ReferredBy) + if ok { + r.Status, r.PaidDay, r.PaidAt = db.RewardPaid, day, now + } + added, err := tx.AddReferralReward(ctx, r) + if err != nil || !added || r.Status != db.RewardPaid { + return err + } + return b.creditReward(ctx, tx, r, now) +} + +// countsForReferral reports whether a purchase was paid in a way our +// referral program rewards: Lightning. +func countsForReferral(p *db.Purchase) bool { return true } + +// 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) { + limit := b.cfg.ReferralDailyCap + if limit <= 0 { + return true, nil + } + paid, err := tx.RewardsPaidOn(ctx, referrer, day) + return paid+amount <= limit, err +} + +func (b *Billing) creditReward(ctx context.Context, tx *db.Store, r *db.ReferralReward, now int64) error { + w, err := tx.EnsureWallet(ctx, db.OwnerUser, r.ReferrerID) if err != nil { return err } _, err = tx.AddLedger(ctx, &db.LedgerEntry{ - WalletID: w.ID, Kind: db.LedgerCredit, Amount: reward, Reason: "referral", - Ref: fmt.Sprint(p.UserID), DedupeKey: fmt.Sprintf("referral:%d", p.UserID), CreatedAt: now, + WalletID: w.ID, Kind: db.LedgerCredit, Amount: r.Amount, Reason: "referral", + Ref: fmt.Sprint(r.InviteeID), DedupeKey: fmt.Sprintf("referral:%d", r.InviteeID), CreatedAt: now, }) return err } +// PayPendingReferrals pays rewards that waited for their inviter's daily +// cap, as far as today's cap allows, oldest first. It returns how many it +// paid. Each one moves from pending to paid and is credited in one +// transaction, so running it twice pays nothing twice. +func (b *Billing) PayPendingReferrals(ctx context.Context) (int, error) { + list, err := b.store.PendingRewards(ctx, 200) + if err != nil { + return 0, err + } + paid := 0 + for _, r := range list { + r := r + err := b.store.InTx(ctx, func(tx *db.Store) error { + now := b.nowMilli() + day := utcDay(time.UnixMilli(now)) + ok, err := b.underCap(ctx, tx, r.ReferrerID, day, r.Amount) + if err != nil || !ok { + return err + } + won, err := tx.MarkRewardPaid(ctx, r.InviteeID, day, now) + if err != nil || !won { + return err + } + if err := b.creditReward(ctx, tx, &r, now); err != nil { + return err + } + paid++ + return nil + }) + if err != nil && !errors.Is(err, db.ErrDuplicate) { + return paid, err + } + } + return paid, nil +} + +// utcDay is a day as YYYYMMDD in UTC. +func utcDay(t time.Time) int { + y, m, d := t.UTC().Date() + return y*10000 + int(m)*100 + d +} + // Cancel closes a pending purchase on the payer's request. If the invoice // is paid anyway, the payment is still credited when it is detected. func (b *Billing) Cancel(ctx context.Context, purchaseID string, userID int64) (*db.Purchase, error) { @@ -641,6 +725,13 @@ func (b *Billing) Run(ctx context.Context) { if _, err := b.Reconcile(ctx, window); err != nil && ctx.Err() == nil { b.log.Warn("payment poll failed", "err", err) } + if tick%12 == 0 { + if n, err := b.PayPendingReferrals(ctx); err != nil && ctx.Err() == nil { + b.log.Warn("paying pending referral rewards failed", "err", err) + } else if n > 0 { + b.log.Info("pending referral rewards paid", "count", n) + } + } } } } diff --git a/internal/billing/billing_test.go b/internal/billing/billing_test.go index ff8ce4a..c727630 100644 --- a/internal/billing/billing_test.go +++ b/internal/billing/billing_test.go @@ -755,3 +755,81 @@ func TestGrantPassAndState(t *testing.T) { t.Fatalf("group wallet = %+v, %v", g, err) } } + +func TestReferralRewardWaitsForSettlementAndTheDailyCap(t *testing.T) { + r := newRig(t) + r.cfg.ReferralDailyCap = 300 + r.b = r.newBilling() + ctx := context.Background() + const inviter = int64(600) + invitees := []int64{601, 602, 603} + for _, id := range append([]int64{inviter}, invitees...) { + if _, err := r.store.UpsertUser(ctx, id, "", "U", "en"); err != nil { + t.Fatal(err) + } + } + for _, id := range invitees { + if ok, err := r.store.SetReferrer(ctx, id, inviter); err != nil || !ok { + t.Fatalf("SetReferrer: %v %v", ok, err) + } + } + stats := func() db.ReferralStats { + st, err := r.store.ReferralStatsFor(ctx, inviter) + if err != nil { + t.Fatal(err) + } + return st + } + + // An invoice that is created but not paid earns nothing. + unpaid := r.buy(invitees[0], billing.ProductPassDay, 0) + if r.balance(inviter) != 0 || stats().Converted != 0 { + t.Fatal("a reward before the payment settled") + } + // Paid: the reward arrives once, however often the webhook comes. + if err := r.ln.Pay(unpaid.PaymentHash); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + if err := r.b.HandleWebhook(ctx, unpaid.PaymentHash); err != nil { + t.Fatal(err) + } + } + if got := r.balance(inviter); got != 200 { + t.Fatalf("balance after one settled purchase = %d, want 200", got) + } + + // The second reward of the day would pass the 300 sat cap: it waits. + _ = r.ln.Pay(r.buy(invitees[1], billing.ProductCredits, 1000).PaymentHash) + _ = r.ln.Pay(r.buy(invitees[2], billing.ProductCredits, 1000).PaymentHash) + if got := r.balance(inviter); got != 200 { + t.Fatalf("balance over the cap = %d, want 200", got) + } + if st := stats(); st.Invited != 3 || st.Converted != 3 || st.Earned != 200 || st.Pending != 400 { + t.Fatalf("stats = %+v", st) + } + if n, err := r.b.PayPendingReferrals(ctx); err != nil || n != 0 { + t.Fatalf("paid %d pending rewards on the same day (%v)", n, err) + } + // The next day one more fits under the cap, the day after the last. + r.advance(24 * time.Hour) + if n, _ := r.b.PayPendingReferrals(ctx); n != 1 { + t.Fatalf("paid %d the next day, want 1", n) + } + if n, _ := r.b.PayPendingReferrals(ctx); n != 0 { + t.Fatalf("paid %d more on the same day", n) + } + r.advance(24 * time.Hour) + if n, _ := r.b.PayPendingReferrals(ctx); n != 1 { + t.Fatalf("paid %d on the third day, want 1", n) + } + if st := stats(); st.Earned != 600 || st.Pending != 0 || r.balance(inviter) != 600 { + t.Fatalf("at the end: stats %+v, balance %d", st, r.balance(inviter)) + } + // Later purchases of the same people earn nothing more. + _ = r.ln.Pay(r.buy(invitees[0], billing.ProductCredits, 1000).PaymentHash) + if r.balance(inviter) != 600 { + t.Fatal("a second purchase was rewarded") + } + r.booksBalance() +} diff --git a/internal/bot/commands.go b/internal/bot/commands.go index bc0c272..183f679 100644 --- a/internal/bot/commands.go +++ b/internal/bot/commands.go @@ -3,7 +3,6 @@ package bot import ( "context" "errors" - "strconv" "strings" "time" @@ -302,13 +301,8 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { case payload == "buy": b.showBuy(ctx, m.Chat.ID, act) return - case strings.HasPrefix(payload, "ref_"): - // Only somebody who is new to the bot can be referred. - if referrer, err := strconv.ParseInt(strings.TrimPrefix(payload, "ref_"), 10, 64); err == nil && act.user.IsNew { - if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil { - b.log.Error("set referrer", "user_id", act.user.ID, "err", err) - } - } + default: + b.applyReferral(ctx, act, payload) } // Somebody new picks a language under the welcome. It starts in the // language of their Telegram app, which is usually right. @@ -528,6 +522,8 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { b.cbRetryLookup(ctx, q, act, id) case cbUpgrade: b.cbShowUpgrade(ctx, q, act) + case cbReferralQR: + b.cbSendReferralQR(ctx, q, act) case cbPersonal: b.cbPersonalSetting(ctx, q, act, id, arg) case cbSkipQueue: diff --git a/internal/bot/money.go b/internal/bot/money.go index 73cbbfe..b61f0b9 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -1,8 +1,10 @@ package bot import ( + "bytes" "context" "errors" + "net/url" "strconv" "strings" "time" @@ -215,26 +217,136 @@ func (b *Bot) cmdReferral(ctx context.Context, m *telego.Message, act actor) { if !b.privateOnly(ctx, m, act) { return } - text, err := b.referralText(ctx, act) + text, kb, err := b.referralView(ctx, act, false) if err != nil { b.internalError(ctx, m.Chat.ID, act, err) return } - _, _ = b.send(ctx, m.Chat.ID, 0, text, nil) + _, _ = b.send(ctx, m.Chat.ID, 0, text, kb) } -// referralText explains the referral program with the user's own link. -func (b *Bot) referralText(ctx context.Context, act actor) (string, error) { - n, err := b.store.CountReferrals(ctx, act.user.ID) +// referralPrefix starts the /start payload of a referral link: +// rf_. Old links carry ref_; they keep working but +// are never shown again. +const ( + referralPrefix = "rf_" + legacyReferralPrefix = "ref_" +) + +// ReferralLink is a user's invite link. The bot's username comes from +// getMe, the code is random. +func (b *Bot) ReferralLink(ctx context.Context, userID int64) (string, error) { + code, err := b.store.RefCode(ctx, userID) if err != nil { return "", err } - link := "https://t.me/" + b.username + "?start=ref_" + strconv.FormatInt(act.user.ID, 10) - return b.tr.HTML(act.lang, "referral.text", i18n.Args{ - "Link": link, - "Reward": b.tr.Sats(act.lang, b.cfg.Prices.ReferralReward), - "Count": n, - }), nil + return "https://t.me/" + b.username + "?start=" + referralPrefix + code, nil +} + +// ReferralStats sums up a user's referrals. +func (b *Bot) ReferralStats(ctx context.Context, userID int64) (db.ReferralStats, error) { + return b.store.ReferralStatsFor(ctx, userID) +} + +// ReferralQR is a user's invite link as a QR code PNG. +func (b *Bot) ReferralQR(ctx context.Context, userID int64) ([]byte, error) { + link, err := b.ReferralLink(ctx, userID) + if err != nil { + return nil, err + } + return qrcode.Encode(link, qrcode.Medium, 512) +} + +// shareURL opens Telegram's share sheet with a link and a line of text. +func shareURL(link, text string) string { + return "https://t.me/share/url?url=" + url.QueryEscape(link) + "&text=" + url.QueryEscape(text) +} + +// referralView explains the referral program with the user's own link, +// stats and buttons to share it. back adds a button to the personal +// settings. +func (b *Bot) referralView(ctx context.Context, act actor, back bool) (string, *telego.InlineKeyboardMarkup, error) { + lang := act.lang + link, err := b.ReferralLink(ctx, act.user.ID) + if err != nil { + return "", nil, err + } + st, err := b.store.ReferralStatsFor(ctx, act.user.ID) + if err != nil { + return "", nil, err + } + text := b.tr.HTML(lang, "referral.text", i18n.Args{ + "Link": link, + "Reward": b.tr.Sats(lang, b.cfg.Prices.ReferralReward), + "Invited": b.tr.Number(lang, int64(st.Invited)), + "Converted": b.tr.Number(lang, int64(st.Converted)), + "Earned": b.tr.Sats(lang, st.Earned), + "Pending": b.tr.Sats(lang, st.Pending), + }) + if c := b.cfg.ReferralDailyCap; c > 0 { + text += "\n\n" + b.tr.HTML(lang, "referral.cap", i18n.Args{"Cap": b.tr.Sats(lang, c)}) + } + rows := [][]telego.InlineKeyboardButton{ + { + urlButton(b.tr.T(lang, "btn.share", nil), shareURL(link, b.tr.T(lang, "referral.share_text", nil))), + {Text: b.tr.T(lang, "btn.copy_link", nil), CopyText: &telego.CopyTextButton{Text: link}}, + }, + {button(b.tr.T(lang, "btn.qr", nil), cbReferralQR)}, + } + if back { + rows = append(rows, b.backRow(lang)) + } + return text, keyboard(rows...), nil +} + +// cbReferralQR sends the invite link as a QR code. +const cbReferralQR = "rq" + +func (b *Bot) cbSendReferralQR(ctx context.Context, q *telego.CallbackQuery, act actor) { + png, err := b.ReferralQR(ctx, act.user.ID) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + link, _ := b.ReferralLink(ctx, act.user.ID) + b.answer(ctx, q, "", false) + _, err = b.api.SendPhoto(ctx, &telego.SendPhotoParams{ + ChatID: chatID(act.user.ID), + Photo: telego.InputFile{File: namedReader{Reader: bytes.NewReader(png), name: "invite.png"}}, + Caption: b.tr.HTML(act.lang, "referral.qr_caption", i18n.Args{"Link": link}), + ParseMode: telego.ModeHTML, + }) + if err != nil { + b.log.Warn("send referral QR", "user_id", act.user.ID, "err", err) + } +} + +// applyReferral records who invited a user who arrived through an invite +// link, and reports whether payload was one. Only somebody new to the bot +// can be referred, never by themselves. Old links with the inviter's +// Telegram ID still work. +func (b *Bot) applyReferral(ctx context.Context, act actor, payload string) bool { + var referrer int64 + switch { + case strings.HasPrefix(payload, referralPrefix): + if u, err := b.store.UserByRefCode(ctx, strings.TrimPrefix(payload, referralPrefix)); err == nil { + referrer = u.ID + } + case strings.HasPrefix(payload, legacyReferralPrefix): + id, err := strconv.ParseInt(strings.TrimPrefix(payload, legacyReferralPrefix), 10, 64) + if err != nil { + return false + } + referrer = id + default: + return false + } + if referrer != 0 && referrer != act.user.ID && act.user.IsNew { + if _, err := b.store.SetReferrer(ctx, act.user.ID, referrer); err != nil { + b.log.Error("set referrer", "user_id", act.user.ID, "err", err) + } + } + return true } func (b *Bot) cmdRedeem(ctx context.Context, m *telego.Message, act actor, arg string) { diff --git a/internal/bot/personal.go b/internal/bot/personal.go index ef2038f..0de3edb 100644 --- a/internal/bot/personal.go +++ b/internal/bot/personal.go @@ -190,12 +190,12 @@ func (b *Bot) cbPersonalSetting(ctx context.Context, q *telego.CallbackQuery, ac } case psReferral: b.answer(ctx, q, "", false) - text, err := b.referralText(ctx, act) + text, kb, err := b.referralView(ctx, act, true) if err != nil { - b.log.Error("referral text", "err", err) + b.log.Error("referral view", "err", err) return } - show(text, keyboard(b.backRow(act.lang))) + show(text, kb) return default: b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) diff --git a/internal/config/config.go b/internal/config/config.go index 74a0eac..7760f91 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -103,6 +103,16 @@ type Config struct { MultiLinkMax int `toml:"multi_link_max" env:"MULTI_LINK_MAX"` // CaptionAttribution adds a "via @botname" line to file captions. CaptionAttribution bool `toml:"caption_attribution" env:"CAPTION_ATTRIBUTION"` + + // ReferralRewardSats is credited to an inviter when somebody they + // invited settles a first Lightning purchase. It is the documented name + // of [prices] referral_reward (REFERRAL_REWARD), which still works; when + // both are set this one wins. -1 means not set. + ReferralRewardSats int64 `toml:"referral_reward_sats" env:"REFERRAL_REWARD_SATS"` + // ReferralDailyCap is the most one inviter earns in referral rewards per + // 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"` } // Telegram holds the Bot API settings. @@ -375,6 +385,8 @@ func Default() Config { QueueNoticeThresholdSeconds: 10, MultiLinkMax: 5, CaptionAttribution: true, + ReferralRewardSats: -1, + ReferralDailyCap: 2000, } } @@ -421,6 +433,9 @@ func Load(path string) (Config, error) { } cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/") cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/") + if cfg.ReferralRewardSats >= 0 { + cfg.Prices.ReferralReward = cfg.ReferralRewardSats + } return cfg, cfg.Validate() } @@ -452,6 +467,9 @@ func (c Config) Validate() error { if c.QueueNoticeThresholdSeconds < 0 { errs = append(errs, "QUEUE_NOTICE_THRESHOLD_SECONDS must not be negative") } + if c.ReferralDailyCap < 0 { + errs = append(errs, "REFERRAL_DAILY_CAP must not be negative") + } if c.MultiLinkMax < 1 || c.MultiLinkMax > 20 { errs = append(errs, "MULTI_LINK_MAX must be between 1 and 20") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 68d9a88..fc69421 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -370,3 +370,26 @@ func TestWorkerConfig(t *testing.T) { t.Fatalf("worker env not applied: %+v", w) } } + +func TestReferralRewardNames(t *testing.T) { + t.Setenv("BOT_TOKEN", "x") + t.Setenv("DLBOT_CONFIG", "") + t.Chdir(t.TempDir()) + t.Setenv("REFERRAL_REWARD", "150") + cfg, err := Load("") + if err != nil { + t.Fatal(err) + } + if cfg.Prices.ReferralReward != 150 || cfg.ReferralDailyCap != 2000 { + t.Fatalf("old name: reward %d, cap %d", cfg.Prices.ReferralReward, cfg.ReferralDailyCap) + } + t.Setenv("REFERRAL_REWARD_SATS", "300") + t.Setenv("REFERRAL_DAILY_CAP", "0") + if cfg, err = Load(""); err != nil || cfg.Prices.ReferralReward != 300 || cfg.ReferralDailyCap != 0 { + t.Fatalf("new name: %+v %v", cfg.Prices.ReferralReward, err) + } + t.Setenv("REFERRAL_DAILY_CAP", "-5") + if _, err := Load(""); err == nil { + t.Fatal("a negative cap was accepted") + } +} diff --git a/internal/db/export_test.go b/internal/db/export_test.go new file mode 100644 index 0000000..57076c3 --- /dev/null +++ b/internal/db/export_test.go @@ -0,0 +1,4 @@ +package db + +// RefCodeGen lets tests replace the referral code generator. +var RefCodeGen = &refCodeGen diff --git a/internal/db/migrations/00008_referrals.sql b/internal/db/migrations/00008_referrals.sql new file mode 100644 index 0000000..7dc594d --- /dev/null +++ b/internal/db/migrations/00008_referrals.sql @@ -0,0 +1,33 @@ +-- +goose Up +-- Referral links carry a random code instead of the inviter's Telegram ID. +-- A user gets a code the first time they need one; '' means none yet. +ALTER TABLE users ADD COLUMN ref_code TEXT NOT NULL DEFAULT ''; +CREATE UNIQUE INDEX users_ref_code_idx ON users (ref_code) WHERE ref_code <> ''; + +-- One row per invited user who settled a first Lightning purchase: the +-- reward their inviter earned for it. The primary key makes it one reward +-- per invited user, ever. A reward over the inviter's daily cap waits as +-- 'pending' and is paid (credited through the ledger) on a later day. +CREATE TABLE referral_rewards ( + invitee_id BIGINT PRIMARY KEY, + referrer_id BIGINT NOT NULL, + purchase_id TEXT NOT NULL DEFAULT '', + amount BIGINT NOT NULL, + status TEXT NOT NULL, -- paid or pending + paid_day INTEGER NOT NULL DEFAULT 0, -- YYYYMMDD (UTC) it was paid on + created_at BIGINT NOT NULL, + paid_at BIGINT NOT NULL DEFAULT 0 +); +CREATE INDEX referral_rewards_referrer_idx ON referral_rewards (referrer_id, status, paid_day); +CREATE INDEX referral_rewards_pending_idx ON referral_rewards (status, created_at); + +-- Rewards paid before this table existed are in the ledger. +INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at) +SELECT CAST(l.ref AS BIGINT), w.owner_id, '', l.amount, 'paid', 0, l.created_at, l.created_at +FROM ledger l JOIN wallets w ON w.id = l.wallet_id +WHERE l.reason = 'referral' AND w.owner_type = 'user' AND l.ref <> ''; + +-- +goose Down +DROP TABLE referral_rewards; +DROP INDEX users_ref_code_idx; +ALTER TABLE users DROP COLUMN ref_code; diff --git a/internal/db/money.go b/internal/db/money.go index eadf00b..f9cc5ce 100644 --- a/internal/db/money.go +++ b/internal/db/money.go @@ -334,6 +334,12 @@ func (s *Store) UnfulfilledPaidPurchases(ctx context.Context, limit int) ([]*Pur } // 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. +func (s *Store) CountReferralPurchases(ctx context.Context, userID int64) (int, error) { + return s.CountPaidPurchases(ctx, userID) +} + 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' diff --git a/internal/db/referrals.go b/internal/db/referrals.go new file mode 100644 index 0000000..7293cda --- /dev/null +++ b/internal/db/referrals.go @@ -0,0 +1,154 @@ +package db + +import ( + "context" + "crypto/rand" + "encoding/base32" + "errors" + "strings" +) + +// RefCodeLength is the length of a referral code. +const RefCodeLength = 8 + +// NewRefCode makes a random referral code: 8 characters of RFC 4648 +// base32 (A to Z, 2 to 7), 40 random bits. +func NewRefCode() string { + var b [5]byte + if _, err := rand.Read(b[:]); err != nil { + panic(err) // the system has no randomness; nothing is safe then + } + return base32.StdEncoding.EncodeToString(b[:]) +} + +// ValidRefCode reports whether s has the shape of a referral code. +func ValidRefCode(s string) bool { + if len(s) != RefCodeLength { + return false + } + for _, r := range s { + if !(r >= 'A' && r <= 'Z' || r >= '2' && r <= '7') { + return false + } + } + return true +} + +// refCodeGen makes codes; tests replace it to force collisions. +var refCodeGen = NewRefCode + +// RefCode returns the user's referral code, creating it on first use. A +// collision with another user's code, which is rare with 40 bits, is +// retried with a new code. +func (s *Store) RefCode(ctx context.Context, userID int64) (string, error) { + for attempt := 0; attempt < 8; attempt++ { + var code string + if err := s.row(ctx, `SELECT ref_code FROM users WHERE id = ?`, userID).Scan(&code); err != nil { + return "", notFound(err) + } + if code != "" { + return code, nil + } + _, err := s.exec(ctx, `UPDATE users SET ref_code = ? WHERE id = ? AND ref_code = ''`, refCodeGen(), userID) + if err != nil && !isUniqueViolation(err) { + return "", err + } + // Either it was stored, or another request stored one first, or the + // code was taken: read again. + } + return "", errors.New("db: no free referral code") +} + +// UserByRefCode finds the owner of a referral code. Codes are compared +// in upper case, since some apps change the case of links. +func (s *Store) UserByRefCode(ctx context.Context, code string) (*User, error) { + code = strings.ToUpper(code) + if !ValidRefCode(code) { + return nil, ErrNotFound + } + return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE ref_code = ?`, code)) +} + +// Reward statuses. +const ( + RewardPaid = "paid" + RewardPending = "pending" +) + +// ReferralReward is the reward an inviter earned for one invited user. +type ReferralReward struct { + InviteeID int64 + ReferrerID int64 + PurchaseID string + Amount int64 + Status string + PaidDay int + CreatedAt int64 + PaidAt int64 +} + +// AddReferralReward records a reward. It reports false when the invited +// user already earned their inviter a reward. +func (s *Store) AddReferralReward(ctx context.Context, r *ReferralReward) (bool, error) { + n, err := s.exec(ctx, `INSERT INTO referral_rewards (invitee_id, referrer_id, purchase_id, amount, status, + paid_day, created_at, paid_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (invitee_id) DO NOTHING`, + r.InviteeID, r.ReferrerID, r.PurchaseID, r.Amount, r.Status, r.PaidDay, r.CreatedAt, r.PaidAt) + return n == 1, err +} + +// MarkRewardPaid moves a pending reward to paid. It reports false when it +// was not pending, so a reward is paid once. +func (s *Store) MarkRewardPaid(ctx context.Context, inviteeID int64, day int, now int64) (bool, error) { + n, err := s.exec(ctx, `UPDATE referral_rewards SET status = 'paid', paid_day = ?, paid_at = ? + WHERE invitee_id = ? AND status = 'pending'`, day, now, inviteeID) + return n == 1, err +} + +// RewardsPaidOn sums what an inviter was paid in rewards on a day. +func (s *Store) RewardsPaidOn(ctx context.Context, referrerID int64, day int) (int64, error) { + var n int64 + err := s.row(ctx, `SELECT COALESCE(SUM(amount), 0) FROM referral_rewards + WHERE referrer_id = ? AND status = 'paid' AND paid_day = ?`, referrerID, day).Scan(&n) + return n, err +} + +// PendingRewards lists rewards waiting for their inviter's daily cap, +// oldest first. +func (s *Store) PendingRewards(ctx context.Context, limit int) ([]ReferralReward, error) { + rows, err := s.rows(ctx, `SELECT invitee_id, referrer_id, purchase_id, amount, status, paid_day, created_at, paid_at + FROM referral_rewards WHERE status = 'pending' ORDER BY created_at, invitee_id LIMIT ?`, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []ReferralReward + for rows.Next() { + var r ReferralReward + if err := rows.Scan(&r.InviteeID, &r.ReferrerID, &r.PurchaseID, &r.Amount, &r.Status, &r.PaidDay, &r.CreatedAt, &r.PaidAt); err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + +// ReferralStats is what /referral shows an inviter. +type ReferralStats struct { + Invited int // users who joined through their link + Converted int // of those, users who settled a first purchase + Earned int64 // sats paid out + Pending int64 // sats earned, waiting for the daily cap +} + +// ReferralStatsFor sums up an inviter's referrals. +func (s *Store) ReferralStatsFor(ctx context.Context, referrerID int64) (ReferralStats, error) { + var st ReferralStats + if err := s.row(ctx, `SELECT COUNT(*) FROM users WHERE referred_by = ?`, referrerID).Scan(&st.Invited); err != nil { + return st, err + } + err := s.row(ctx, `SELECT COUNT(*), + COALESCE(SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) + FROM referral_rewards WHERE referrer_id = ?`, referrerID).Scan(&st.Converted, &st.Earned, &st.Pending) + return st, err +} diff --git a/internal/db/referrals_test.go b/internal/db/referrals_test.go new file mode 100644 index 0000000..59992cf --- /dev/null +++ b/internal/db/referrals_test.go @@ -0,0 +1,80 @@ +package db_test + +import ( + "context" + "testing" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/db/dbtest" +) + +func TestRefCodesAreShortRandomAndUnique(t *testing.T) { + store := dbtest.Open(t).Store() + ctx := context.Background() + seen := map[string]bool{} + for id := int64(1); id <= 300; id++ { + if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil { + t.Fatal(err) + } + code, err := store.RefCode(ctx, id) + if err != nil { + t.Fatal(err) + } + if !db.ValidRefCode(code) { + t.Fatalf("code %q is not 8 characters of base32", code) + } + if seen[code] { + t.Fatalf("code %q given twice", code) + } + seen[code] = true + // The code is stable once made. + if again, _ := store.RefCode(ctx, id); again != code { + t.Fatalf("code changed from %q to %q", code, again) + } + owner, err := store.UserByRefCode(ctx, code) + if err != nil || owner.ID != id { + t.Fatalf("UserByRefCode(%q) = %+v, %v", code, owner, err) + } + } + // Lower case works (some apps change links), garbage does not. + for code := range seen { + lower := []byte(code) + for i, c := range lower { + if c >= 'A' && c <= 'Z' { + lower[i] = c + 32 + } + } + if _, err := store.UserByRefCode(ctx, string(lower)); err != nil { + t.Fatalf("lower case code: %v", err) + } + break + } + for _, bad := range []string{"", "ABC", "ABCDEFG1", "ABCDEFGHI", "12345678", "' OR 1=1"} { + if _, err := store.UserByRefCode(ctx, bad); err != db.ErrNotFound { + t.Errorf("UserByRefCode(%q) = %v, want not found", bad, err) + } + } +} + +func TestRefCodeCollisionIsRetried(t *testing.T) { + store := dbtest.Open(t).Store() + ctx := context.Background() + for _, id := range []int64{1, 2} { + if _, err := store.UpsertUser(ctx, id, "", "U", "en"); err != nil { + t.Fatal(err) + } + } + codes := []string{"AAAAAAAA", "AAAAAAAA", "BBBBBBBB"} + restore := *db.RefCodeGen + *db.RefCodeGen = func() string { c := codes[0]; codes = codes[1:]; return c } + defer func() { *db.RefCodeGen = restore }() + first, err := store.RefCode(ctx, 1) + if err != nil || first != "AAAAAAAA" { + t.Fatalf("first = %q, %v", first, err) + } + // The second user draws the same code first, then a free one. + second, err := store.RefCode(ctx, 2) + if err != nil || second != "BBBBBBBB" { + t.Fatalf("second = %q, %v", second, err) + } +} diff --git a/locales/en.toml b/locales/en.toml index 27906ea..62e11a2 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -156,6 +156,9 @@ pick = "Pick a format:" cancelled = "Cancelled." [btn] +qr = "QR code" +copy_link = "Copy link" +share = "Share" maybe_over = "{{.Label}} ⚠" remove_from_history = "Remove from history" clear_yes = "Yes, clear it" @@ -357,24 +360,6 @@ Downloads at the same time: {{.ActiveJobs}} Downloads per day: {{.DailyDownloads}} Volume per day: {{.DailyVolume}}""" -[referral.text] -one = """ -Invite friends - -Share your link. When somebody you invited makes a first purchase, you get {{.Reward}}. - -{{.Link}} - -You invited {{.Count}} person so far.""" -other = """ -Invite friends - -Share your link. When somebody you invited makes a first purchase, you get {{.Reward}}. - -{{.Link}} - -You invited {{.Count}} people so far.""" - [redeem] usage = "Send the code after the command.\nExample: /redeem NR-ABCD-EFGH-JKMN" invalid = "That code is not valid." @@ -857,6 +842,10 @@ one = "Usage, last day" other = "Usage, last {{.Count}} days" [app.me] +qr = "QR code" +pending = "Waiting for the daily cap" +earned = "Earned" +converted = "Bought something" downloads_title = "Downloads" quality_note = "With a default set, a link starts right away instead of asking for a format." audio_only = "Audio only" @@ -864,7 +853,7 @@ audio_only_hint = "Always fetch the sound as MP3." language_title = "Language" language = "Language" referral_title = "Invite friends" -referral_note = "When somebody you invited makes a first purchase, you get {{.Reward}}." +referral_note = "When somebody you invited pays for a first purchase in sats (Lightning), you get {{.Reward}} in credits." copy_link = "Copy link" share = "Share" invited = "Invited so far" @@ -912,3 +901,19 @@ other = "{{.Count}} days ago" [history.clear_confirm] one = "Remove {{.Count}} download from your history? Files already in this chat stay where they are." other = "Remove all {{.Count}} downloads from your history? Files already in this chat stay where they are." + +[referral] +qr_caption = """ +Your invite link as a QR code: +{{.Link}}""" +share_text = "Download videos and music from a link, right in Telegram." +cap = "You earn at most {{.Cap}} a day. Rewards above that wait for the next day." +text = """ +Invite friends + +Share your link. When somebody you invited pays for a first purchase in sats (Lightning), you get {{.Reward}} in credits. + +{{.Link}} + +Invited: {{.Invited}} · Bought something: {{.Converted}} +Earned: {{.Earned}} · Waiting: {{.Pending}}""" diff --git a/locales/es.toml b/locales/es.toml index 7a7497b..2469eeb 100644 --- a/locales/es.toml +++ b/locales/es.toml @@ -147,6 +147,9 @@ pick = "Elige un formato:" cancelled = "Cancelado." [btn] +qr = "Código QR" +copy_link = "Copiar enlace" +share = "Compartir" maybe_over = "{{.Label}} ⚠" remove_from_history = "Quitar del historial" clear_yes = "Sí, borrarlo" @@ -343,24 +346,6 @@ Descargas al mismo tiempo: {{.ActiveJobs}} Descargas por día: {{.DailyDownloads}} Volumen por día: {{.DailyVolume}}""" -[referral.text] -one = """ -Invita a tus amigos - -Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}. - -{{.Link}} - -Hasta ahora invitaste a {{.Count}} persona.""" -other = """ -Invita a tus amigos - -Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}. - -{{.Link}} - -Hasta ahora invitaste a {{.Count}} personas.""" - [redeem] usage = "Envía el código después del comando.\nEjemplo: /redeem NR-ABCD-EFGH-JKMN" invalid = "Ese código no es válido." @@ -832,6 +817,10 @@ one = "Uso, último día" other = "Uso, últimos {{.Count}} días" [app.me] +qr = "Código QR" +pending = "En espera del tope diario" +earned = "Ganado" +converted = "Compraron algo" downloads_title = "Descargas" quality_note = "Con un formato por defecto, un enlace empieza enseguida en vez de preguntar." audio_only = "Solo audio" @@ -839,7 +828,7 @@ audio_only_hint = "Bajar siempre el sonido en MP3." language_title = "Idioma" language = "Idioma" referral_title = "Invita a tus amigos" -referral_note = "Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}." +referral_note = "Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes {{.Reward}} en créditos." copy_link = "Copiar enlace" share = "Compartir" invited = "Invitados hasta ahora" @@ -885,3 +874,19 @@ other = "hace {{.Count}} días" [history.clear_confirm] one = "Quitar {{.Count}} descarga de tu historial? Los archivos que ya están en este chat se quedan donde están." other = "Quitar las {{.Count}} descargas de tu historial? Los archivos que ya están en este chat se quedan donde están." + +[referral] +qr_caption = """ +Tu enlace de invitación como código QR: +{{.Link}}""" +share_text = "Descarga videos y música desde un enlace, directo en Telegram." +cap = "Ganas como máximo {{.Cap}} al día. Lo que pase de eso espera al día siguiente." +text = """ +Invita a tus amigos + +Comparte tu enlace. Cuando alguien que invitaste pague una primera compra en sats (Lightning), recibes {{.Reward}} en créditos. + +{{.Link}} + +Invitados: {{.Invited}} · Compraron algo: {{.Converted}} +Ganado: {{.Earned}} · En espera: {{.Pending}}""" diff --git a/locales/nl.toml b/locales/nl.toml index 56ee180..68d3ca7 100644 --- a/locales/nl.toml +++ b/locales/nl.toml @@ -146,6 +146,9 @@ pick = "Kies een formaat:" cancelled = "Geannuleerd." [btn] +qr = "QR-code" +copy_link = "Link kopiëren" +share = "Delen" maybe_over = "{{.Label}} ⚠" remove_from_history = "Uit geschiedenis halen" clear_yes = "Ja, wissen" @@ -342,24 +345,6 @@ Downloads tegelijk: {{.ActiveJobs}} Downloads per dag: {{.DailyDownloads}} Volume per dag: {{.DailyVolume}}""" -[referral.text] -one = """ -Nodig vrienden uit - -Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}. - -{{.Link}} - -Je hebt tot nu toe {{.Count}} persoon uitgenodigd.""" -other = """ -Nodig vrienden uit - -Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}. - -{{.Link}} - -Je hebt tot nu toe {{.Count}} mensen uitgenodigd.""" - [redeem] usage = "Stuur de code achter het commando.\nVoorbeeld: /redeem NR-ABCD-EFGH-JKMN" invalid = "Die code is niet geldig." @@ -831,6 +816,10 @@ one = "Gebruik, afgelopen dag" other = "Gebruik, afgelopen {{.Count}} dagen" [app.me] +qr = "QR-code" +pending = "Wacht op de daglimiet" +earned = "Verdiend" +converted = "Iets gekocht" downloads_title = "Downloads" quality_note = "Met een standaardformaat start een link meteen in plaats van te vragen." audio_only = "Alleen audio" @@ -838,7 +827,7 @@ audio_only_hint = "Altijd het geluid als MP3 ophalen." language_title = "Taal" language = "Taal" referral_title = "Nodig vrienden uit" -referral_note = "Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}." +referral_note = "Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij {{.Reward}} aan tegoed." copy_link = "Link kopiëren" share = "Delen" invited = "Tot nu toe uitgenodigd" @@ -884,3 +873,19 @@ other = "{{.Count}} dagen geleden" [history.clear_confirm] one = "{{.Count}} download uit je geschiedenis halen? Bestanden die al in deze chat staan blijven staan." other = "Alle {{.Count}} downloads uit je geschiedenis halen? Bestanden die al in deze chat staan blijven staan." + +[referral] +qr_caption = """ +Je uitnodigingslink als QR-code: +{{.Link}}""" +share_text = "Download video's en muziek via een link, gewoon in Telegram." +cap = "Je verdient maximaal {{.Cap}} per dag. Wat daarboven komt, wacht tot de volgende dag." +text = """ +Nodig vrienden uit + +Deel je link. Als iemand die je uitnodigde een eerste aankoop in sats (Lightning) betaalt, krijg jij {{.Reward}} aan tegoed. + +{{.Link}} + +Uitgenodigd: {{.Invited}} · Iets gekocht: {{.Converted}} +Verdiend: {{.Earned}} · Wacht nog: {{.Pending}}""" diff --git a/web/miniapp/dist/assets/app.js b/web/miniapp/dist/assets/app.js index e320d09..1585624 100644 --- a/web/miniapp/dist/assets/app.js +++ b/web/miniapp/dist/assets/app.js @@ -6,4 +6,4 @@ var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports) `+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` 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)),children:x(`app.me.share`)})})]})]}),(0,C.jsx)(T,{title:x(`app.me.invited`),after:x(`app.me.invited_count`,{Count:e.referral_count})})]}),(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 +`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||yn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&yn(e,``+r);else return;break;case`className`:rn(e,`class`,r);break;case`tabIndex`:rn(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:rn(e,n,r);break;case`style`:Sn(e,r,a);return;case`data`:if(t!==`object`){rn(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)||r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=En(r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=En(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=Dn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=En(r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),nn(e,`popover`,r);break;case`xlinkActuate`:an(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:an(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:an(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:an(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:an(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:an(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:an(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:an(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:an(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:nn(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2s)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 diff --git a/web/miniapp/dist/assets/index.css b/web/miniapp/dist/assets/index.css index 08620d2..9b29b97 100644 --- a/web/miniapp/dist/assets/index.css +++ b/web/miniapp/dist/assets/index.css @@ -1 +1 @@ -:root{--bg:var(--tg-theme-secondary-bg-color,#efeff4);--card:var(--tg-theme-section-bg-color,var(--tg-theme-bg-color,#fff));--text:var(--tg-theme-text-color,#111);--hint:var(--tg-theme-hint-color,#8a8a8f);--link:var(--tg-theme-link-color,#2481cc);--accent:var(--tg-theme-button-color,#2481cc);--on-accent:var(--tg-theme-button-text-color,#fff);--danger:var(--tg-theme-destructive-text-color,#d93025);--line:var(--tg-theme-section-separator-color,#80808040);--header:var(--tg-theme-section-header-text-color,var(--hint));--bar:var(--tg-theme-bottom-bar-bg-color,var(--card));--ok:#2e9e5b;--radius:12px;--safe-bottom:max(env(safe-area-inset-bottom,0px), var(--tg-safe-area-inset-bottom,0px));--safe-top:var(--tg-content-safe-area-inset-top,0px)}@media (prefers-color-scheme:dark){:root{--bg:var(--tg-theme-secondary-bg-color,#111114);--card:var(--tg-theme-section-bg-color,var(--tg-theme-bg-color,#1c1c1f));--text:var(--tg-theme-text-color,#f2f2f2)}}*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}html,body{background:var(--bg);color:var(--text);overscroll-behavior-y:none;margin:0;font:16px/1.4 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}button,input,select{font:inherit;color:inherit}.app{min-height:100vh;padding:calc(8px + var(--safe-top)) 12px calc(76px + var(--safe-bottom));max-width:640px;margin:0 auto}.section{margin-block-start:0;margin-block-end:16px}.section-title{text-transform:uppercase;letter-spacing:.03em;color:var(--header);justify-content:space-between;align-items:baseline;gap:8px;padding:8px 12px 6px;font-size:13px;display:flex}.section-title button{text-transform:none;letter-spacing:0}.card{background:var(--card);border-radius:var(--radius);overflow:hidden}.pad{padding:12px}.cell{border:0;border-block-end:1px solid var(--line);text-align:start;background:0 0;align-items:center;gap:12px;width:100%;min-height:48px;padding:10px 12px;display:flex}.cell:last-child{border-block-end:0}button.cell{cursor:pointer}button.cell:active{background:var(--line)}.cell-body{flex:1;min-width:0}.cell-title{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.cell-title.wrap{white-space:normal}.cell-sub{color:var(--hint);overflow-wrap:anywhere;font-size:13px}.cell-after{color:var(--hint);flex-shrink:0;align-items:center;gap:8px;display:flex}.chevron{border-block-start:2px solid var(--hint);border-inline-end:2px solid var(--hint);opacity:.6;width:8px;height:8px;transform:rotate(45deg)}[dir=rtl] .chevron{transform:rotate(-135deg)}.check{color:var(--accent);font-weight:700}.hint{color:var(--hint);font-size:13px}.note{color:var(--hint);padding:6px 12px 0;font-size:13px}.big{font-size:28px;font-weight:700;line-height:1.15}.error{color:var(--danger)}.center{text-align:center}.empty{text-align:center;color:var(--hint);padding:28px 16px}.mono{overflow-wrap:anywhere;direction:ltr;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.btn{background:var(--accent);min-height:44px;color:var(--on-accent);cursor:pointer;border:0;border-radius:10px;justify-content:center;align-items:center;gap:6px;padding:8px 16px;font-weight:600;display:inline-flex}.btn.wide{width:100%}.btn.small{min-height:32px;padding:4px 12px;font-size:14px}.btn.soft{background:color-mix(in srgb, var(--accent) 14%, transparent);color:var(--accent)}.btn.danger{background:color-mix(in srgb, var(--danger) 12%, transparent);color:var(--danger)}.btn.plain{color:var(--link);background:0 0;min-height:0;padding-inline-start:4px;padding-inline-end:4px;font-weight:500}.btn:disabled{opacity:.5;cursor:default}.btn:active:not(:disabled){filter:brightness(.93)}.row{align-items:center;gap:8px;display:flex}.row.wrap{flex-wrap:wrap}.row>.grow{flex:1;min-width:0}.stack{flex-direction:column;gap:10px;display:flex}.input,.select{border:1px solid var(--line);background:var(--bg);border-radius:10px;outline:none;width:100%;min-height:44px;padding:8px 12px}.input:focus,.select:focus{border-color:var(--accent)}.select:disabled{opacity:.5}.select.compact,.input.compact{width:auto;max-width:55vw;min-height:36px;padding:4px 8px}.input.number{text-align:end;width:110px}.switch{background:var(--line);cursor:pointer;border:0;border-radius:15px;flex-shrink:0;width:50px;height:30px;transition:background .15s;position:relative}.switch:after{content:"";background:#fff;border-radius:50%;width:24px;height:24px;position:absolute;top:3px;box-shadow:0 1px 3px #0000004d}.switch:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{transition:left .15s;left:3px}.switch:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{transition:left .15s;left:3px}.switch:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{transition:right .15s;right:3px}.switch:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{transition:right .15s;right:3px}.switch[aria-checked=true]{background:var(--accent)}.switch[aria-checked=true]:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{left:23px}.switch[aria-checked=true]:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{left:23px}.switch[aria-checked=true]:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{right:23px}.switch[aria-checked=true]:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{right:23px}.segmented{background:var(--line);border-radius:10px;margin-block-end:12px;padding:3px;display:flex}.segmented button{cursor:pointer;background:0 0;border:0;border-radius:8px;flex:1;min-height:34px;padding:4px 6px;font-size:14px}.segmented button[aria-selected=true]{background:var(--card);font-weight:600;box-shadow:0 1px 2px #00000026}.chips{flex-wrap:wrap;gap:6px;display:flex}.chip{background:color-mix(in srgb, var(--accent) 14%, transparent);color:var(--accent);cursor:pointer;border:0;border-radius:14px;align-items:center;gap:6px;padding:4px 10px;font-size:14px;display:inline-flex}.meter{background:var(--line);border-radius:3px;height:6px;margin-block-start:6px;margin-block-end:2px;overflow:hidden}.meter>div{background:var(--accent);border-radius:3px;height:100%;transition:width .4s}.meter.busy>div{animation:1.2s ease-in-out infinite alternate slide;width:35%!important}@keyframes slide{0%{margin-inline-start:0}to{margin-inline-start:65%}}.spinner{border:3px solid var(--line);border-block-start-color:var(--accent);border-radius:50%;width:22px;height:22px;margin:24px auto;animation:.8s linear infinite spin}.btn .spinner{border-width:2px;border-color:color-mix(in srgb, currentColor 30%, transparent);border-block-start-color:currentColor;width:16px;height:16px;margin:0}@keyframes spin{to{transform:rotate(360deg)}}.stats{grid-template-columns:1fr 1fr;gap:8px;display:grid}.stat{border-radius:var(--radius);background:var(--card);padding:12px}.stat .value{font-size:20px;font-weight:700}.steps{gap:6px;margin:4px 0 14px;display:flex}.steps span{background:var(--line);border-radius:2px;flex:1;height:4px}.steps span.on{background:var(--accent)}.qr{width:min(260px,70vw);height:auto;image-rendering:pixelated;background:#fff;border-radius:12px;margin:8px auto;padding:8px;display:block}.paid-mark{background:var(--ok);color:#fff;text-align:center;border-radius:50%;width:72px;height:72px;margin:12px auto;font-size:40px;line-height:72px}.table{border-collapse:collapse;width:100%;font-size:14px}.table th,.table td{border-block-end:1px solid var(--line);text-align:end;white-space:nowrap;padding:10px 12px}.table th{color:var(--hint);font-size:12px;font-weight:500}.table th:first-child,.table td:first-child{text-align:start;white-space:normal;overflow-wrap:anywhere}.table tr:last-child td{border-block-end:0}.tabs{z-index:10;background:var(--bar);border-block-start:1px solid var(--line);justify-content:center;padding-block-end:var(--safe-bottom);display:flex;position:fixed;bottom:0;left:0;right:0}.tabs button{max-width:128px;min-height:56px;color:var(--hint);cursor:pointer;background:0 0;border:0;flex:1;padding:6px 2px 4px;font-size:11px;position:relative}.tabs button[aria-current=page]{color:var(--accent)}.tabs svg{width:24px;height:24px;margin:0 auto 2px;display:block}.badge{background:var(--accent);min-width:18px;color:var(--on-accent);border-radius:9px;padding:0 5px;font-size:11px;line-height:18px;position:absolute;top:4px}.badge:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))){left:calc(50% + 6px)}.badge:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))){left:calc(50% + 6px)}.badge:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)){right:calc(50% + 6px)}.badge:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)){right:calc(50% + 6px)}.sheet-back{z-index:20;background:#00000073;justify-content:center;align-items:flex-end;display:flex;position:fixed;top:0;bottom:0;left:0;right:0}.sheet{width:100%;max-width:640px;max-height:92vh;padding:16px 16px calc(16px + var(--safe-bottom));background:var(--card);border-radius:16px 16px 0 0;overflow-y:auto}.toast{z-index:30;color:#fff;text-align:center;background:#1e1e20f0;border-radius:12px;max-width:616px;margin:0 auto;padding:12px 14px;font-size:14px;position:fixed;bottom:calc(72px + var(--safe-bottom));left:12px;right:12px}.toast.bad{background:var(--danger)} +:root{--bg:var(--tg-theme-secondary-bg-color,#efeff4);--card:var(--tg-theme-section-bg-color,var(--tg-theme-bg-color,#fff));--text:var(--tg-theme-text-color,#111);--hint:var(--tg-theme-hint-color,#8a8a8f);--link:var(--tg-theme-link-color,#2481cc);--accent:var(--tg-theme-button-color,#2481cc);--on-accent:var(--tg-theme-button-text-color,#fff);--danger:var(--tg-theme-destructive-text-color,#d93025);--line:var(--tg-theme-section-separator-color,#80808040);--header:var(--tg-theme-section-header-text-color,var(--hint));--bar:var(--tg-theme-bottom-bar-bg-color,var(--card));--ok:#2e9e5b;--radius:12px;--safe-bottom:max(env(safe-area-inset-bottom,0px), var(--tg-safe-area-inset-bottom,0px));--safe-top:var(--tg-content-safe-area-inset-top,0px)}@media (prefers-color-scheme:dark){:root{--bg:var(--tg-theme-secondary-bg-color,#111114);--card:var(--tg-theme-section-bg-color,var(--tg-theme-bg-color,#1c1c1f));--text:var(--tg-theme-text-color,#f2f2f2)}}*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}html,body{background:var(--bg);color:var(--text);overscroll-behavior-y:none;margin:0;font:16px/1.4 -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,sans-serif}button,input,select{font:inherit;color:inherit}.app{min-height:100vh;padding:calc(8px + var(--safe-top)) 12px calc(76px + var(--safe-bottom));max-width:640px;margin:0 auto}.section{margin-block-start:0;margin-block-end:16px}.section-title{text-transform:uppercase;letter-spacing:.03em;color:var(--header);justify-content:space-between;align-items:baseline;gap:8px;padding:8px 12px 6px;font-size:13px;display:flex}.section-title button{text-transform:none;letter-spacing:0}.card{background:var(--card);border-radius:var(--radius);overflow:hidden}.pad{padding:12px}.cell{border:0;border-block-end:1px solid var(--line);text-align:start;background:0 0;align-items:center;gap:12px;width:100%;min-height:48px;padding:10px 12px;display:flex}.cell:last-child{border-block-end:0}button.cell{cursor:pointer}button.cell:active{background:var(--line)}.cell-body{flex:1;min-width:0}.cell-title{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.cell-title.wrap{white-space:normal}.cell-sub{color:var(--hint);overflow-wrap:anywhere;font-size:13px}.cell-after{color:var(--hint);flex-shrink:0;align-items:center;gap:8px;display:flex}.chevron{border-block-start:2px solid var(--hint);border-inline-end:2px solid var(--hint);opacity:.6;width:8px;height:8px;transform:rotate(45deg)}[dir=rtl] .chevron{transform:rotate(-135deg)}.check{color:var(--accent);font-weight:700}.hint{color:var(--hint);font-size:13px}.note{color:var(--hint);padding:6px 12px 0;font-size:13px}.big{font-size:28px;font-weight:700;line-height:1.15}.error{color:var(--danger)}.center{text-align:center}.empty{text-align:center;color:var(--hint);padding:28px 16px}.mono{overflow-wrap:anywhere;direction:ltr;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}.btn{background:var(--accent);min-height:44px;color:var(--on-accent);cursor:pointer;border:0;border-radius:10px;justify-content:center;align-items:center;gap:6px;padding:8px 16px;font-weight:600;display:inline-flex}.btn.wide{width:100%}.btn.small{min-height:32px;padding:4px 12px;font-size:14px}.btn.soft{background:color-mix(in srgb, var(--accent) 14%, transparent);color:var(--accent)}.btn.danger{background:color-mix(in srgb, var(--danger) 12%, transparent);color:var(--danger)}.btn.plain{color:var(--link);background:0 0;min-height:0;padding-inline-start:4px;padding-inline-end:4px;font-weight:500}.btn:disabled{opacity:.5;cursor:default}.btn:active:not(:disabled){filter:brightness(.93)}.row{align-items:center;gap:8px;display:flex}.row.wrap{flex-wrap:wrap}.row>.grow{flex:1;min-width:0}.stack{flex-direction:column;gap:10px;display:flex}.input,.select{border:1px solid var(--line);background:var(--bg);border-radius:10px;outline:none;width:100%;min-height:44px;padding:8px 12px}.input:focus,.select:focus{border-color:var(--accent)}.select:disabled{opacity:.5}.select.compact,.input.compact{width:auto;max-width:55vw;min-height:36px;padding:4px 8px}.input.number{text-align:end;width:110px}.switch{background:var(--line);cursor:pointer;border:0;border-radius:15px;flex-shrink:0;width:50px;height:30px;transition:background .15s;position:relative}.switch:after{content:"";background:#fff;border-radius:50%;width:24px;height:24px;position:absolute;top:3px;box-shadow:0 1px 3px #0000004d}.switch:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{transition:left .15s;left:3px}.switch:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{transition:left .15s;left:3px}.switch:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{transition:right .15s;right:3px}.switch:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{transition:right .15s;right:3px}.switch[aria-checked=true]{background:var(--accent)}.switch[aria-checked=true]:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{left:23px}.switch[aria-checked=true]:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))):after{left:23px}.switch[aria-checked=true]:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{right:23px}.switch[aria-checked=true]:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)):after{right:23px}.segmented{background:var(--line);border-radius:10px;margin-block-end:12px;padding:3px;display:flex}.segmented button{cursor:pointer;background:0 0;border:0;border-radius:8px;flex:1;min-height:34px;padding:4px 6px;font-size:14px}.segmented button[aria-selected=true]{background:var(--card);font-weight:600;box-shadow:0 1px 2px #00000026}.chips{flex-wrap:wrap;gap:6px;display:flex}.chip{background:color-mix(in srgb, var(--accent) 14%, transparent);color:var(--accent);cursor:pointer;border:0;border-radius:14px;align-items:center;gap:6px;padding:4px 10px;font-size:14px;display:inline-flex}.meter{background:var(--line);border-radius:3px;height:6px;margin-block-start:6px;margin-block-end:2px;overflow:hidden}.meter>div{background:var(--accent);border-radius:3px;height:100%;transition:width .4s}.meter.busy>div{animation:1.2s ease-in-out infinite alternate slide;width:35%!important}@keyframes slide{0%{margin-inline-start:0}to{margin-inline-start:65%}}.spinner{border:3px solid var(--line);border-block-start-color:var(--accent);border-radius:50%;width:22px;height:22px;margin:24px auto;animation:.8s linear infinite spin}.btn .spinner{border-width:2px;border-color:color-mix(in srgb, currentColor 30%, transparent);border-block-start-color:currentColor;width:16px;height:16px;margin:0}@keyframes spin{to{transform:rotate(360deg)}}.stats{grid-template-columns:1fr 1fr;gap:8px;display:grid}.stat{border-radius:var(--radius);background:var(--card);padding:12px}.stat .value{font-size:20px;font-weight:700}.steps{gap:6px;margin:4px 0 14px;display:flex}.steps span{background:var(--line);border-radius:2px;flex:1;height:4px}.steps span.on{background:var(--accent)}.qr{width:min(260px,70vw);height:auto;image-rendering:pixelated;background:#fff;border-radius:12px;margin:8px auto;padding:8px;display:block}.qr-toggle summary{cursor:pointer;color:var(--accent);text-align:center}.paid-mark{background:var(--ok);color:#fff;text-align:center;border-radius:50%;width:72px;height:72px;margin:12px auto;font-size:40px;line-height:72px}.table{border-collapse:collapse;width:100%;font-size:14px}.table th,.table td{border-block-end:1px solid var(--line);text-align:end;white-space:nowrap;padding:10px 12px}.table th{color:var(--hint);font-size:12px;font-weight:500}.table th:first-child,.table td:first-child{text-align:start;white-space:normal;overflow-wrap:anywhere}.table tr:last-child td{border-block-end:0}.tabs{z-index:10;background:var(--bar);border-block-start:1px solid var(--line);justify-content:center;padding-block-end:var(--safe-bottom);display:flex;position:fixed;bottom:0;left:0;right:0}.tabs button{max-width:128px;min-height:56px;color:var(--hint);cursor:pointer;background:0 0;border:0;flex:1;padding:6px 2px 4px;font-size:11px;position:relative}.tabs button[aria-current=page]{color:var(--accent)}.tabs svg{width:24px;height:24px;margin:0 auto 2px;display:block}.badge{background:var(--accent);min-width:18px;color:var(--on-accent);border-radius:9px;padding:0 5px;font-size:11px;line-height:18px;position:absolute;top:4px}.badge:not(:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))){left:calc(50% + 6px)}.badge:not(:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi))){left:calc(50% + 6px)}.badge:-webkit-any(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)){right:calc(50% + 6px)}.badge:is(:lang(ae),:lang(ar),:lang(arc),:lang(bcc),:lang(bqi),:lang(ckb),:lang(dv),:lang(fa),:lang(glk),:lang(he),:lang(ku),:lang(mzn),:lang(nqo),:lang(pnb),:lang(ps),:lang(sd),:lang(ug),:lang(ur),:lang(yi)){right:calc(50% + 6px)}.sheet-back{z-index:20;background:#00000073;justify-content:center;align-items:flex-end;display:flex;position:fixed;top:0;bottom:0;left:0;right:0}.sheet{width:100%;max-width:640px;max-height:92vh;padding:16px 16px calc(16px + var(--safe-bottom));background:var(--card);border-radius:16px 16px 0 0;overflow-y:auto}.toast{z-index:30;color:#fff;text-align:center;background:#1e1e20f0;border-radius:12px;max-width:616px;margin:0 auto;padding:12px 14px;font-size:14px;position:fixed;bottom:calc(72px + var(--safe-bottom));left:12px;right:12px}.toast.bad{background:var(--danger)} diff --git a/web/miniapp/dist/source.sha256 b/web/miniapp/dist/source.sha256 index da0696f..7b40ae2 100644 --- a/web/miniapp/dist/source.sha256 +++ b/web/miniapp/dist/source.sha256 @@ -1 +1 @@ -c10d582421dc81e08e5517a101087298a33bbe2e5a01476b97664ffb99fab3ad +76674362440fe3a7ff1521135372c7f8ff3e06523cb9d2d3fded859c9d170e7f diff --git a/web/miniapp/embed_test.go b/web/miniapp/embed_test.go index 53b7a6a..3a254a6 100644 --- a/web/miniapp/embed_test.go +++ b/web/miniapp/embed_test.go @@ -92,7 +92,7 @@ func TestEveryTextIsInTheCatalog(t *testing.T) { } // The tables the API hands to the app, see appTables in internal/api. exported := map[string]any{} - for _, table := range []string{"app", "product", "unit", "btn", "settings", "quality", "language"} { + for _, table := range []string{"app", "product", "unit", "btn", "settings", "quality", "language", "referral"} { for k := range bundle.Section("en", table) { exported[table+"."+k] = true } diff --git a/web/miniapp/src/api.ts b/web/miniapp/src/api.ts index b8f1518..5e9da2e 100644 --- a/web/miniapp/src/api.ts +++ b/web/miniapp/src/api.ts @@ -65,7 +65,12 @@ export interface Me { payments: boolean; referral_link: string; referral_count: number; + referral_converted: number; + referral_earned: number; + referral_pending: number; + referral_qr: string; referral_reward: number; + referral_daily_cap: number; support: string; start_param: string; bot: string; diff --git a/web/miniapp/src/pages/Profile.tsx b/web/miniapp/src/pages/Profile.tsx index 0e5c084..afc9ab4 100644 --- a/web/miniapp/src/pages/Profile.tsx +++ b/web/miniapp/src/pages/Profile.tsx @@ -85,13 +85,32 @@ export function Profile() {
-
+ {me.referral_qr && ( +
+ {t("app.me.qr")} + {t("app.me.qr")} +
+ )} + + + {me.referral_pending > 0 && }
diff --git a/web/miniapp/src/styles.css b/web/miniapp/src/styles.css index c931a0b..38e4c1b 100644 --- a/web/miniapp/src/styles.css +++ b/web/miniapp/src/styles.css @@ -489,6 +489,12 @@ button.cell:active { image-rendering: pixelated; } +.qr-toggle summary { + cursor: pointer; + color: var(--accent); + text-align: center; +} + .paid-mark { width: 72px; height: 72px;