From 4f11f939a0a722394fb86703a112d2613d0b18e7 Mon Sep 17 00:00:00 2001 From: Michilis Date: Wed, 18 Nov 2026 10:27:20 +0000 Subject: [PATCH] Phase 6: Mini App A Telegram Mini App served by the core under /app/, embedded in the binary. - API under /app/api/ with initData validated (HMAC, age) on every call - Pages: Home, Queue, Buy (target, product, invoice), History, Groups, group detail (Overview, Settings, Wallet, Usage) and Me - Every action runs through the same service, billing and scheduler code as the chat, so limits, prices and admin checks are decided on the server - Texts come from the catalog over the API; layout mirrors for RTL - Front end in web/miniapp (Vite, React, TypeScript); the build is committed and guarded by a source hash test; the Docker image rebuilds it - MINIAPP_ENABLED with an https PUBLIC_URL; entry points from /app, group settings and the over-limit offer - Browser test (make miniapp-e2e) against a core in test mode - Fix: each download attempt gets its own scratch directory, so a retry cannot lose its file to the cleanup of the failed attempt Co-Authored-By: Claude Fable 5.2 --- .dockerignore | 11 + .env.example | 5 + .gitignore | 4 +- Makefile | 12 +- README.md | 14 + config.example.toml | 3 + deploy/Dockerfile | 12 + docs/ARCHITECTURE.md | 59 +- docs/ASSUMPTIONS.md | 139 ++++ docs/OPERATIONS.md | 39 + internal/api/initdata.go | 127 +++ internal/api/initdata_test.go | 67 ++ internal/api/miniapp.go | 773 +++++++++++++++++++ internal/app/app.go | 7 + internal/app/miniapp_test.go | 768 +++++++++++++++++++ internal/app/stage_test.go | 76 ++ internal/bot/appops.go | 258 +++++++ internal/bot/money.go | 5 + internal/config/config.go | 23 + internal/config/config_test.go | 17 + internal/i18n/i18n.go | 94 +++ internal/i18n/i18n_test.go | 56 ++ internal/repocheck/repocheck_test.go | 2 +- internal/tg/fakeserver/server.go | 4 + internal/worker/worker.go | 9 +- internal/worker/worker_test.go | 77 ++ locales/en.toml | 171 +++++ web/miniapp/dist/assets/app.js | 9 + web/miniapp/dist/assets/index.css | 1 + web/miniapp/dist/index.html | 15 + web/miniapp/dist/source.sha256 | 1 + web/miniapp/e2e/run.sh | 42 + web/miniapp/e2e/smoke.mjs | 294 +++++++ web/miniapp/embed.go | 25 + web/miniapp/embed_test.go | 132 ++++ web/miniapp/index.html | 14 + web/miniapp/package-lock.json | 1061 ++++++++++++++++++++++++++ web/miniapp/package.json | 24 + web/miniapp/src/App.tsx | 166 ++++ web/miniapp/src/Invoice.tsx | 124 +++ web/miniapp/src/api.ts | 172 +++++ web/miniapp/src/i18n.ts | 103 +++ web/miniapp/src/main.tsx | 14 + web/miniapp/src/pages/Buy.tsx | 140 ++++ web/miniapp/src/pages/GroupPage.tsx | 371 +++++++++ web/miniapp/src/pages/Groups.tsx | 32 + web/miniapp/src/pages/History.tsx | 15 + web/miniapp/src/pages/Home.tsx | 189 +++++ web/miniapp/src/pages/Profile.tsx | 105 +++ web/miniapp/src/pages/Queue.tsx | 101 +++ web/miniapp/src/styles.css | 623 +++++++++++++++ web/miniapp/src/tg.ts | 90 +++ web/miniapp/src/ui.tsx | 306 ++++++++ web/miniapp/tsconfig.json | 17 + web/miniapp/vite.config.ts | 57 ++ 55 files changed, 7069 insertions(+), 6 deletions(-) create mode 100644 .dockerignore create mode 100644 internal/api/initdata.go create mode 100644 internal/api/initdata_test.go create mode 100644 internal/api/miniapp.go create mode 100644 internal/app/miniapp_test.go create mode 100644 internal/app/stage_test.go create mode 100644 internal/bot/appops.go create mode 100644 web/miniapp/dist/assets/app.js create mode 100644 web/miniapp/dist/assets/index.css create mode 100644 web/miniapp/dist/index.html create mode 100644 web/miniapp/dist/source.sha256 create mode 100755 web/miniapp/e2e/run.sh create mode 100644 web/miniapp/e2e/smoke.mjs create mode 100644 web/miniapp/embed.go create mode 100644 web/miniapp/embed_test.go create mode 100644 web/miniapp/index.html create mode 100644 web/miniapp/package-lock.json create mode 100644 web/miniapp/package.json create mode 100644 web/miniapp/src/App.tsx create mode 100644 web/miniapp/src/Invoice.tsx create mode 100644 web/miniapp/src/api.ts create mode 100644 web/miniapp/src/i18n.ts create mode 100644 web/miniapp/src/main.tsx create mode 100644 web/miniapp/src/pages/Buy.tsx create mode 100644 web/miniapp/src/pages/GroupPage.tsx create mode 100644 web/miniapp/src/pages/Groups.tsx create mode 100644 web/miniapp/src/pages/History.tsx create mode 100644 web/miniapp/src/pages/Home.tsx create mode 100644 web/miniapp/src/pages/Profile.tsx create mode 100644 web/miniapp/src/pages/Queue.tsx create mode 100644 web/miniapp/src/styles.css create mode 100644 web/miniapp/src/tg.ts create mode 100644 web/miniapp/src/ui.tsx create mode 100644 web/miniapp/tsconfig.json create mode 100644 web/miniapp/vite.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a4f6541 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +# Keep secrets, runtime data and local tools out of the build context. +.git +.env +.env.* +!.env.example +!.env.worker.example +config.toml +data +bin +.tools +web/miniapp/node_modules diff --git a/.env.example b/.env.example index b0f5176..b487bf4 100644 --- a/.env.example +++ b/.env.example @@ -27,6 +27,11 @@ OWNER_IDS= # without it (invoices are then settled by polling only). PUBLIC_URL= +# The Mini App: downloads, queue, shop, groups and settings inside Telegram. +# Needs PUBLIC_URL with https, and one setting in @BotFather, see +# docs/OPERATIONS.md. The app is served by the core under /app/. +MINIAPP_ENABLED=false + # Where /support sends users: a @username or a link. SUPPORT_CONTACT= # Load translations from this directory instead of the built-in ones, and diff --git a/.gitignore b/.gitignore index 9fa6e76..2f03a7b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,9 +11,9 @@ bin/ *.test coverage.out -# Mini App build artifacts +# Mini App dependencies. The build in web/miniapp/dist is committed on +# purpose: the core embeds it, so "go build" works without Node.js. web/miniapp/node_modules/ -web/miniapp/dist/ # Editors .idea/ diff --git a/Makefile b/Makefile index b6358c5..8566a0b 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ GO ?= go BIN := bin VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) -.PHONY: all build faketelegram test test-postgres race vet fmt check run e2e acceptance clean +.PHONY: all build faketelegram miniapp miniapp-e2e test test-postgres race vet fmt check run e2e acceptance clean all: check build @@ -14,6 +14,16 @@ build: faketelegram: $(GO) build -o $(BIN)/faketelegram ./cmd/faketelegram +# Rebuild the Mini App front end into web/miniapp/dist, which the core +# embeds. Needed only after changing web/miniapp; commit dist with the change. +miniapp: + cd web/miniapp && npm ci --no-audit --no-fund && npm run build + +# Click through the Mini App in headless Chromium against a core in test +# mode. Needs "make miniapp" once, and a browser: see web/miniapp/e2e/run.sh. +miniapp-e2e: + web/miniapp/e2e/run.sh + test: $(GO) test ./... diff --git a/README.md b/README.md index 6d5b511..a81b52d 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,10 @@ and in groups. Written in Go on top of yt-dlp. - Groups: a group wallet and group pass, spending rules, admin-only settings with inline toggles, allowed and blocked sites, optional link detection, per-member usage. +- A Mini App inside Telegram: paste a link, watch and cancel the queue, + buy a pass or credits with a QR invoice that notices the payment, resend + from history, manage groups (settings, wallet, spending rules, usage by + member) and personal preferences. It is embedded in the core binary. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start with docker compose @@ -169,6 +173,8 @@ The settings you are most likely to touch: | `PRICE_CREDIT_DOWNLOAD` | `50` | Cost of a download paid with credits | | `QUEUE_FREE_MAX_LEN` | `20` | Most queued free jobs | | `DB_DSN` | `data/dlbot.db` | SQLite file | +| `PUBLIC_URL` | none | HTTPS address of the core, for webhooks, wallet links and the Mini App | +| `MINIAPP_ENABLED` | `false` | Turn the Mini App on, see [docs/OPERATIONS.md](docs/OPERATIONS.md#the-mini-app) | | `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | ## Development @@ -179,12 +185,18 @@ make test # tests only make e2e # real yt-dlp against a public test file, needs network make test-postgres PG_DSN=postgres://... # the same suite on Postgres make acceptance # kill a worker mid-job, watch the other finish +make miniapp # rebuild the Mini App front end after changing web/miniapp +make miniapp-e2e # click through the Mini App in headless Chromium ``` The tests need neither a bot token nor network access. They run the real bot against a fake Bot API server (`internal/tg/fakeserver`) and a scripted yt-dlp. +Go is all you need to build: the Mini App's compiled front end is committed +in `web/miniapp/dist` and embedded in the core. Node.js is only needed to +change it. A test fails when `dist` is older than its sources. + ## Documentation - [docs/OPERATIONS.md](docs/OPERATIONS.md): deploying and running it. @@ -211,6 +223,8 @@ internal/ytdlp yt-dlp and ffprobe wrapper internal/db migrations and queries internal/storage file storage backends internal/i18n translations and formatting +internal/api HTTP: health, payment webhook, worker protocol, Mini App API +web/miniapp the Mini App front end (Vite, React) and its embedded build locales translation catalogs docs architecture and assumptions ``` diff --git a/config.example.toml b/config.example.toml index bf9e0ea..66d4221 100644 --- a/config.example.toml +++ b/config.example.toml @@ -9,6 +9,9 @@ owners = [] # Public HTTPS base URL of this server, without a trailing slash. public_url = "" +# The Mini App, served under /app/. Needs an https public_url. +miniapp = false + # Who looks links up for the card: "auto", "local" or "worker". probe_mode = "auto" diff --git a/deploy/Dockerfile b/deploy/Dockerfile index f14dfa6..4d15d56 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -9,8 +9,19 @@ # docker-compose.yml builds core and worker for you. ARG GO_VERSION=1.26 +ARG NODE_VERSION=24 ARG DEBIAN_VERSION=bookworm +# --- Mini App front end ------------------------------------------------------ +# The repository carries a build of the Mini App already. Building it again +# here makes sure the image holds exactly what the sources say. +FROM node:${NODE_VERSION}-${DEBIAN_VERSION}-slim AS miniapp +WORKDIR /src/web/miniapp +COPY web/miniapp/package.json web/miniapp/package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY web/miniapp/ ./ +RUN npm run build + # --- build ------------------------------------------------------------------- FROM golang:${GO_VERSION}-${DEBIAN_VERSION} AS build WORKDIR /src @@ -20,6 +31,7 @@ ENV GOTOOLCHAIN=auto CGO_ENABLED=0 COPY go.mod go.sum ./ RUN go mod download COPY . . +COPY --from=miniapp /src/web/miniapp/dist ./web/miniapp/dist RUN go build -trimpath -ldflags "-s -w" -o /out/core ./cmd/core \ && go build -trimpath -ldflags "-s -w" -o /out/worker ./cmd/worker \ && go build -trimpath -ldflags "-s -w" -o /out/faketelegram ./cmd/faketelegram diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 62633ff..ae7ddf6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -49,7 +49,8 @@ phase; sections for later phases say so. | `internal/db` | Schema migrations and queries for SQLite and Postgres. | | `internal/i18n` | go-i18n wrapper, locale aware formatting. | | `internal/tg` | Narrow Bot API interface, error helpers, the fake Bot API server. | -| `internal/api` | HTTP server: health check, Telegram webhook. | +| `internal/api` | HTTP server: health check, payment webhook, worker protocol, Mini App API. | +| `web/miniapp` | The Mini App front end (Vite, React, TypeScript) and its build, embedded with `go:embed`. | | `locales` | Translation catalogs, embedded in the binary. | Dependencies point one way: `bot` uses `service`, `service` uses `sched`, @@ -351,6 +352,58 @@ Admin-only actions are checked in one place each: `requireAdmin` for commands and `cbSetting` for buttons, both through `groups.Admins`, which asks Telegram and caches the answer. +## The Mini App + +The Mini App is a second front end to the same rules. It is a single page +app, built once and embedded in the core binary, served under `/app/`, with +a JSON API under `/app/api/`. + +``` +browser (inside Telegram) core + index.html, app.js, index.css <---- GET /app/... embedded files + Authorization: tma ----> /app/api/... api.MiniApp + validate initData (HMAC, age) + load user, refuse banned + call bot.App*, service, billing +``` + +**Authentication.** Telegram gives the app an `initData` string signed with +a key derived from the bot token. The app sends it with every call and +`api.ValidateInitData` checks it every time. There are no sessions and no +cookies, so there is nothing to steal besides a string that expires. The +user ID comes from the validated string and from nowhere else. + +**Nothing is decided in the browser.** The app shows prices, limits and +buttons, but every operation goes through the code the chat uses: + +| App action | Runs | +| --- | --- | +| Look a link up | `bot.AppProbe`: `service.Gate`, rate limit, `service.Probe` | +| Start a download, resend | `bot.AppDownload`, `bot.AppResend`: `service.Preview`, then `service.Start` | +| Cancel | `sched.CancelDelivery`, owner checked | +| Prioritize | credits or a `skip_queue` invoice, like the chat button | +| Buy | `billing.CreatePurchase`; the price comes from the core's price list | +| Payment detection | `billing.Check`, which asks LNbits | +| Group pages | `groups.Admins.IsAdmin` on every call, then the same settings rows | + +So a cache hit, a resend or a tampered request meets the same limits and +the same ledger as a message in the chat. Files and status messages always +arrive in the user's private chat with the bot; a web page cannot receive +them. + +**Texts.** The app has no text of its own. `GET /app/api/i18n` returns the +`app` table of the catalog plus the tables it shares with the chat +(product names, units, button and setting labels), in the user's language +with the usual fallback, placeholders rewritten from `{{.Name}}` to +`{Name}` and plurals as CLDR forms. The response also carries the text +direction. The style sheet uses logical properties only, so `dir="rtl"` +mirrors the layout. + +**Build.** `web/miniapp/dist` is committed, so `go build` needs no Node.js. +The build writes a hash of its sources next to its output and a Go test +recomputes it, which catches a source change committed without a rebuild. +The Docker image rebuilds the front end from source. + ## Internationalization Handlers never contain user-facing text. They call `i18n.Bundle` with a @@ -376,6 +429,10 @@ all output. URLs are redacted before they are logged. `tg/fakeserver`, an HTTP server that speaks enough of the Bot API to push updates in and record every call, including multipart uploads. - One opt-in test runs the real yt-dlp against a public test file. +- The Mini App API is tested over real HTTP with initData signed like + Telegram signs it. `make miniapp-e2e` additionally opens the built app in + headless Chromium against a core in test mode and clicks through every + flow; it is opt-in because it needs a browser. - Payments are tested against `billing/lnbitstest`, a fake LNbits that speaks the real request and response shapes and lets a test pay invoices, replay or drop webhooks and take the server down. diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index 55b61a8..d16980f 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -516,3 +516,142 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current). change at runtime. - `/privacy`, `/terms` and `/support` are short texts in the catalog. Replace them with your own before running a public bot. + +## Phase 6 + +### Verified Telegram Mini App facts + +Checked against https://core.telegram.org/bots/webapps on 2026-11-18. + +- The page must load `https://telegram.org/js/telegram-web-app.js` in its + head. It provides `window.Telegram.WebApp`. +- `initData` is a query string. It is valid when + `hex(HMAC_SHA256(key=HMAC_SHA256(key="WebAppData", msg=bot_token), msg=data_check_string))` + equals its `hash` field, where the check string is every other field as + `key=value`, sorted by key, joined with line feeds. +- `start_param` in initData carries the `startapp` value of a + `https://t.me/?startapp=` link. Such links open the bot's + main Mini App, which is set in @BotFather. No Bot API method sets it. +- A launch from an inline keyboard `web_app` button has no start + parameter. Those buttons work in private chats only. +- Theme colors arrive as CSS variables (`--tg-theme-...`), safe areas as + `--tg-safe-area-inset-...` and `--tg-content-safe-area-inset-...`. +- `openLink` opens a URL in the system browser. The page does not say that + it accepts schemes other than http and https. + +### Authentication + +- Every API call carries `Authorization: tma `. The core + validates it on each request. There is no session, cookie or token of + our own, so a call can never be more trusted than Telegram's signature. +- initData older than 24 hours is refused, and so is one dated more than + five minutes ahead. Telegram does not refresh initData while an app + stays open, so an app left open for a day has to be opened again. A + shorter window would log people out mid-use; no window would make a + leaked string valid forever. +- The check string is tried as documented (all fields but `hash`), and + also without `signature`. Either way only the bot token can produce the + hash. +- A call without valid initData gets `401` and one sentence in the + language of the browser. A banned user gets `403`. +- The API exists only when `MINIAPP_ENABLED=true`. That setting requires + an https `PUBLIC_URL` and the core refuses to start otherwise (plain + http is accepted for localhost, for development). + +### What the app can do, and where the result goes + +- A web page cannot receive files. Downloads started in the app, and + resends from its history, post their status message and file in the + user's private chat with the bot. The app says so and shows progress on + the Queue tab. +- Downloads from the app are personal: they resolve entitlement like a + private chat (own pass, own credits, free), never a group's wallet. +- The front end is never trusted. It shows every format and every + product; the core applies limits and prices when the call arrives. A + price sent by the client is ignored for passes, and credits must be an + amount the billing service accepts. +- The shop sells passes and credits. "Pay for this file only" needs a + refused download behind it and stays in the chat; "skip the queue" is + the Prioritize button on the Queue tab. Donations stay in the chat. +- Buy, step 1: the targets offered are the user and the groups they + administer. The API accepts any group the bot is in, the same rule as in + chat, where anybody may pay for a group. +- Payment detection: the app asks `GET /app/api/purchase/` every 2.5 + seconds, and each call asks LNbits. This works without a webhook. A + paid purchase also produces the usual "Paid" message in the chat. +- The QR code is made by the core and sent as a PNG data URL, so the app + ships no QR library. +- "Open in wallet" goes through the existing `/pay/` page with + `openLink`, because `openLink` is only documented for web addresses. +- Queue and history are polled (queue every 2 seconds while visible). + There is no push channel; polling is simple and the numbers are small. +- "Audio only" on the Me tab is the default format MP3. Turning it off + returns to "ask every time". +- Rate limits: link lookups share the chat's budget (`RATE_USER_PER_MINUTE`), + starts and resends get twice that, invoices 10 per minute per user. + +### Groups in the app + +- Telegram has no "list my groups" call. The Groups tab shows groups where + the bot is present, has seen the user at least once, and Telegram + confirms the user as an admin right now (cached for five minutes, like + in chat). +- Every group endpoint checks admin status again. A demoted admin loses + access; a group the bot left is "not found" for everybody. +- Settings are saved as a whole and validated field by field. Site lists + accept a host name or a pasted link and store the host. +- Size and duration caps for a group can only be set here. They can lower + the tier's limit, never raise it; a higher value is stored as the tier's. +- Usage by member covers the last 7 days. + +### Front end + +- Vite, React and TypeScript, no router and no UI library. About 77 KB of + JavaScript after gzip. +- The build output `web/miniapp/dist` is committed, so `go build` and + `go install` work without Node.js. `make miniapp` rebuilds it. A Go test + fails when it is older than its sources. The Docker build rebuilds it. +- File names are stable (`assets/app.js`) to keep diffs small. The core + sends `Cache-Control: no-cache` with an ETag of the content, so clients + revalidate and pick up a new build at once. +- A Content-Security-Policy allows scripts from the app itself and + telegram.org only, and framing by Telegram's web clients only. +- The lookup card in the app has no thumbnail. An image loaded by the + browser would reveal the user's IP address to the video site; in chat the + thumbnail is fetched by Telegram's servers instead. +- All text comes from the catalog over the API. A test fails when the app + asks for a key the catalog lacks, or when markup contains a literal + sentence. +- Right to left: the direction comes from the language (`ar`, `he`, `fa`, + `ur` and a few more are known as RTL), and the style sheet uses logical + properties. No RTL catalog ships yet, so this is tested by forcing the + direction in the browser test. +- The bot's menu button is left alone. Replacing it with the app would + hide the command list, which is translated per language. +- The built-in catalogs decide the language list on the Me tab. The app + follows the user's language setting, or the Telegram language when none + is set, and reloads its texts when it changes. + +### What could and could not be run here + +- The API tests run on SQLite and Postgres like the rest of the suite. +- The browser test (`make miniapp-e2e`) ran here in headless Chromium: + lookup and download, cancel, resend, buying a pass, group settings, + group top-up, preferences, a deep link, forced RTL, and the notice + outside Telegram. It is not part of `make check`, because it needs a + browser. +- The app was not opened inside a real Telegram client. The bridge script + is replaced by a stand-in in the browser test. Theme colors, the back + button and haptics follow the documentation but were not seen on a + phone. +- `npm audit` reports an advisory for `picomatch`, a dependency of Vite. + It is a build tool and is not part of what the core serves. + +### Fixed on the way + +- A worker used one scratch directory per job. When a download failed and + the retry started on another slot of the same worker before the first + slot had finished reporting, the first slot's cleanup deleted the + retry's file, and the job failed with an internal error. It showed up as + a rare test failure on a busy machine. Every attempt now has its own + directory, and a test holds the two slots in exactly that order. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index e764a98..393468a 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -118,6 +118,7 @@ Put a TLS reverse proxy (Caddy, nginx, Traefik) in front and set `PUBLIC_URL=https://bot.example.com` when you want any of: - instant payment settlement (LNbits webhook) and the "Open in wallet" button +- the Mini App - remote workers across the internet - Telegram webhooks instead of long polling (`TELEGRAM_MODE=webhook`, `WEBHOOK_URL`, `WEBHOOK_SECRET`) @@ -129,12 +130,50 @@ Routes the proxy must pass through: | `/telegram/webhook` | Telegram (webhook mode only) | | `/lnbits/webhook/` | LNbits | | `/pay/` | Users pressing "Open in wallet" | +| `/app/...` | The Mini App and its API, opened by Telegram clients | | `/worker/v1/...` | Remote workers. Allow long requests (30 s) and large uploads. | | `/healthz` | Your monitoring | Without `PUBLIC_URL` the bot still works: long polling for Telegram, polling for payments, workers on the same network. +## The Mini App + +The Mini App is a small web page that Telegram opens inside the chat. The +core serves it; there is nothing extra to host. + +1. Give the core a public HTTPS address and set it (see the section above). + Telegram refuses Mini Apps over plain http. + + ```sh + PUBLIC_URL=https://bot.example.com + MINIAPP_ENABLED=true + ``` + +2. Restart the core, then open `https://bot.example.com/app/` in a browser. + You should see one sentence asking you to open the page from Telegram. + That means the app is served and refuses strangers, as it should. + +3. Tell Telegram where the app lives. In @BotFather: `/mybots`, pick the + bot, **Bot Settings**, **Configure Mini App**, **Enable Mini App**, and + enter `https://bot.example.com/app/`. This is the bot's "main Mini App". + It adds a **Launch app** button to the bot's profile and makes the link + `https://t.me/?startapp` work, which the bot uses in groups. + +4. Send `/app` to the bot and press the button. + +With the app on, `/app` shows an "Open app" button, group admins get a +link from `/settings` straight into their group's page, and a download +that is over the limit offers the shop inside the app. + +The app has no login of its own. Telegram signs who the user is, and the +core checks that signature with the bot token on every call. A signature +older than 24 hours is refused, so an app left open for a day asks to be +opened again. + +If step 3 is skipped, the button in private chats still works. Only the +`?startapp` links from groups and the profile button need it. + ## Health and logs - `GET /healthz` on the core answers 200 while the database is reachable. diff --git a/internal/api/initdata.go b/internal/api/initdata.go new file mode 100644 index 0000000..666fcfe --- /dev/null +++ b/internal/api/initdata.go @@ -0,0 +1,127 @@ +package api + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/url" + "sort" + "strconv" + "strings" + "time" +) + +// InitData is what a validated Mini App launch tells us. +type InitData struct { + User InitUser + AuthDate time.Time + StartParam string +} + +// InitUser is the Telegram user who opened the Mini App. +type InitUser struct { + ID int64 `json:"id"` + FirstName string `json:"first_name"` + Username string `json:"username"` + LanguageCode string `json:"language_code"` +} + +// Errors from ValidateInitData. +var ( + ErrInitDataMissing = errors.New("api: no init data") + ErrInitDataInvalid = errors.New("api: init data signature is wrong") + ErrInitDataExpired = errors.New("api: init data is too old") +) + +// ValidateInitData checks the initData string a Mini App got from +// Telegram, as described in "Validating data received via the Mini App": +// +// secret_key = HMAC_SHA256(key="WebAppData", message=bot_token) +// hash = hex(HMAC_SHA256(key=secret_key, message=data_check_string)) +// +// where data_check_string is every received field except hash, as +// key=value, sorted by key and joined with line feeds. Only somebody who +// knows the bot token can produce a matching hash, so a valid initData +// proves that Telegram vouches for the user in it. +// +// maxAge bounds how old the launch may be. Without that bound a leaked +// initData string would work forever. +func ValidateInitData(raw, botToken string, maxAge time.Duration, now time.Time) (*InitData, error) { + if raw == "" { + return nil, ErrInitDataMissing + } + values, err := url.ParseQuery(raw) + if err != nil { + return nil, ErrInitDataInvalid + } + got, err := hex.DecodeString(values.Get("hash")) + if err != nil || len(got) != sha256.Size { + return nil, ErrInitDataInvalid + } + secret := hmacSHA256([]byte("WebAppData"), []byte(botToken)) + // The documented string leaves out only "hash". Some clients built + // theirs without "signature" as well; both are accepted, since either + // way the hash can only be made with the bot token. + if !hmac.Equal(got, hmacSHA256(secret, []byte(checkString(values, "hash")))) && + !hmac.Equal(got, hmacSHA256(secret, []byte(checkString(values, "hash", "signature")))) { + return nil, ErrInitDataInvalid + } + sec, err := strconv.ParseInt(values.Get("auth_date"), 10, 64) + if err != nil { + return nil, ErrInitDataInvalid + } + d := &InitData{AuthDate: time.Unix(sec, 0), StartParam: values.Get("start_param")} + if maxAge > 0 && now.Sub(d.AuthDate) > maxAge { + return nil, ErrInitDataExpired + } + if d.AuthDate.After(now.Add(5 * time.Minute)) { + return nil, ErrInitDataInvalid // dated in the future + } + if err := json.Unmarshal([]byte(values.Get("user")), &d.User); err != nil || d.User.ID == 0 { + return nil, ErrInitDataInvalid + } + return d, nil +} + +func checkString(values url.Values, skip ...string) string { + keys := make([]string, 0, len(values)) +next: + for k := range values { + for _, s := range skip { + if k == s { + continue next + } + } + keys = append(keys, k) + } + sort.Strings(keys) + lines := make([]string, 0, len(keys)) + for _, k := range keys { + lines = append(lines, k+"="+values.Get(k)) + } + return strings.Join(lines, "\n") +} + +func hmacSHA256(key, msg []byte) []byte { + m := hmac.New(sha256.New, key) + m.Write(msg) + return m.Sum(nil) +} + +// SignInitData builds a valid initData string. Telegram does this in +// production; tests and local tools use it to act as a Mini App. +func SignInitData(botToken string, user InitUser, authDate time.Time, startParam string) string { + u, _ := json.Marshal(user) + values := url.Values{} + values.Set("auth_date", strconv.FormatInt(authDate.Unix(), 10)) + values.Set("user", string(u)) + values.Set("query_id", "AAF0test") + if startParam != "" { + values.Set("start_param", startParam) + } + secret := hmacSHA256([]byte("WebAppData"), []byte(botToken)) + values.Set("hash", hex.EncodeToString(hmacSHA256(secret, []byte(checkString(values, "hash"))))) + return values.Encode() +} diff --git a/internal/api/initdata_test.go b/internal/api/initdata_test.go new file mode 100644 index 0000000..4d898f3 --- /dev/null +++ b/internal/api/initdata_test.go @@ -0,0 +1,67 @@ +package api + +import ( + "errors" + "net/url" + "strings" + "testing" + "time" +) + +const testToken = "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" + +func TestValidateInitData(t *testing.T) { + now := time.Unix(1_800_000_000, 0) + user := InitUser{ID: 42, FirstName: "Ana & Co", Username: "ana", LanguageCode: "es-PY"} + raw := SignInitData(testToken, user, now.Add(-time.Minute), "group_-1001") + + got, err := ValidateInitData(raw, testToken, time.Hour, now) + if err != nil { + t.Fatalf("valid data refused: %v", err) + } + if got.User != user || got.StartParam != "group_-1001" || !got.AuthDate.Equal(now.Add(-time.Minute)) { + t.Fatalf("parsed = %+v", got) + } + + mutate := func(f func(url.Values)) string { + v, _ := url.ParseQuery(raw) + f(v) + return v.Encode() + } + cases := []struct { + name string + raw string + tok string + want error + }{ + {"empty", "", testToken, ErrInitDataMissing}, + {"no hash", mutate(func(v url.Values) { v.Del("hash") }), testToken, ErrInitDataInvalid}, + {"other bot's token", raw, strings.Replace(testToken, "01", "02", 1), ErrInitDataInvalid}, + {"user swapped", mutate(func(v url.Values) { v.Set("user", `{"id":43,"first_name":"Eve"}`) }), testToken, ErrInitDataInvalid}, + {"field added", mutate(func(v url.Values) { v.Set("chat_type", "private") }), testToken, ErrInitDataInvalid}, + {"start param changed", mutate(func(v url.Values) { v.Set("start_param", "group_-1002") }), testToken, ErrInitDataInvalid}, + {"hash of another length", mutate(func(v url.Values) { v.Set("hash", "abcd") }), testToken, ErrInitDataInvalid}, + {"not a query string", "%zz", testToken, ErrInitDataInvalid}, + } + for _, c := range cases { + if _, err := ValidateInitData(c.raw, c.tok, time.Hour, now); !errors.Is(err, c.want) { + t.Errorf("%s: err = %v, want %v", c.name, err, c.want) + } + } + + // Old data is refused even with a good signature, and so is data from + // the future beyond clock skew. + if _, err := ValidateInitData(raw, testToken, time.Hour, now.Add(2*time.Hour)); !errors.Is(err, ErrInitDataExpired) { + t.Errorf("stale data: err = %v", err) + } + future := SignInitData(testToken, user, now.Add(time.Hour), "") + if _, err := ValidateInitData(future, testToken, time.Hour, now); err == nil { + t.Error("data dated an hour ahead was accepted") + } + + // A signature over a user without an ID is not a user. + anon := SignInitData(testToken, InitUser{}, now, "") + if _, err := ValidateInitData(anon, testToken, time.Hour, now); err == nil { + t.Error("data without a user ID was accepted") + } +} diff --git a/internal/api/miniapp.go b/internal/api/miniapp.go new file mode 100644 index 0000000..22c351a --- /dev/null +++ b/internal/api/miniapp.go @@ -0,0 +1,773 @@ +package api + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io/fs" + "log/slog" + "net/http" + "strconv" + "strings" + "time" + + qrcode "github.com/skip2/go-qrcode" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/bot" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/groups" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +// MiniApp serves the Telegram Mini App: the static front end under /app/ +// and its JSON API under /app/api/. +// +// Every API call carries the initData string Telegram gave the app, in +// "Authorization: tma ". It is validated on each request; there +// is no session and no cookie. Whatever the front end shows, what a user +// may do and what it costs is decided here, by the same service the chat +// commands use. +type MiniApp struct { + Cfg config.Config + Store *db.Store + Billing *billing.Billing + Service *service.Service + Bot *bot.Bot + I18n *i18n.Bundle + Admins *groups.Admins + Log *slog.Logger + // Static is the built front end. + Static fs.FS + // MaxAge bounds how old an initData may be. Defaults to 24 hours. + MaxAge time.Duration + Now func() time.Time +} + +// session is the authenticated caller of one request. +type session struct { + user *db.User + lang string + init *InitData +} + +type appHandler func(w http.ResponseWriter, r *http.Request, s *session) + +// RegisterMiniApp adds the Mini App routes to the server. +func (s *Server) RegisterMiniApp(m *MiniApp) { + if m.Log == nil { + m.Log = s.log + } + if m.MaxAge <= 0 { + m.MaxAge = 24 * time.Hour + } + if m.Now == nil { + m.Now = time.Now + } + api := func(pattern string, h appHandler) { s.mux.HandleFunc(pattern, m.auth(h)) } + api("GET /app/api/me", m.me) + api("PUT /app/api/me", m.updateMe) + api("GET /app/api/i18n", m.messages) + api("POST /app/api/probe", m.probe) + api("POST /app/api/download", m.download) + api("GET /app/api/queue", m.queue) + api("POST /app/api/queue/{id}/cancel", m.cancel) + api("POST /app/api/queue/{id}/prioritize", m.prioritize) + api("GET /app/api/history", m.history) + api("POST /app/api/history/{id}/resend", m.resend) + api("GET /app/api/products", m.products) + api("POST /app/api/purchase", m.purchase) + api("GET /app/api/purchase/{id}", m.purchaseStatus) + api("POST /app/api/purchase/{id}/cancel", m.purchaseCancel) + api("GET /app/api/groups", m.groups) + api("GET /app/api/groups/{id}", m.group) + api("PUT /app/api/groups/{id}/settings", m.groupSettings) + api("GET /app/api/groups/{id}/usage", m.groupUsage) + if m.Static != nil { + s.mux.Handle("GET /app/", m.static()) + } +} + +// static serves the built front end. Unknown paths get index.html, which +// is what a single page app needs. Files carry an ETag of their content, +// so a client revalidates cheaply and picks up a new build at once. +func (m *MiniApp) static() http.Handler { + etags := map[string]string{} + _ = fs.WalkDir(m.Static, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + if data, err := fs.ReadFile(m.Static, path); err == nil { + sum := sha256.Sum256(data) + etags[path] = `"` + hex.EncodeToString(sum[:8]) + `"` + } + return nil + }) + files := http.StripPrefix("/app/", http.FileServerFS(m.Static)) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/app/") + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cache-Control", "no-cache") + // The app only loads its own code plus Telegram's bridge script, + // and may only be framed by Telegram's web clients. No images from + // other hosts: a thumbnail fetched by the browser would show the + // user's address to the video site. + h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self' https://telegram.org; "+ + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "+ + "frame-ancestors https://web.telegram.org https://*.telegram.org") + if _, ok := etags[path]; !ok { + path = "index.html" + r = r.Clone(r.Context()) + r.URL.Path = "/app/" + } + h.Set("ETag", etags[path]) + files.ServeHTTP(w, r) + }) +} + +func (m *MiniApp) fail(w http.ResponseWriter, status int, code, message string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"error": code, "message": message}) +} + +// explain answers with the bot's wording for an operation error. +func (m *MiniApp) explain(w http.ResponseWriter, s *session, err error) { + code, msg, upgradable := m.Bot.Explain(s.lang, err) + status := http.StatusUnprocessableEntity + switch code { + case "internal": + status = http.StatusInternalServerError + case "not_found": + // The chat wording talks about a card, which the app does not have. + status, msg = http.StatusNotFound, m.I18n.T(s.lang, "app.error.not_found", nil) + case "rate_limited": + status = http.StatusTooManyRequests + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"error": code, "message": msg, "upgradable": upgradable}) +} + +func (m *MiniApp) ok(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(v) +} + +// auth validates initData and loads the user. It runs on every call. +func (m *MiniApp) auth(next appHandler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + raw, _ := strings.CutPrefix(r.Header.Get("Authorization"), "tma ") + init, err := ValidateInitData(raw, m.Cfg.Telegram.Token, m.MaxAge, m.Now()) + if err != nil { + // The caller is unknown, so the browser's language is the best + // guess for the one sentence it gets to read. + lang, _, _ := strings.Cut(r.Header.Get("Accept-Language"), ",") + lang, _, _ = strings.Cut(lang, ";") + m.fail(w, http.StatusUnauthorized, "unauthorized", m.I18n.T(m.I18n.Resolve(strings.TrimSpace(lang)), "app.error.unauthorized", nil)) + return + } + u, err := m.Store.UpsertUser(r.Context(), init.User.ID, init.User.Username, init.User.FirstName, init.User.LanguageCode) + if err != nil { + m.Log.Error("mini app: load user", "err", err) + m.fail(w, http.StatusInternalServerError, "internal", "") + return + } + lang := u.LangOverride + if lang == "" { + lang = m.I18n.Resolve(u.Lang) + } + if u.Banned { + m.fail(w, http.StatusForbidden, "forbidden", m.I18n.T(lang, "app.error.banned", nil)) + return + } + next(w, r, &session{user: u, lang: lang, init: init}) + } +} + +func decode(r *http.Request, v any) error { + return json.NewDecoder(http.MaxBytesReader(nil, r.Body, 64<<10)).Decode(v) +} + +// --- me ---------------------------------------------------------------------- + +type tierJSON struct { + MaxSize int64 `json:"max_size"` + MaxDuration int64 `json:"max_duration"` + ActiveJobs int `json:"active_jobs"` + DailyDownloads int `json:"daily_downloads"` + DailyBytes int64 `json:"daily_bytes"` +} + +func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { + ctx := r.Context() + who := service.Who{UserID: s.user.ID, ChatID: s.user.ID, ChatType: "private"} + dec, err := m.Service.Entitlement(ctx, who, false) + if err != nil { + m.explain(w, s, err) + return + } + st, _ := m.Billing.State(ctx, db.OwnerUser, s.user.ID) + usage, _ := m.Service.Usage(ctx, s.user.ID) + refs, _ := m.Store.CountReferrals(ctx, s.user.ID) + var langs []map[string]string + for _, l := range m.I18n.Langs() { + if !m.I18n.Hidden(l) { + langs = append(langs, map[string]string{"code": l, "name": m.I18n.T(l, "language.name", nil)}) + } + } + support := m.Cfg.Support + if support == "" { + support = "@" + m.Bot.Username() + } + m.ok(w, map[string]any{ + "id": s.user.ID, + "name": s.user.FirstName, + "lang": s.lang, + "lang_override": s.user.LangOverride, + "dir": i18n.Dir(s.lang), + "languages": langs, + "quality": s.user.Quality, + "pass_until": st.PassUntil, + "balance": st.Credits, + "source": string(dec.Source), + "usage": map[string]any{"downloads": usage.Downloads, "bytes": usage.Bytes}, + "limits": tierJSON{ + MaxSize: dec.Limits.MaxSize, MaxDuration: dec.Limits.MaxDuration, ActiveJobs: dec.Limits.ActiveJobs, + DailyDownloads: dec.Limits.DailyDownloads, DailyBytes: dec.Limits.DailyBytes, + }, + "payments": m.Billing.Enabled(), + "referral_link": "https://t.me/" + m.Bot.Username() + "?start=ref_" + strconv.FormatInt(s.user.ID, 10), + "referral_count": refs, + "referral_reward": m.Cfg.Prices.ReferralReward, + "support": support, + "start_param": s.init.StartParam, + "bot": m.Bot.Username(), + }) +} + +func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { + var in struct { + Quality *string `json:"quality"` + Lang *string `json:"lang"` + } + if err := decode(r, &in); err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + ctx := r.Context() + if in.Quality != nil { + q := *in.Quality + if q != "" { + p, err := media.Parse(q) + if err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + } + if err := m.Store.SetUserQuality(ctx, s.user.ID, q); err != nil { + m.explain(w, s, err) + return + } + } + if in.Lang != nil { + lang := "" + if *in.Lang != "" && *in.Lang != "auto" { + for _, l := range m.I18n.Langs() { + if l == *in.Lang { + lang = l + } + } + if lang == "" { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + } + if err := m.Store.SetUserLang(ctx, s.user.ID, lang); err != nil { + m.explain(w, s, err) + return + } + } + m.ok(w, map[string]bool{"ok": true}) +} + +// appTables are the catalog tables the Mini App reads. Its own texts are +// under "app"; names it shares with the chat (products, units, button and +// setting labels) are not written twice. +var appTables = []string{"app", "product", "unit", "btn", "settings", "quality", "language"} + +// messages returns the Mini App's texts in the user's language, from the +// same catalogs the bot uses. Keys keep their full name: "app.tab.home". +func (m *MiniApp) messages(w http.ResponseWriter, _ *http.Request, s *session) { + out := map[string]any{} + for _, table := range appTables { + for k, v := range m.I18n.Section(s.lang, table) { + out[table+"."+k] = v + } + } + m.ok(w, map[string]any{"lang": s.lang, "dir": i18n.Dir(s.lang), "messages": out}) +} + +// --- downloads --------------------------------------------------------------- + +func (m *MiniApp) probe(w http.ResponseWriter, r *http.Request, s *session) { + var in struct { + URL string `json:"url"` + } + if err := decode(r, &in); err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + url, err := links.Normalize(in.URL) + if err != nil { + m.fail(w, http.StatusUnprocessableEntity, "bad_link", m.I18n.T(s.lang, "app.error.bad_link", nil)) + return + } + info, err := m.Bot.AppProbe(r.Context(), s.user, url) + if err != nil { + m.explain(w, s, err) + return + } + type option struct { + Profile string `json:"profile"` + Size int64 `json:"size,omitempty"` + } + opts := []option{{Profile: "best", Size: info.Sizes["best"]}} + for _, p := range []media.Profile{media.P1080, media.P720, media.P480} { + if info.MaxHeight == 0 || info.MaxHeight > p.Height() { + opts = append(opts, option{Profile: string(p), Size: info.Sizes[string(p)]}) + } + } + if info.HasAudio { + opts = append(opts, option{Profile: "mp3", Size: info.Sizes["mp3"]}) + } + m.ok(w, map[string]any{ + "url": url, "title": info.Title, "uploader": info.Uploader, + "duration": info.Duration, "site": info.Site, "options": opts, + }) +} + +func (m *MiniApp) download(w http.ResponseWriter, r *http.Request, s *session) { + var in struct { + URL string `json:"url"` + Profile string `json:"profile"` + } + if err := decode(r, &in); err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + url, uerr := links.Normalize(in.URL) + profile, perr := media.Parse(in.Profile) + if uerr != nil || perr != nil { + m.fail(w, http.StatusUnprocessableEntity, "bad_link", m.I18n.T(s.lang, "app.error.bad_link", nil)) + return + } + if err := m.Bot.AppDownload(r.Context(), s.user, s.lang, url, profile); err != nil { + m.explain(w, s, err) + return + } + m.ok(w, map[string]bool{"ok": true}) +} + +func (m *MiniApp) queue(w http.ResponseWriter, r *http.Request, s *session) { + jobs, err := m.Bot.AppQueue(r.Context(), s.user.ID) + if err != nil { + m.explain(w, s, err) + return + } + m.ok(w, map[string]any{"jobs": jobs}) +} + +func (m *MiniApp) cancel(w http.ResponseWriter, r *http.Request, s *session) { + if err := m.Bot.AppCancel(r.Context(), s.user.ID, r.PathValue("id")); err != nil { + m.explain(w, s, err) + return + } + m.ok(w, map[string]bool{"ok": true}) +} + +func (m *MiniApp) prioritize(w http.ResponseWriter, r *http.Request, s *session) { + done, p, err := m.Bot.AppSkip(r.Context(), s.user, s.lang, r.PathValue("id")) + if err != nil { + m.explain(w, s, err) + return + } + out := map[string]any{"done": done} + if p != nil { + out["purchase"] = m.purchaseJSON(p, true) + } + m.ok(w, out) +} + +func (m *MiniApp) history(w http.ResponseWriter, r *http.Request, s *session) { + limit := 30 + if r.URL.Query().Get("limit") == "5" { + limit = 5 + } + dels, err := m.Store.History(r.Context(), s.user.ID, limit) + if err != nil { + m.explain(w, s, err) + return + } + type item struct { + ID string `json:"id"` + Title string `json:"title"` + Profile string `json:"profile"` + Size int64 `json:"size"` + At int64 `json:"at"` + } + items := []item{} + for _, d := range dels { + job, err := m.Store.GetJob(r.Context(), d.JobID) + if err != nil { + continue + } + items = append(items, item{ID: d.ID, Title: job.Title, Profile: job.Profile, Size: job.FileSize, At: d.UpdatedAt}) + } + m.ok(w, map[string]any{"items": items}) +} + +func (m *MiniApp) resend(w http.ResponseWriter, r *http.Request, s *session) { + if err := m.Bot.AppResend(r.Context(), s.user, s.lang, r.PathValue("id")); err != nil { + m.explain(w, s, err) + return + } + m.ok(w, map[string]bool{"ok": true}) +} + +// --- buying ------------------------------------------------------------------ + +func (m *MiniApp) products(w http.ResponseWriter, _ *http.Request, s *session) { + p := m.Cfg.Prices + paid := m.Cfg.Limits.Paid + size := paid.MaxSizeMB << 20 + if up := m.Cfg.MaxUploadBytes(); up > 0 && up < size { + size = up + } + m.ok(w, map[string]any{ + "enabled": m.Billing.Enabled(), + "passes": []map[string]any{ + {"product": billing.ProductPassDay, "price": p.PassDay}, + {"product": billing.ProductPassWeek, "price": p.PassWeek}, + {"product": billing.ProductPassMonth, "price": p.PassMonth}, + }, + "credit_packs": p.CreditPacks, + "credit_per_download": p.CreditPerDownload, + "paid": tierJSON{MaxSize: size, MaxDuration: int64(paid.MaxDuration.D().Seconds()), ActiveJobs: paid.ActiveJobs, DailyDownloads: paid.DailyDownloads, DailyBytes: paid.DailyMB << 20}, + "invoice_seconds": int(m.Cfg.LNbits.InvoiceExpiry.D().Seconds()), + }) +} + +// purchaseJSON is what the app needs to show an invoice. The QR code is +// made here, so the front end needs no QR library. +func (m *MiniApp) purchaseJSON(p *db.Purchase, withInvoice bool) map[string]any { + out := map[string]any{ + "id": p.ID, "product": p.Product, "amount": p.AmountSats, "status": p.Status, + "expires_at": p.ExpiresAt, "paid_at": p.PaidAt, + } + if withInvoice && p.Status == db.PurchasePending { + out["bolt11"] = p.Bolt11 + if png, err := qrcode.Encode(strings.ToUpper(p.Bolt11), qrcode.Medium, 512); err == nil { + out["qr"] = "data:image/png;base64," + base64.StdEncoding.EncodeToString(png) + } + } + return out +} + +func (m *MiniApp) purchase(w http.ResponseWriter, r *http.Request, s *session) { + var in struct { + Target string `json:"target"` // "me" or a group chat ID + Product string `json:"product"` + Amount int64 `json:"amount"` + } + if err := decode(r, &in); err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + // Products that need a download or a job behind them are not sold + // from this endpoint. + switch in.Product { + case billing.ProductPassDay, billing.ProductPassWeek, billing.ProductPassMonth, billing.ProductCredits: + default: + m.explain(w, s, billing.ErrBadProduct) + return + } + var groupID int64 + if in.Target != "" && in.Target != "me" { + id, err := strconv.ParseInt(in.Target, 10, 64) + if err != nil || id >= 0 { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + groupID = id + } + p, err := m.Bot.AppPurchase(r.Context(), s.user, s.lang, groupID, in.Product, in.Amount, "") + if err != nil { + m.explain(w, s, err) + return + } + m.ok(w, m.purchaseJSON(p, true)) +} + +// purchaseStatus is polled by the app while an invoice is open. Each call +// asks the payment backend, so the app notices a payment within seconds +// even when the webhook is not set up. +func (m *MiniApp) purchaseStatus(w http.ResponseWriter, r *http.Request, s *session) { + p, err := m.Billing.Check(r.Context(), r.PathValue("id"), s.user.ID) + if errors.Is(err, billing.ErrLightningDown) { + // Still answer with what is known; the next poll may reach it. + if p, err = m.Store.GetPurchase(r.Context(), r.PathValue("id")); err == nil && p.UserID != s.user.ID { + err = db.ErrNotFound + } + } + if err != nil { + m.explain(w, s, db.ErrNotFound) + return + } + out := m.purchaseJSON(p, false) + if p.Status == db.PurchasePaid { + if wl, err := m.Store.GetWallet(r.Context(), p.WalletID); err == nil { + out["balance"] = wl.Balance + if until, err := m.Store.PassUntil(r.Context(), wl.ID, db.NowMilli()); err == nil { + out["pass_until"] = until + } + } + } + m.ok(w, out) +} + +func (m *MiniApp) purchaseCancel(w http.ResponseWriter, r *http.Request, s *session) { + if _, err := m.Billing.Cancel(r.Context(), r.PathValue("id"), s.user.ID); err != nil { + m.explain(w, s, db.ErrNotFound) + return + } + m.ok(w, map[string]bool{"ok": true}) +} + +// --- groups ------------------------------------------------------------------ + +func (m *MiniApp) groupJSON(ctx context.Context, g *db.Group) map[string]any { + st, _ := m.Billing.State(ctx, db.OwnerGroup, g.ChatID) + return map[string]any{ + "id": strconv.FormatInt(g.ChatID, 10), "title": g.Title, "balance": st.Credits, "pass_until": st.PassUntil, + } +} + +// groups lists the groups where the caller is an admin and the bot is +// present. Admin status is asked from Telegram, never taken from the app. +func (m *MiniApp) groups(w http.ResponseWriter, r *http.Request, s *session) { + ctx := r.Context() + list, err := m.Store.GroupsOfUser(ctx, s.user.ID, 50) + if err != nil { + m.explain(w, s, err) + return + } + out := []map[string]any{} + for _, g := range list { + if m.Admins.IsAdmin(ctx, g.ChatID, s.user.ID) { + out = append(out, m.groupJSON(ctx, g)) + } + } + m.ok(w, map[string]any{"groups": out}) +} + +// adminGroup loads the group of a request and checks that the caller is +// one of its admins. Every group endpoint goes through it. +func (m *MiniApp) adminGroup(w http.ResponseWriter, r *http.Request, s *session) (*db.Group, bool) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return nil, false + } + g, err := m.Store.GetGroup(r.Context(), id) + if err != nil || !g.Present() { + m.explain(w, s, db.ErrNotFound) + return nil, false + } + if !m.Admins.IsAdmin(r.Context(), id, s.user.ID) { + m.fail(w, http.StatusForbidden, "forbidden", m.I18n.T(s.lang, "notice.admins_only", nil)) + return nil, false + } + return g, true +} + +type settingsJSON struct { + Enabled bool `json:"enabled"` + AutoDetect bool `json:"auto_detect"` + DeleteCmds bool `json:"delete_commands"` + WhoCanUse string `json:"who_can_use"` + SpendRule string `json:"spend_rule"` + SpendCap int64 `json:"spend_cap"` + DailyCap int64 `json:"daily_cap"` + MaxSizeMB int64 `json:"max_size_mb"` + MaxDuration int64 `json:"max_duration"` + Quality string `json:"quality"` + Lang string `json:"lang"` + Allowed []string `json:"allowed"` + Blocked []string `json:"blocked"` +} + +func toSettingsJSON(st *db.GroupSettings) settingsJSON { + nonNil := func(v []string) []string { + if v == nil { + return []string{} + } + return v + } + return settingsJSON{ + Enabled: st.Enabled, AutoDetect: st.AutoDetect, DeleteCmds: st.DeleteCmds, WhoCanUse: st.WhoCanUse, + SpendRule: st.SpendRule, SpendCap: st.SpendCap, DailyCap: st.DailyCap, MaxSizeMB: st.MaxSizeMB, + MaxDuration: st.MaxDuration, Quality: st.Quality, Lang: st.Lang, + Allowed: nonNil(db.Sites(st.Allowed)), Blocked: nonNil(db.Sites(st.Blocked)), + } +} + +func (m *MiniApp) group(w http.ResponseWriter, r *http.Request, s *session) { + g, ok := m.adminGroup(w, r, s) + if !ok { + return + } + st, err := m.Store.GetGroupSettings(r.Context(), g.ChatID) + if err != nil { + m.explain(w, s, err) + return + } + out := m.groupJSON(r.Context(), g) + out["settings"] = toSettingsJSON(st) + out["tier_max_size_mb"] = m.Cfg.Limits.Paid.MaxSizeMB + out["tier_max_duration"] = int64(m.Cfg.Limits.Paid.MaxDuration.D().Seconds()) + m.ok(w, out) +} + +func cleanHosts(in []string) (string, bool) { + var out []string + seen := map[string]bool{} + for _, raw := range in { + h := groups.CleanHost(raw) + if h == "" { + return "", false + } + if !seen[h] { + seen[h] = true + out = append(out, h) + } + } + if len(out) > 50 { + return "", false + } + return strings.Join(out, ","), true +} + +// groupSettings replaces a group's settings. Every field is validated: +// the front end is not trusted to send sane values. +func (m *MiniApp) groupSettings(w http.ResponseWriter, r *http.Request, s *session) { + g, ok := m.adminGroup(w, r, s) + if !ok { + return + } + var in settingsJSON + if err := decode(r, &in); err != nil { + m.fail(w, http.StatusBadRequest, "bad_request", "") + return + } + bad := func() { + m.fail(w, http.StatusBadRequest, "bad_request", m.I18n.T(s.lang, "app.error.bad_settings", nil)) + } + switch in.WhoCanUse { + case db.UseEveryone, db.UsePassHolders, db.UseAdmins: + default: + bad() + return + } + switch in.SpendRule { + case db.SpendAnyone, db.SpendAdmins, db.SpendCapped: + default: + bad() + return + } + tier := m.Cfg.Limits.Paid + if in.SpendCap < 0 || in.SpendCap > billing.MaxAmount || in.DailyCap < 0 || in.DailyCap > billing.MaxAmount || + in.MaxSizeMB < 0 || in.MaxDuration < 0 { + bad() + return + } + // Caps go up to the group's tier and no further. + if tier.MaxSizeMB > 0 && in.MaxSizeMB > tier.MaxSizeMB { + in.MaxSizeMB = tier.MaxSizeMB + } + if max := int64(tier.MaxDuration.D().Seconds()); max > 0 && in.MaxDuration > max { + in.MaxDuration = max + } + if in.Quality != "" { + if p, err := media.Parse(in.Quality); err != nil || (p.Kind() != media.KindVideo && p.Kind() != media.KindAudio) { + bad() + return + } + } + if in.Lang != "" { + known := false + for _, l := range m.I18n.Langs() { + known = known || l == in.Lang + } + if !known { + bad() + return + } + } + allowed, ok1 := cleanHosts(in.Allowed) + blocked, ok2 := cleanHosts(in.Blocked) + if !ok1 || !ok2 { + bad() + return + } + st := &db.GroupSettings{ + ChatID: g.ChatID, Enabled: in.Enabled, AutoDetect: in.AutoDetect, DeleteCmds: in.DeleteCmds, + WhoCanUse: in.WhoCanUse, SpendRule: in.SpendRule, SpendCap: in.SpendCap, DailyCap: in.DailyCap, + MaxSizeMB: in.MaxSizeMB, MaxDuration: in.MaxDuration, Quality: in.Quality, Lang: in.Lang, + Allowed: allowed, Blocked: blocked, + } + if err := m.Store.SaveGroupSettings(r.Context(), st); err != nil { + m.explain(w, s, err) + return + } + m.Log.Info("group settings changed in the mini app", "chat_id", g.ChatID, "by", s.user.ID) + m.ok(w, map[string]any{"settings": toSettingsJSON(st)}) +} + +func (m *MiniApp) groupUsage(w http.ResponseWriter, r *http.Request, s *session) { + g, ok := m.adminGroup(w, r, s) + if !ok { + return + } + since := service.Day(m.Now().AddDate(0, 0, -6)) + usage, err := m.Store.GroupUsage(r.Context(), g.ChatID, since, 100) + if err != nil { + m.explain(w, s, err) + return + } + type row struct { + Name string `json:"name"` + Downloads int64 `json:"downloads"` + Sats int64 `json:"sats"` + Bytes int64 `json:"bytes"` + } + rows := []row{} + for _, u := range usage { + name := u.Name + if name == "" { + name = strconv.FormatInt(u.UserID, 10) + } + rows = append(rows, row{Name: name, Downloads: u.Downloads, Sats: u.Sats, Bytes: u.Bytes}) + } + m.ok(w, map[string]any{"days": 7, "members": rows}) +} diff --git a/internal/app/app.go b/internal/app/app.go index 9d9149f..f38e96d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -32,6 +32,7 @@ import ( "github.com/noderunners/dlbot/internal/worker" "github.com/noderunners/dlbot/internal/ytdlp" "github.com/noderunners/dlbot/locales" + "github.com/noderunners/dlbot/web/miniapp" ) // Options configure a core instance. @@ -281,6 +282,12 @@ func New(ctx context.Context, opts Options) (*App, error) { a.HTTP.RegisterWorkerAPI(&api.WorkerAPI{ Store: a.Store, Sched: a.Sched, Storage: a.Storage, Broker: a.Broker, Log: log, }) + if cfg.MiniAppEnabled() { + a.HTTP.RegisterMiniApp(&api.MiniApp{ + Cfg: cfg, Store: a.Store, Billing: a.Billing, Service: a.Service, Bot: a.Bot, I18n: tr, + Admins: a.Bot.Admins(), Log: log, Static: miniapp.FS(), + }) + } if cfg.Worker.Embedded { a.worker = worker.New(worker.Config{ diff --git a/internal/app/miniapp_test.go b/internal/app/miniapp_test.go new file mode 100644 index 0000000..75907d6 --- /dev/null +++ b/internal/app/miniapp_test.go @@ -0,0 +1,768 @@ +package app_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/api" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +// These tests drive the Mini App the way its front end does: plain HTTP +// against the real API of a running core, with initData signed by the +// bot token like Telegram signs it. + +func startApp(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *moneyHarness { + t.Helper() + return startGroup(t, fake, func(c *config.Config) { + c.MiniApp = true + if mut != nil { + mut(c) + } + }) +} + +type appReply struct { + Status int + Body map[string]any + Raw string +} + +func (r appReply) str(key string) string { s, _ := r.Body[key].(string); return s } +func (r appReply) num(key string) int64 { + f, _ := r.Body[key].(float64) + return int64(f) +} +func (r appReply) list(key string) []map[string]any { + var out []map[string]any + items, _ := r.Body[key].([]any) + for _, it := range items { + if m, ok := it.(map[string]any); ok { + out = append(out, m) + } + } + return out +} + +func initDataFor(user int64) string { + return api.SignInitData(fakeserver.Token, api.InitUser{ID: user, FirstName: "User", LanguageCode: "en"}, time.Now(), "") +} + +// rawCall makes one request with the given Authorization header. +func (h *moneyHarness) rawCall(auth, method, path string, body any) appReply { + h.t.Helper() + var rd io.Reader + if body != nil { + b, _ := json.Marshal(body) + rd = bytes.NewReader(b) + } + req, err := http.NewRequest(method, h.cfg.PublicURL+"/app/api/"+path, rd) + if err != nil { + h.t.Fatal(err) + } + if auth != "" { + req.Header.Set("Authorization", auth) + } + req.Header.Set("Accept-Language", "en-US,en;q=0.9") + res, err := http.DefaultClient.Do(req) + if err != nil { + h.t.Fatalf("%s %s: %v", method, path, err) + } + defer res.Body.Close() + raw, _ := io.ReadAll(res.Body) + out := appReply{Status: res.StatusCode, Raw: string(raw)} + _ = json.Unmarshal(raw, &out.Body) + return out +} + +// call makes a request as a Telegram user. +func (h *moneyHarness) call(user int64, method, path string, body any) appReply { + h.t.Helper() + return h.rawCall("tma "+initDataFor(user), method, path, body) +} + +// must is call, failing the test unless the answer is 200. +func (h *moneyHarness) must(user int64, method, path string, body any) appReply { + h.t.Helper() + r := h.call(user, method, path, body) + if r.Status != http.StatusOK { + h.t.Fatalf("%s %s as %d: status %d, body %s", method, path, user, r.Status, r.Raw) + } + return r +} + +// refused asserts that a call fails with the given status and error code. +func (h *moneyHarness) refused(r appReply, status int, code string) { + h.t.Helper() + if r.Status != status || r.str("error") != code { + h.t.Fatalf("status %d error %q, want %d %q (body %s)", r.Status, r.str("error"), status, code, r.Raw) + } +} + +// meetGroup makes the bot see a user in the test group, which is how it +// learns that the group exists and who is in it. +func (h *moneyHarness) meetGroup(users ...int64) { + h.t.Helper() + for _, u := range users { + seq := h.srv.Seq() + h.srv.PushMessage(group, u, "/queue") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group }) + } +} + +var appRoutes = []struct{ method, path string }{ + {"GET", "me"}, {"PUT", "me"}, {"GET", "i18n"}, {"POST", "probe"}, {"POST", "download"}, + {"GET", "queue"}, {"POST", "queue/x/cancel"}, {"POST", "queue/x/prioritize"}, + {"GET", "history"}, {"POST", "history/x/resend"}, {"GET", "products"}, + {"POST", "purchase"}, {"GET", "purchase/x"}, {"POST", "purchase/x/cancel"}, + {"GET", "groups"}, {"GET", "groups/-1001234567890"}, {"PUT", "groups/-1001234567890/settings"}, + {"GET", "groups/-1001234567890/usage"}, +} + +// --- acceptance: initData is validated on every call ----------------------- + +func TestMiniAppRefusesCallsWithoutValidInitData(t *testing.T) { + h := startApp(t, nil, nil) + good := initDataFor(alice) + forged := api.SignInitData("987654321:OTHERotherOTHERotherOTHERotherOTHER-01", api.InitUser{ID: alice, FirstName: "User"}, time.Now(), "") + stale := api.SignInitData(fakeserver.Token, api.InitUser{ID: alice, FirstName: "User"}, time.Now().Add(-48*time.Hour), "") + // The same signature, claiming to be somebody else. + swapped := strings.Replace(good, "%22id%22%3A42", "%22id%22%3A43", 1) + if swapped == good { + t.Fatal("test setup: the user ID was not found in the init data") + } + + bad := map[string]string{ + "no header": "", + "empty init data": "tma ", + "wrong scheme": "Bearer " + good, + "another bot's data": "tma " + forged, + "two days old": "tma " + stale, + "user swapped": "tma " + swapped, + "garbage": "tma hash=zz&user=%7B%7D", + } + for _, rt := range appRoutes { + for name, auth := range bad { + r := h.rawCall(auth, rt.method, rt.path, map[string]any{}) + if r.Status != http.StatusUnauthorized || r.str("error") != "unauthorized" { + t.Errorf("%s %s with %s: status %d body %s", rt.method, rt.path, name, r.Status, r.Raw) + } + } + } + // The refusal is a sentence a person can read, from the catalog. + if r := h.rawCall("", "GET", "me", nil); !strings.Contains(r.str("message"), "Open this page from Telegram") { + t.Fatalf("refusal message = %q", r.str("message")) + } + // Nothing was created for the callers that were turned away. + if _, err := h.app.Store.GetUser(context.Background(), alice); err == nil { + t.Fatal("a refused call created a user") + } + + me := h.must(alice, "GET", "me", nil) + if me.num("id") != alice || me.str("lang") != "en" || me.str("dir") != "ltr" || me.str("source") != "free" { + t.Fatalf("me = %s", me.Raw) + } + // A banned user is locked out of the app like out of the chat. + if ok, err := h.app.Store.SetUserBanned(context.Background(), alice, true); err != nil || !ok { + t.Fatal(ok, err) + } + h.refused(h.call(alice, "GET", "me", nil), http.StatusForbidden, "forbidden") +} + +func TestMiniAppIsServedFromTheBinary(t *testing.T) { + h := startApp(t, nil, nil) + get := func(path string, hdr ...string) (*http.Response, string) { + req, _ := http.NewRequest("GET", h.cfg.PublicURL+path, nil) + for i := 0; i+1 < len(hdr); i += 2 { + req.Header.Set(hdr[i], hdr[i+1]) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return res, string(b) + } + res, index := get("/app/") + if res.StatusCode != 200 || !strings.Contains(index, "telegram-web-app.js") || !strings.Contains(index, `id="root"`) { + t.Fatalf("/app/ = %d %q", res.StatusCode, index) + } + if !strings.HasPrefix(res.Header.Get("Content-Type"), "text/html") { + t.Fatalf("content type = %q", res.Header.Get("Content-Type")) + } + if csp := res.Header.Get("Content-Security-Policy"); !strings.Contains(csp, "frame-ancestors") { + t.Fatalf("no content security policy: %q", csp) + } + // Every script and style the page names is in the binary too. + for _, part := range strings.Split(index, `"`) { + if strings.HasPrefix(part, "/app/assets/") { + if r, body := get(part); r.StatusCode != 200 || len(body) == 0 { + t.Errorf("%s = %d, %d bytes", part, r.StatusCode, len(body)) + } + } + } + // A deep path is the app's business: it gets the same page. + if r, body := get("/app/groups/123"); r.StatusCode != 200 || body != index { + t.Fatalf("deep path = %d", r.StatusCode) + } + // A client that has the current build is told so. + etag := res.Header.Get("ETag") + if etag == "" { + t.Fatal("no ETag") + } + if r, _ := get("/app/", "If-None-Match", etag); r.StatusCode != http.StatusNotModified { + t.Fatalf("revalidation = %d, want 304", r.StatusCode) + } +} + +// --- acceptance: buy ------------------------------------------------------- + +func TestMiniAppBuyPass(t *testing.T) { + h := startApp(t, nil, nil) + + products := h.must(alice, "GET", "products", nil) + if products.Body["enabled"] != true || len(products.list("passes")) != 3 { + t.Fatalf("products = %s", products.Raw) + } + + seq := h.srv.Seq() + // The amount sent with a pass is ignored: the price list is the core's. + p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "pass_week", "amount": 1}) + inv, ok := h.ln.WaitInvoice(1, 5*time.Second) + if !ok { + t.Fatal("no invoice was created") + } + if inv.AmountSats != 3000 || p.num("amount") != 3000 || p.str("status") != "pending" { + t.Fatalf("invoice %d sats, purchase %s", inv.AmountSats, p.Raw) + } + if p.str("bolt11") != inv.Bolt11 || !strings.HasPrefix(p.str("qr"), "data:image/png;base64,") { + t.Fatalf("purchase lacks the invoice or its QR code: %.200s", p.Raw) + } + id := p.str("id") + + if st := h.must(alice, "GET", "purchase/"+id, nil); st.str("status") != "pending" { + t.Fatalf("status before paying = %s", st.Raw) + } + // Somebody else cannot watch or cancel this purchase. + h.refused(h.call(bob, "GET", "purchase/"+id, nil), http.StatusNotFound, "not_found") + h.refused(h.call(bob, "POST", "purchase/"+id+"/cancel", nil), http.StatusNotFound, "not_found") + + h.pay(inv) + // The app notices by asking: no webhook is needed for this to work. + var st appReply + deadline := time.Now().Add(5 * time.Second) + for { + st = h.must(alice, "GET", "purchase/"+id, nil) + if st.str("status") == "paid" { + break + } + if time.Now().After(deadline) { + t.Fatalf("the purchase never became paid: %s", st.Raw) + } + time.Sleep(20 * time.Millisecond) + } + week := int64(7 * 24 * time.Hour / time.Millisecond) + if until := st.num("pass_until"); until < db.NowMilli()+week-60_000 || until > db.NowMilli()+week+60_000 { + t.Fatalf("pass_until = %d, want a week from now", until) + } + if st.Body["bolt11"] != nil { + t.Fatal("a settled purchase still carries its invoice") + } + me := h.must(alice, "GET", "me", nil) + if me.str("source") != "own_pass" || me.num("pass_until") != st.num("pass_until") { + t.Fatalf("me after buying = %s", me.Raw) + } + // The chat gets a receipt as well. + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Paid") }) + h.booksBalance() +} + +func TestMiniAppPollingAloneSettlesAPurchase(t *testing.T) { + // No webhook reaches the core here, and its own poller is an hour + // away. The app's status calls are what settle the payment. + h := startApp(t, nil, func(c *config.Config) { c.LNbits.WebhookSecret = "" }) + p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 500}) + inv, ok := h.ln.WaitInvoice(1, 5*time.Second) + if !ok || inv.AmountSats != 500 { + t.Fatalf("invoice = %+v", inv) + } + h.pay(inv) + st := h.must(alice, "GET", "purchase/"+p.str("id"), nil) + if st.str("status") != "paid" || st.num("balance") != 500 { + t.Fatalf("status after paying = %s", st.Raw) + } + // Asking again does not credit again. + h.must(alice, "GET", "purchase/"+p.str("id"), nil) + if got := h.balance(alice); got != 500 { + t.Fatalf("balance = %d, want 500", got) + } + h.booksBalance() +} + +func TestMiniAppRefusesWhatItDoesNotSell(t *testing.T) { + h := startApp(t, nil, nil) + for _, body := range []map[string]any{ + {"target": "me", "product": "yacht"}, + {"target": "me", "product": "one_off"}, // needs a download behind it + {"target": "me", "product": "skip_queue"}, // needs a waiting job behind it + {"target": "me", "product": "donation", "amount": 100}, // not sold in the app + {"target": "me", "product": "credits", "amount": -5}, // not an amount + {"target": "me", "product": "credits", "amount": 1 << 50}, // absurd + {"target": "-1009999", "product": "pass_day"}, // a group the bot is not in + } { + if r := h.call(alice, "POST", "purchase", body); r.Status == http.StatusOK { + t.Errorf("purchase %v was accepted: %s", body, r.Raw) + } + } + h.refused(h.call(alice, "POST", "purchase", map[string]any{"target": "42", "product": "pass_day"}), http.StatusBadRequest, "bad_request") + if n := len(h.ln.Invoices()); n != 0 { + t.Fatalf("%d invoices were created for refused purchases", n) + } +} + +func TestMiniAppBuyCreditsForAGroup(t *testing.T) { + h := startApp(t, nil, nil) + h.meetGroup(bob) + gid := strconv.FormatInt(group, 10) + + groups := h.must(bob, "GET", "groups", nil).list("groups") + if len(groups) != 1 || groups[0]["id"] != gid { + t.Fatalf("bob's groups = %v", groups) + } + p := h.must(bob, "POST", "purchase", map[string]any{"target": gid, "product": "credits", "amount": 1000}) + inv, ok := h.ln.WaitInvoice(1, 5*time.Second) + if !ok || inv.AmountSats != 1000 { + t.Fatalf("invoice = %+v", inv) + } + h.pay(inv) + deadline := time.Now().Add(5 * time.Second) + for h.must(bob, "GET", "purchase/"+p.str("id"), nil).str("status") != "paid" { + if time.Now().After(deadline) { + t.Fatal("the group purchase never became paid") + } + time.Sleep(20 * time.Millisecond) + } + if got := h.groupWallet().Balance; got != 1000 { + t.Fatalf("group balance = %d, want 1000", got) + } + if got := h.balance(bob); got != 0 { + t.Fatalf("the buyer's own balance = %d, want 0", got) + } + detail := h.must(bob, "GET", "groups/"+gid, nil) + if detail.num("balance") != 1000 { + t.Fatalf("group detail = %s", detail.Raw) + } + h.booksBalance() +} + +// --- acceptance: history resend -------------------------------------------- + +func TestMiniAppHistoryResend(t *testing.T) { + h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) + h.fetch(alice, link) + + items := h.must(alice, "GET", "history", nil).list("items") + if len(items) != 1 || items[0]["title"] != "Test Video" || items[0]["profile"] != "best" { + t.Fatalf("history = %v", items) + } + id, _ := items[0]["id"].(string) + + // History is personal. + if got := h.must(bob, "GET", "history", nil).list("items"); len(got) != 0 { + t.Fatalf("bob sees %d items of alice's history", len(got)) + } + h.refused(h.call(bob, "POST", "history/"+id+"/resend", nil), http.StatusNotFound, "not_found") + + seq := h.srv.Seq() + h.must(alice, "POST", "history/"+id+"/resend", nil) + again := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + if again.Params["video"] == "" || len(again.Files) != 0 { + t.Fatalf("the resend should reuse Telegram's copy: params %v, %d uploads", again.Params, len(again.Files)) + } + h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") }) + // One real download happened, and both deliveries count as usage. + if n := len(h.fake.Downloads()); n != 1 { + t.Fatalf("%d downloads ran, want 1", n) + } + if u := h.usage(alice); u.Downloads != 2 { + t.Fatalf("usage = %+v, want 2 downloads: a resend is a download", u) + } + if got := h.must(alice, "GET", "history", nil).list("items"); len(got) != 2 { + t.Fatalf("history has %d items after the resend, want 2", len(got)) + } +} + +func TestMiniAppResendObeysTheDailyLimit(t *testing.T) { + h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, func(c *config.Config) { c.Limits.Free.DailyDownloads = 1 }) + h.fetch(alice, link) + id, _ := h.must(alice, "GET", "history", nil).list("items")[0]["id"].(string) + + seq := h.srv.Seq() + r := h.call(alice, "POST", "history/"+id+"/resend", nil) + h.refused(r, http.StatusUnprocessableEntity, "limit.daily_downloads") + if r.Body["upgradable"] != true || r.str("message") == "" { + t.Fatalf("refusal = %s", r.Raw) + } + h.never(seq, "sendVideo|sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) +} + +// --- acceptance: download and queue cancel --------------------------------- + +func TestMiniAppDownloadAndCancel(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startApp(t, &ytdlptest.Fake{Block: block, FileSize: 3000}, nil) + + probe := h.must(alice, "POST", "probe", map[string]any{"url": link}) + if probe.str("title") != "Test Video" || probe.num("duration") != 60 || len(probe.list("options")) < 2 { + t.Fatalf("probe = %s", probe.Raw) + } + h.refused(h.call(alice, "POST", "probe", map[string]any{"url": "not a link"}), http.StatusUnprocessableEntity, "bad_link") + h.refused(h.call(alice, "POST", "probe", map[string]any{"url": "http://127.0.0.1/x"}), http.StatusUnprocessableEntity, "bad_link") + + seq := h.srv.Seq() + h.must(alice, "POST", "download", map[string]any{"url": probe.str("url"), "profile": "best"}) + // The status lives in the chat, like for a download started there. + status := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + h.waitJobs(db.JobRunning, 1) + + var jobs []map[string]any + deadline := time.Now().Add(5 * time.Second) + for { + jobs = h.must(alice, "GET", "queue", nil).list("jobs") + if len(jobs) == 1 && jobs[0]["status"] == "running" { + break + } + if time.Now().After(deadline) { + t.Fatalf("queue = %v", jobs) + } + time.Sleep(20 * time.Millisecond) + } + if jobs[0]["title"] != "Test Video" || jobs[0]["can_cancel"] != true || jobs[0]["can_prioritize"] != false { + t.Fatalf("job = %v", jobs[0]) + } + id, _ := jobs[0]["id"].(string) + + // The queue is personal, and so is the right to cancel. + if got := h.must(bob, "GET", "queue", nil).list("jobs"); len(got) != 0 { + t.Fatalf("bob sees alice's queue: %v", got) + } + h.refused(h.call(bob, "POST", "queue/"+id+"/cancel", nil), http.StatusNotFound, "not_found") + h.waitJobs(db.JobRunning, 1) + + seq = h.srv.Seq() + h.must(alice, "POST", "queue/"+id+"/cancel", nil) + h.wait(seq, edits, func(c fakeserver.Call) bool { + return c.MessageID == status.MessageID && strings.Contains(c.Text(), "Cancelled") + }) + h.waitJobs(db.JobCancelled, 1) + if got := h.must(alice, "GET", "queue", nil).list("jobs"); len(got) != 0 { + t.Fatalf("queue after cancel = %v", got) + } + if u := h.usage(alice); u.Downloads != 0 { + t.Fatalf("a cancelled download was counted: %+v", u) + } + h.never(seq, "sendVideo", nil) +} + +func TestMiniAppCannotDownloadPastTheLimits(t *testing.T) { + h := startApp(t, nil, nil) + seq := h.srv.Seq() + // The front end offers every format. The core still says no. + r := h.call(alice, "POST", "download", map[string]any{"url": bigLink, "profile": "best"}) + h.refused(r, http.StatusUnprocessableEntity, "limit.too_large") + if r.Body["upgradable"] != true || !strings.Contains(r.str("message"), "MB") { + t.Fatalf("refusal = %s", r.Raw) + } + h.never(seq, "sendMessage|sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)); n != 0 { + t.Fatalf("%d jobs exist after a refusal", n) + } + h.refused(h.call(alice, "POST", "download", map[string]any{"url": link, "profile": "8k"}), http.StatusUnprocessableEntity, "bad_link") +} + +func TestMiniAppPrioritize(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startApp(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) + h.queued() // alice's job runs, bob's waits behind it + + jobs := h.must(bob, "GET", "queue", nil).list("jobs") + if len(jobs) != 1 || jobs[0]["status"] != "queued" || jobs[0]["can_prioritize"] != true || jobs[0]["skip_price"] != float64(50) { + t.Fatalf("bob's queue = %v", jobs) + } + if pos, _ := jobs[0]["position"].(float64); pos != 1 { + t.Fatalf("position = %v, want 1", jobs[0]["position"]) + } + id, _ := jobs[0]["id"].(string) + h.refused(h.call(alice, "POST", "queue/"+id+"/prioritize", nil), http.StatusNotFound, "not_found") + + // Without credits the answer is an invoice, and paying it promotes. + r := h.must(bob, "POST", "queue/"+id+"/prioritize", nil) + purchase, _ := r.Body["purchase"].(map[string]any) + if r.Body["done"] != false || purchase == nil || purchase["amount"] != float64(50) || purchase["bolt11"] == "" { + t.Fatalf("prioritize = %s", r.Raw) + } + inv, ok := h.ln.WaitInvoice(1, 5*time.Second) + if !ok { + t.Fatal("no invoice") + } + h.pay(inv) + deadline := time.Now().Add(5 * time.Second) + for { + if q := h.jobs(db.JobQueued); len(q) == 1 && q[0].Lane == db.LanePaid { + break + } + if time.Now().After(deadline) { + t.Fatal("the job was not promoted after payment") + } + time.Sleep(20 * time.Millisecond) + } + if jobs = h.must(bob, "GET", "queue", nil).list("jobs"); len(jobs) != 1 || jobs[0]["can_prioritize"] != false { + t.Fatalf("queue after promotion = %v", jobs) + } + h.booksBalance() +} + +func TestMiniAppPrioritizeWithCredits(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := startApp(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) + h.grant(bob, 40) // not enough for a paid download, so bob queues as free + h.queued() + h.grant(bob, 20) // now 60 + + id, _ := h.must(bob, "GET", "queue", nil).list("jobs")[0]["id"].(string) + r := h.must(bob, "POST", "queue/"+id+"/prioritize", nil) + if r.Body["done"] != true || r.Body["purchase"] != nil { + t.Fatalf("prioritize = %s", r.Raw) + } + if q := h.jobs(db.JobQueued); len(q) != 1 || q[0].Lane != db.LanePaid { + t.Fatalf("the job was not promoted: %+v", q) + } + if got := h.balance(bob); got != 10 { + t.Fatalf("balance = %d, want 10", got) + } + // A second press finds nothing left to promote and charges nothing. + h.refused(h.call(bob, "POST", "queue/"+id+"/prioritize", nil), http.StatusUnprocessableEntity, "too_late") + if got := h.balance(bob); got != 10 { + t.Fatalf("balance after a second press = %d, want 10", got) + } + if n := len(h.ln.Invoices()); n != 0 { + t.Fatalf("%d invoices, want none", n) + } + h.booksBalance() +} + +// --- acceptance: group settings -------------------------------------------- + +func TestMiniAppGroupSettingsAreForAdmins(t *testing.T) { + h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) + h.meetGroup(alice, bob) + gid := strconv.FormatInt(group, 10) + path := "groups/" + gid + + // Alice is a member, not an admin: the group is not hers to manage. + if got := h.must(alice, "GET", "groups", nil).list("groups"); len(got) != 0 { + t.Fatalf("alice's groups = %v", got) + } + change := map[string]any{ + "enabled": true, "auto_detect": true, "delete_commands": false, "who_can_use": "admins", + "spend_rule": "capped", "spend_cap": 200, "daily_cap": 5000, "max_size_mb": 20, "max_duration": 600, + "quality": "720", "lang": "en", + "allowed": []string{}, "blocked": []string{"https://www.Example.ORG/some/page", "example.org"}, + } + h.refused(h.call(alice, "GET", path, nil), http.StatusForbidden, "forbidden") + h.refused(h.call(alice, "GET", path+"/usage", nil), http.StatusForbidden, "forbidden") + h.refused(h.call(alice, "PUT", path+"/settings", change), http.StatusForbidden, "forbidden") + if st := h.settings(nil); st.WhoCanUse != db.UseEveryone || st.AutoDetect { + t.Fatalf("a refused change was applied: %+v", st) + } + // A group that does not exist looks the same to everybody. + h.refused(h.call(bob, "GET", "groups/-1009", nil), http.StatusNotFound, "not_found") + + before := h.must(bob, "GET", path, nil) + settings, _ := before.Body["settings"].(map[string]any) + if before.str("title") == "" || settings["who_can_use"] != "everyone" || settings["spend_rule"] != "admins" { + t.Fatalf("group detail = %s", before.Raw) + } + + saved := h.must(bob, "PUT", path+"/settings", change) + settings, _ = saved.Body["settings"].(map[string]any) + if fmt.Sprint(settings["blocked"]) != "[example.org]" { + t.Fatalf("blocked sites were not cleaned: %v", settings["blocked"]) + } + st := h.settings(nil) + if !st.AutoDetect || st.WhoCanUse != db.UseAdmins || st.SpendRule != db.SpendCapped || st.SpendCap != 200 || + st.DailyCap != 5000 || st.MaxSizeMB != 20 || st.MaxDuration != 600 || st.Quality != "720" || st.Lang != "en" || + st.Blocked != "example.org" { + t.Fatalf("stored settings = %+v", st) + } + + // The change is live in the chat: only admins may use the bot now. + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl https://example.com/for-admins") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return c.ChatID() == group && strings.Contains(c.Text(), "admins") + }) + h.never(seq, "sendPhoto", nil) + + // Nonsense is refused whole, and a cap above the tier is lowered to it. + for field, value := range map[string]any{ + "who_can_use": "root", "spend_rule": "everything", "spend_cap": -1, "daily_cap": -1, + "max_size_mb": -3, "quality": "thumb", "lang": "tlh", "blocked": []string{"not a host!"}, + } { + bad := map[string]any{} + for k, v := range change { + bad[k] = v + } + bad[field] = value + h.refused(h.call(bob, "PUT", path+"/settings", bad), http.StatusBadRequest, "bad_request") + } + if got := h.settings(nil); got.WhoCanUse != db.UseAdmins || got.MaxSizeMB != 20 { + t.Fatalf("a refused change was applied: %+v", got) + } + change["max_size_mb"] = 999999 + h.must(bob, "PUT", path+"/settings", change) + if got := h.settings(nil).MaxSizeMB; got != h.cfg.Limits.Paid.MaxSizeMB { + t.Fatalf("max size = %d MB, want the tier's %d", got, h.cfg.Limits.Paid.MaxSizeMB) + } + + // An admin who is demoted loses access with the next check. + h.srv.SetMember(group, bob, "member") + h.app.Bot.Admins().Forget(group) + h.refused(h.call(bob, "GET", path, nil), http.StatusForbidden, "forbidden") +} + +func TestMiniAppGroupUsage(t *testing.T) { + h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) + h.groupFetch(alice, link) + h.meetGroup(bob) + usage := h.must(bob, "GET", "groups/"+strconv.FormatInt(group, 10)+"/usage", nil) + members := usage.list("members") + if usage.num("days") != 7 || len(members) != 1 || members[0]["downloads"] != float64(1) || members[0]["bytes"] != float64(3000) { + t.Fatalf("usage = %s", usage.Raw) + } +} + +// --- preferences and texts ------------------------------------------------- + +func TestMiniAppPreferences(t *testing.T) { + h := startApp(t, nil, nil) + ctx := context.Background() + + h.must(alice, "PUT", "me", map[string]any{"quality": "720"}) + if me := h.must(alice, "GET", "me", nil); me.str("quality") != "720" { + t.Fatalf("me = %s", me.Raw) + } + // A default format has to be a video or audio format. + h.refused(h.call(alice, "PUT", "me", map[string]any{"quality": "thumb"}), http.StatusBadRequest, "bad_request") + h.refused(h.call(alice, "PUT", "me", map[string]any{"lang": "tlh"}), http.StatusBadRequest, "bad_request") + h.must(alice, "PUT", "me", map[string]any{"quality": ""}) + + h.must(alice, "PUT", "me", map[string]any{"lang": "en"}) + u, err := h.app.Store.GetUser(ctx, alice) + if err != nil || u.LangOverride != "en" || u.Quality != "" { + t.Fatalf("user = %+v, %v", u, err) + } + h.must(alice, "PUT", "me", map[string]any{"lang": "auto"}) + if u, _ = h.app.Store.GetUser(ctx, alice); u.LangOverride != "" { + t.Fatalf("language override = %q, want none", u.LangOverride) + } + + me := h.must(alice, "GET", "me", nil) + if !strings.HasSuffix(me.str("referral_link"), "?start=ref_42") || len(me.list("languages")) == 0 { + t.Fatalf("me = %s", me.Raw) + } +} + +func TestMiniAppTextsComeFromTheCatalog(t *testing.T) { + h := startApp(t, nil, nil) + r := h.must(alice, "GET", "i18n", nil) + msgs, _ := r.Body["messages"].(map[string]any) + if r.str("lang") != "en" || r.str("dir") != "ltr" { + t.Fatalf("i18n = %.200s", r.Raw) + } + if msgs["app.tab.home"] != "Home" || msgs["product.pass_week"] != "Week pass" { + t.Fatalf("messages lack basic entries: %v, %v", msgs["app.tab.home"], msgs["product.pass_week"]) + } + // Placeholders arrive in the form the app fills in, plurals as forms. + if msgs["app.pass_until"] != "Pass until {Until}" { + t.Fatalf("placeholder form = %v", msgs["app.pass_until"]) + } + forms, _ := msgs["unit.sats"].(map[string]any) + if forms["one"] != "{N} sat" || forms["other"] != "{N} sats" { + t.Fatalf("plural forms = %v", msgs["unit.sats"]) + } +} + +// --- the way into the app from the chat ------------------------------------ + +func TestChatPointsToTheMiniApp(t *testing.T) { + h := startApp(t, nil, nil) + appURL := h.cfg.PublicURL + "/app/" + + // In private the button opens the app in place. + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/app") + msg := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) + if b := msg.Buttons(); len(b) != 1 || b[0].WebApp == nil || b[0].WebApp.URL != appURL { + t.Fatalf("/app in private = %+v", msg.Buttons()) + } + + // Telegram refuses web app buttons in groups, so there it is a link + // to the bot's main Mini App. + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/app") + msg = h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group }) + if b := msg.Buttons(); len(b) != 1 || b[0].WebApp != nil || b[0].URL != "https://t.me/"+fakeserver.BotUsername+"?startapp" { + t.Fatalf("/app in a group = %+v", msg.Buttons()) + } + + // A refused download offers the shop inside the app as well. + card := h.card(alice, alice, bigLink) + seq = h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && len(c.Buttons()) > 0 }) + var open *fakeserver.Button + for _, b := range offer.Buttons() { + if b.WebApp != nil { + open = &b + } + } + if open == nil || open.Text != "Open app" || open.WebApp.URL != appURL+"?page=buy" { + t.Fatalf("the offer has no way into the app: %+v", offer.Buttons()) + } +} + +func TestChatHidesTheMiniAppWhenItIsOff(t *testing.T) { + h := startGroup(t, nil, nil) // MINIAPP_ENABLED is not set + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/app") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "not set up") && len(c.Buttons()) == 0 + }) + card := h.card(alice, alice, bigLink) + seq = h.press(alice, alice, card, "dl:") + offer := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && len(c.Buttons()) > 0 }) + for _, b := range offer.Buttons() { + if b.WebApp != nil { + t.Fatalf("a web app button without a Mini App: %+v", b) + } + } + // The API is not there either. + if r := h.call(alice, "GET", "me", nil); r.Status != http.StatusNotFound { + t.Fatalf("the Mini App API answers with %d while the app is off", r.Status) + } +} diff --git a/internal/app/stage_test.go b/internal/app/stage_test.go new file mode 100644 index 0000000..5179d63 --- /dev/null +++ b/internal/app/stage_test.go @@ -0,0 +1,76 @@ +package app_test + +import ( + "encoding/json" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +// TestMiniAppStage is not a test of its own. It holds a complete core +// (fake Telegram, fake LNbits, scripted yt-dlp) open so that a browser can +// be pointed at the Mini App: web/miniapp/e2e/smoke.mjs does that, and +// "make miniapp-e2e" runs the two together. +// +// It runs only when DLBOT_STAGE_DIR names a directory. It writes +// stage.json there (the URL, and signed initData per user) and stays up +// until a file named "stop" appears in the directory. Invoices are paid +// by themselves three seconds after they are created. +func TestMiniAppStage(t *testing.T) { + dir := os.Getenv("DLBOT_STAGE_DIR") + if dir == "" { + t.Skip("set DLBOT_STAGE_DIR to hold a core open for the browser test") + } + h := startApp(t, &ytdlptest.Fake{FileSize: 3000, Delay: 5 * time.Second}, func(c *config.Config) { + c.Worker.Concurrency = 1 + }) + h.meetGroup(alice, bob) + h.fetch(bob, link) // something for the history page + + stop := make(chan struct{}) + defer close(stop) + go func() { + seen := map[string]time.Time{} + for { + select { + case <-stop: + return + case <-time.After(200 * time.Millisecond): + } + for _, inv := range h.ln.Invoices() { + first, ok := seen[inv.PaymentHash] + if !ok { + seen[inv.PaymentHash] = time.Now() + } else if !first.IsZero() && time.Since(first) > 3*time.Second { + _ = h.ln.Pay(inv.PaymentHash) + seen[inv.PaymentHash] = time.Time{} + } + } + } + }() + + stage, _ := json.Marshal(map[string]any{ + "url": h.cfg.PublicURL + "/app/", + "group": strconv.FormatInt(group, 10), + "init_data": map[string]string{ + "member": initDataFor(alice), + "admin": initDataFor(bob), + }, + }) + if err := os.WriteFile(filepath.Join(dir, "stage.json"), stage, 0o600); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(15 * time.Minute) + for time.Now().Before(deadline) { + if _, err := os.Stat(filepath.Join(dir, "stop")); err == nil { + return + } + time.Sleep(200 * time.Millisecond) + } + t.Fatal("nobody stopped the stage") +} diff --git a/internal/bot/appops.go b/internal/bot/appops.go new file mode 100644 index 0000000..0ac9505 --- /dev/null +++ b/internal/bot/appops.go @@ -0,0 +1,258 @@ +package bot + +import ( + "context" + "errors" + "html" + "strconv" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/billing" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/ids" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +// This file is the bot's side of the Mini App. The app is another way to +// press the same buttons: every operation here goes through the same +// service calls as a chat message, so limits, prices and refunds are +// decided in one place. Files and status always arrive in the user's +// private chat with the bot. + +// AppJob is one active download as the Mini App shows it. +type AppJob struct { + ID string `json:"id"` + Title string `json:"title"` + Profile string `json:"profile"` + Status string `json:"status"` + Stage string `json:"stage,omitempty"` + Position int `json:"position,omitempty"` + WaitSeconds int `json:"wait_seconds,omitempty"` + Progress float64 `json:"progress"` + CanCancel bool `json:"can_cancel"` + CanPrioritize bool `json:"can_prioritize"` + SkipPrice int64 `json:"skip_price,omitempty"` +} + +// AppQueue lists a user's active downloads. +func (b *Bot) AppQueue(ctx context.Context, userID int64) ([]AppJob, error) { + dels, err := b.store.ActiveDeliveriesForUser(ctx, userID) + if err != nil { + return nil, err + } + out := []AppJob{} + for _, d := range dels { + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil { + continue + } + j := AppJob{ + ID: d.ID, Title: job.Title, Profile: job.Profile, Status: job.Status, Stage: job.Stage, + CanCancel: d.Status == db.DeliveryPending, + } + switch job.Status { + case db.JobQueued: + if pos, err := b.sched.Position(ctx, job, b.slots()); err == nil { + j.Position, j.WaitSeconds = pos.Ahead+1, int(pos.Wait.Seconds()) + } + if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 { + j.CanPrioritize, j.SkipPrice = true, b.cfg.Prices.SkipQueue + } + case db.JobRunning: + if job.TotalBytes > 0 { + j.Progress = float64(job.ProgressBytes) / float64(job.TotalBytes) + } + case db.JobDelivering: + j.Progress, j.Stage = 1, ytdlp.StageUploading + } + out = append(out, j) + } + return out, nil +} + +// AppProbe looks a link up for the paste box, after the same gate a chat +// message passes. +func (b *Bot) AppProbe(ctx context.Context, user *db.User, url string) (*service.CardInfo, error) { + who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} + if err := b.svc.Gate(ctx, who); err != nil { + return nil, err + } + if !b.rate.allow("u:"+itoa(user.ID), b.cfg.Rate.UserPerMinute, time.Minute) { + return nil, ErrRateLimited + } + return b.svc.Probe(ctx, url) +} + +// ErrRateLimited is returned when a user sends links too fast. +var ErrRateLimited = errors.New("bot: rate limited") + +// AppDownload starts a download from the Mini App. The status message and +// the file go to the user's private chat. +func (b *Bot) AppDownload(ctx context.Context, user *db.User, lang, url string, profile media.Profile) error { + who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} + if err := b.svc.Gate(ctx, who); err != nil { + return err + } + if !b.appStartAllowed(user.ID) { + return ErrRateLimited + } + info, err := b.svc.Probe(ctx, url) + if err != nil { + return err + } + return b.startInChat(ctx, user, lang, url, info, profile) +} + +// appStartAllowed bounds how fast the app may start downloads for a user. +// It is its own budget, twice the one for links: a lookup followed by a +// start is one download, and both are HTTP calls anyone can script. +func (b *Bot) appStartAllowed(userID int64) bool { + return b.rate.allow("as:"+itoa(userID), 2*b.cfg.Rate.UserPerMinute, time.Minute) +} + +// startInChat creates a request for a known link and starts it, with a +// fresh status message in the user's private chat. +func (b *Bot) startInChat(ctx context.Context, user *db.User, lang, url string, info *service.CardInfo, profile media.Profile) error { + who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} + // Refuse before a message is sent, so a refusal leaves nothing behind. + if err := b.svc.Preview(ctx, who, url, info, profile); err != nil { + return err + } + msg, err := b.send(ctx, user.ID, 0, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil) + if err != nil { + return err + } + req := &db.Request{ + ID: ids.New(), UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate, URL: url, + CardMessageID: int64(msg.MessageID), Status: db.RequestReady, Info: info.JSON(), Lang: lang, + } + if err := b.store.InsertRequest(ctx, req); err != nil { + return err + } + if err := b.startFromRequest(ctx, req, info, profile, nil); err != nil { + _ = b.edit(ctx, user.ID, req.CardMessageID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) + return err + } + return nil +} + +// AppResend sends a past download again. It is a new download with the +// usual limits; the cache usually makes it instant. +func (b *Bot) AppResend(ctx context.Context, user *db.User, lang, deliveryID string) error { + old, err := b.store.GetDelivery(ctx, deliveryID) + if err != nil || old.UserID != user.ID || old.Status != db.DeliverySent { + return db.ErrNotFound + } + job, err := b.store.GetJob(ctx, old.JobID) + if err != nil { + return db.ErrNotFound + } + orig, err := b.store.GetRequest(ctx, old.RequestID) + if err != nil { + return db.ErrNotFound + } + info, ierr := service.ParseCardInfo(orig.Info) + profile, perr := media.Parse(job.Profile) + if ierr != nil || perr != nil { + return db.ErrNotFound + } + info.Fresh = false + if !b.appStartAllowed(user.ID) { + return ErrRateLimited + } + return b.startInChat(ctx, user, lang, orig.URL, info, profile) +} + +// AppCancel cancels one of the user's downloads. +func (b *Bot) AppCancel(ctx context.Context, userID int64, deliveryID string) error { + err := b.cancelDelivery(ctx, deliveryID, userID) + if errors.Is(err, sched.ErrNotOwner) { + return db.ErrNotFound + } + return err +} + +// AppSkip moves a waiting download to the priority lane. With enough +// credits it is done at once. Otherwise an invoice is created and +// returned, and the promotion happens when it is paid. +func (b *Bot) AppSkip(ctx context.Context, user *db.User, lang, deliveryID string) (done bool, purchase *db.Purchase, err error) { + d, err := b.store.GetDelivery(ctx, deliveryID) + if err != nil || d.UserID != user.ID { + return false, nil, db.ErrNotFound + } + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree { + return false, nil, sched.ErrTooLate + } + if b.skipWithCredits(ctx, actor{user: user, lang: lang}, d, job, b.cfg.Prices.SkipQueue) { + b.refreshStatus(ctx, job.ID) + return true, nil, nil + } + p, err := b.AppPurchase(ctx, user, lang, 0, billing.ProductSkipQueue, 0, d.ID) + return false, p, err +} + +// AppPurchase creates an invoice from the Mini App. groupID 0 targets the +// user's own wallet, anything else that group's wallet. +func (b *Bot) AppPurchase(ctx context.Context, user *db.User, lang string, groupID int64, product string, amount int64, deliveryID string) (*db.Purchase, error) { + if !billing.ValidProduct(product) { + return nil, billing.ErrBadProduct + } + // Every invoice is a call to the payment backend. A person needs a + // few per minute at most. + if !b.rate.allow("ap:"+itoa(user.ID), 10, time.Minute) { + return nil, ErrRateLimited + } + ownerType, ownerID := db.OwnerUser, user.ID + if groupID != 0 { + g, err := b.store.GetGroup(ctx, groupID) + if err != nil || !g.Present() { + return nil, db.ErrNotFound + } + ownerType, ownerID = db.OwnerGroup, groupID + } + w, err := b.bill.Wallet(ctx, ownerType, ownerID) + if err != nil { + return nil, err + } + return b.bill.CreatePurchase(ctx, billing.NewPurchase{ + UserID: user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, DeliveryID: deliveryID, + Memo: b.tr.T(lang, "invoice.memo", map[string]any{"Title": b.productTitle(lang, product)}), + }) +} + +// Explain turns an error from the operations above into a stable code and +// a message in the user's language. +func (b *Bot) Explain(lang string, err error) (code, message string, upgradable bool) { + var le *service.LimitError + var ye *ytdlp.Error + switch { + case errors.As(err, &le): + return "limit." + le.Code, b.limitText(lang, le), le.Upgradable + case errors.Is(err, service.ErrPlaylist): + return "error.playlist", b.tr.T(lang, "error.playlist", nil), false + case errors.As(err, &ye): + return "error." + string(ye.Code), b.tr.T(lang, "error."+string(ye.Code), nil), false + case errors.Is(err, ErrRateLimited): + return "rate_limited", b.tr.T(lang, "notice.rate_limited", nil), false + case errors.Is(err, sched.ErrTooLate): + return "too_late", b.tr.T(lang, "notice.skip_too_late", nil), false + case errors.Is(err, db.ErrNotFound): + return "not_found", b.tr.T(lang, "notice.expired", nil), false + case errors.Is(err, billing.ErrDisabled): + return "payments_off", b.tr.T(lang, "buy.unavailable", nil), false + case errors.Is(err, billing.ErrLightningDown): + return "payments_down", b.tr.T(lang, "buy.backend_down_short", nil), false + case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct): + return "bad_amount", b.tr.T(lang, "buy.bad_amount", nil), false + } + b.log.Error("mini app operation failed", "err", err) + return "internal", b.tr.T(lang, "error.internal", nil), false +} + +func itoa(n int64) string { return strconv.FormatInt(n, 10) } diff --git a/internal/bot/money.go b/internal/bot/money.go index 8e65acd..fbdc218 100644 --- a/internal/bot/money.go +++ b/internal/bot/money.go @@ -742,6 +742,11 @@ func (b *Bot) offerUpgrade(ctx context.Context, chat, replyTo int64, lang string cbData(cbOfferBuy, billing.ProductOneOff, req.ID, string(profile))), }) } + if b.cfg.MiniAppEnabled() { + rows = append(rows, []telego.InlineKeyboardButton{{ + Text: b.tr.T(lang, "btn.open_app", nil), WebApp: &telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/?page=buy"}, + }}) + } } else { // Two targets, both pre-selected by the link: the requester's own // wallet, or the group's. diff --git a/internal/config/config.go b/internal/config/config.go index 1f22fc2..44b07f5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -9,6 +9,8 @@ import ( "bufio" "errors" "fmt" + "net" + "net/url" "os" "reflect" "sort" @@ -427,6 +429,19 @@ func (c Config) Validate() error { if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() { errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE") } + if c.MiniApp { + // Telegram only opens Mini Apps over HTTPS. A plain http address + // is accepted for this machine itself, for development and tests. + u, err := url.Parse(c.PublicURL) + switch { + case c.PublicURL == "": + errs = append(errs, "PUBLIC_URL is required when MINIAPP_ENABLED=true") + case err != nil || u.Host == "": + errs = append(errs, "PUBLIC_URL is not a URL") + case u.Scheme != "https" && !isLoopback(u.Hostname()): + errs = append(errs, "PUBLIC_URL must start with https:// when MINIAPP_ENABLED=true") + } + } if c.Storage.Backend == "s3" { if c.Storage.S3.Endpoint == "" || c.Storage.S3.Bucket == "" { errs = append(errs, "S3_ENDPOINT and S3_BUCKET are required when STORAGE_BACKEND=s3") @@ -519,6 +534,14 @@ func (c Config) RequiredTags(site string) string { return strings.Join(tags, ",") } +func isLoopback(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + // MiniAppEnabled reports whether Mini App links can be shown. The Mini App // is served from PublicURL, so both are needed. func (c Config) MiniAppEnabled() bool { return c.MiniApp && c.PublicURL != "" } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 8af3169..68d9a88 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -167,6 +167,23 @@ func TestValidate(t *testing.T) { func(c *Config) { c.Worker.Concurrency = 0 }, func(c *Config) { c.Queue.MaxAttempts = 0 }, func(c *Config) { c.Queue.Heartbeat = c.Queue.Lease }, + func(c *Config) { c.MiniApp = true }, // no public URL + func(c *Config) { c.MiniApp, c.PublicURL = true, "http://bot.example.com" }, + func(c *Config) { c.MiniApp, c.PublicURL = true, "bot.example.com" }, + } + good := []func(*Config){ + func(c *Config) { c.MiniApp, c.PublicURL = true, "https://bot.example.com" }, + func(c *Config) { c.MiniApp, c.PublicURL = true, "http://127.0.0.1:8080" }, + func(c *Config) { c.MiniApp, c.PublicURL = true, "http://localhost:8080" }, + func(c *Config) { c.PublicURL = "http://bot.example.com" }, // fine without the Mini App + } + for i, mut := range good { + cfg := Default() + cfg.Telegram.Token = "x" + mut(&cfg) + if err := cfg.Validate(); err != nil { + t.Errorf("good case %d: %v", i, err) + } } for i, mut := range bad { cfg := Default() diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index 34d9078..f094f0c 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -34,6 +34,9 @@ type Bundle struct { names []string matcher language.Matcher log *slog.Logger + // raw keeps each catalog as parsed TOML, for exporting the Mini App's + // messages to the browser. + raw map[string]map[string]any mu sync.Mutex localizers map[string]*goi18n.Localizer @@ -51,6 +54,7 @@ func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { log: log, localizers: map[string]*goi18n.Localizer{}, printers: map[string]*message.Printer{}, + raw: map[string]map[string]any{}, } b.bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) files, err := fs.Glob(fsys, "*.toml") @@ -71,6 +75,10 @@ func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { if mf.Tag == language.English { hasDefault = true } + var doc map[string]any + if err := toml.Unmarshal(data, &doc); err == nil { + b.raw[mf.Tag.String()] = doc + } } if !hasDefault { return nil, fmt.Errorf("i18n: the %s catalog is missing", Default) @@ -108,6 +116,7 @@ func (b *Bundle) Reload(fsys fs.FS) error { b.mu.Lock() defer b.mu.Unlock() b.bundle, b.tags, b.names, b.matcher = fresh.bundle, fresh.tags, fresh.names, fresh.matcher + b.raw = fresh.raw b.localizers = map[string]*goi18n.Localizer{} b.printers = map[string]*message.Printer{} return nil @@ -227,3 +236,88 @@ func (b *Bundle) Has(lang, id string) bool { }) return err == nil && gotTag == tag } + +// rtlLangs are the languages written right to left. +var rtlLangs = map[string]bool{"ar": true, "he": true, "fa": true, "ur": true, "ps": true, "sd": true, "yi": true, "dv": true, "ckb": true, "ug": true} + +// Dir returns the text direction of a language: "rtl" or "ltr". +func Dir(lang string) string { + base, _, _ := strings.Cut(strings.ToLower(lang), "-") + if rtlLangs[base] { + return "rtl" + } + return "ltr" +} + +var pluralForms = map[string]bool{"zero": true, "one": true, "two": true, "few": true, "many": true, "other": true} + +// Section exports one top-level table of the catalogs for a client that +// renders text itself, such as the Mini App. Keys are flattened with dots. +// A value is a string, or an object of plural forms. Placeholders are +// rewritten from {{.Name}} to {Name}. Languages fall back the same way as +// everywhere else: the exact one, its base language, then English. +func (b *Bundle) Section(lang, table string) map[string]any { + b.mu.Lock() + defer b.mu.Unlock() + out := map[string]any{} + chain := []string{Default} + if base, _, ok := strings.Cut(lang, "-"); ok && base != Default { + chain = append(chain, base) + } + if lang != Default { + chain = append(chain, lang) + } + for _, l := range chain { + doc, ok := b.raw[l] + if !ok { + continue + } + if t, ok := doc[table].(map[string]any); ok { + flatten("", t, out) + } + } + return out +} + +func flatten(prefix string, in map[string]any, out map[string]any) { + for k, v := range in { + key := k + if prefix != "" { + key = prefix + "." + k + } + switch x := v.(type) { + case string: + out[key] = clientTemplate(x) + case map[string]any: + if isPlural(x) { + forms := map[string]string{} + for form, text := range x { + if s, ok := text.(string); ok { + forms[form] = clientTemplate(s) + } + } + out[key] = forms + } else { + flatten(key, x, out) + } + } + } +} + +func isPlural(m map[string]any) bool { + if len(m) == 0 { + return false + } + for k, v := range m { + if _, ok := v.(string); !ok || !pluralForms[k] { + return false + } + } + return true +} + +// clientTemplate turns {{.Name}} into {Name}. +func clientTemplate(s string) string { + s = strings.ReplaceAll(s, "{{.", "{") + return strings.ReplaceAll(s, "}}", "}") +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 8abba50..a41b2a7 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -144,3 +144,59 @@ func TestFormatting(t *testing.T) { t.Errorf("Percent = %q", got) } } + +func TestSectionExportsForTheMiniApp(t *testing.T) { + fsys := fstest.MapFS{ + "en.toml": {Data: []byte(` +[app] +hello = "Hi {{.Name}}" +only_english = "English only" +[app.tab] +home = "Home" +[app.files] +one = "{{.Count}} file" +other = "{{.Count}} files" +[other] +secret = "not exported" +`)}, + "es.toml": {Data: []byte(` +[app] +hello = "Hola {{.Name}}" +[app.tab] +home = "Inicio" +[app.files] +one = "{{.Count}} archivo" +other = "{{.Count}} archivos" +`)}, + } + b, err := i18n.Load(fsys, nil) + if err != nil { + t.Fatal(err) + } + got := b.Section("es-PY", "app") + if got["hello"] != "Hola {Name}" || got["tab.home"] != "Inicio" { + t.Fatalf("section = %v", got) + } + // A message missing in the language comes from English, like in chat. + if got["only_english"] != "English only" { + t.Fatalf("no fallback to English: %v", got["only_english"]) + } + forms, ok := got["files"].(map[string]string) + if !ok || forms["one"] != "{Count} archivo" || forms["other"] != "{Count} archivos" { + t.Fatalf("plural forms = %v", got["files"]) + } + if _, leaked := got["secret"]; leaked || len(b.Section("es", "missing")) != 0 { + t.Fatal("a section must hold its own table only") + } +} + +func TestDir(t *testing.T) { + for lang, want := range map[string]string{ + "en": "ltr", "es-PY": "ltr", "nl": "ltr", "en-XA": "ltr", + "ar": "rtl", "ar-EG": "rtl", "he": "rtl", "fa-IR": "rtl", "ur": "rtl", "": "ltr", + } { + if got := i18n.Dir(lang); got != want { + t.Errorf("Dir(%q) = %q, want %q", lang, got, want) + } + } +} diff --git a/internal/repocheck/repocheck_test.go b/internal/repocheck/repocheck_test.go index 9aa31c5..2e86310 100644 --- a/internal/repocheck/repocheck_test.go +++ b/internal/repocheck/repocheck_test.go @@ -13,7 +13,7 @@ import ( // textExt lists the file types that are checked. var textExt = map[string]bool{ ".go": true, ".md": true, ".toml": true, ".sql": true, ".yml": true, ".yaml": true, - ".sh": true, ".example": true, ".service": true, ".ts": true, ".tsx": true, + ".sh": true, ".example": true, ".service": true, ".ts": true, ".tsx": true, ".mjs": true, ".css": true, ".html": true, ".json": true, ".txt": true, "": true, } diff --git a/internal/tg/fakeserver/server.go b/internal/tg/fakeserver/server.go index a3093ba..3686656 100644 --- a/internal/tg/fakeserver/server.go +++ b/internal/tg/fakeserver/server.go @@ -53,6 +53,10 @@ type Button struct { Text string `json:"text"` Data string `json:"callback_data"` URL string `json:"url"` + // WebApp is set on a button that opens a Mini App. + WebApp *struct { + URL string `json:"url"` + } `json:"web_app"` } // Buttons parses the inline keyboard of the call, flattened row by row. diff --git a/internal/worker/worker.go b/internal/worker/worker.go index f161acf..51cfd67 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -11,6 +11,7 @@ import ( "math" "os" "path/filepath" + "strconv" "sync" "sync/atomic" "time" @@ -71,6 +72,8 @@ type Worker struct { trans ffmpeg.Transcoder log *slog.Logger active atomic.Int32 + // runs numbers the jobs this process has started, for directory names. + runs atomic.Uint64 // lastOK is the unix time of the last call the core answered. lastOK atomic.Int64 // authFailed is set when the core rejected the token. @@ -277,7 +280,11 @@ func (w *Worker) slot(ctx context.Context) { // process runs one job to completion and always reports an outcome. func (w *Worker) process(ctx context.Context, job *workerproto.Job) { log := w.log.With("job_id", job.ID, "attempt", job.Attempt) - dir := filepath.Join(w.cfg.TempDir, job.ID) + // Each run gets a directory of its own. A retry of the same job can + // start on another slot while this one is still reporting its + // failure; with a shared directory this slot's cleanup would delete + // the retry's file. + dir := filepath.Join(w.cfg.TempDir, job.ID+"."+strconv.FormatUint(w.runs.Add(1), 10)) defer func() { if err := os.RemoveAll(dir); err != nil { log.Warn("cannot remove temp dir", "err", err) diff --git a/internal/worker/worker_test.go b/internal/worker/worker_test.go index aec0d95..3e48b2c 100644 --- a/internal/worker/worker_test.go +++ b/internal/worker/worker_test.go @@ -12,6 +12,7 @@ import ( "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/storage" "github.com/noderunners/dlbot/internal/worker" + "github.com/noderunners/dlbot/internal/workerproto" "github.com/noderunners/dlbot/internal/ytdlp" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) @@ -146,6 +147,82 @@ func TestWorkerRetriesOnceAfterRetryableFailure(t *testing.T) { } } +// slowFail is a coordinator whose Fail call returns late: the core has +// already put the job back in the queue, but the worker slot that reported +// the failure is still busy with the answer. +type slowFail struct { + *sched.Local + failed chan struct{} // closed when Fail may return + uploaded chan struct{} +} + +func (c *slowFail) Fail(ctx context.Context, req workerproto.FailRequest) error { + err := c.Local.Fail(ctx, req) + <-c.failed + return err +} + +func (c *slowFail) Upload(ctx context.Context, job *workerproto.Job, path string) error { + // The retry has its file. Now let the first attempt finish and clean + // up after itself, and only then upload. + close(c.failed) + time.Sleep(150 * time.Millisecond) + defer close(c.uploaded) + return c.Local.Upload(ctx, job, path) +} + +// A retry can start on another slot of the same worker while the slot +// that failed is still wrapping up. The cleanup of the failed attempt must +// not remove the files of the retry. +func TestWorkerRetryDoesNotLoseItsFileToTheFailedAttempt(t *testing.T) { + url := "https://example.com/flaky" + fake := &ytdlptest.Fake{FileSize: 4096, DownloadErrs: map[string][]error{ + url: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "connection reset"}}, + }} + st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files")) + if err != nil { + t.Fatal(err) + } + store := dbtest.Open(t).Store() + sc := sched.New(store, sched.Config{Lease: 5 * time.Second, MaxAttempts: 2}, nil) + coord := &slowFail{Local: &sched.Local{Sched: sc, Storage: st}, failed: make(chan struct{}), uploaded: make(chan struct{})} + w := worker.New(worker.Config{ + ID: "w1", Concurrency: 2, TempDir: filepath.Join(t.TempDir(), "tmp"), + Heartbeat: 30 * time.Millisecond, ClaimWait: 100 * time.Millisecond, + }, coord, fake, nil) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { defer close(done); w.Run(ctx) }() + defer func() { cancel(); <-done }() + + job, _, err := sc.Enqueue(ctx, sched.EnqueueParams{URL: url, Profile: "best", UserID: 1, ChatID: 1, MaxSize: 10 << 20}) + if err != nil { + t.Fatal(err) + } + select { + case <-coord.uploaded: + case <-time.After(10 * time.Second): + t.Fatal("the retry never reached its upload") + } + deadline := time.Now().Add(5 * time.Second) + for { + got, err := store.GetJob(ctx, job.ID) + if err != nil { + t.Fatal(err) + } + if got.Status == db.JobDelivering { + if obj, err := st.Stat(ctx, got.StorageKey); err != nil || obj.Size != 4096 { + t.Fatalf("stored object = %+v, %v", obj, err) + } + return + } + if got.Status == db.JobFailed || time.Now().After(deadline) { + t.Fatalf("job is %s (%s): the retry lost its file to the cleanup of the first attempt", got.Status, got.ErrorCode) + } + time.Sleep(10 * time.Millisecond) + } +} + func TestWorkerGivesUpAfterSecondFailure(t *testing.T) { url := "https://example.com/down" netErr := &ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "boom"} diff --git a/locales/en.toml b/locales/en.toml index 4fdbe17..808b6a3 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -599,9 +599,180 @@ other = "{{.Name}}: {{.Count}} downloads, {{.Size}}, {{.Sats}}" unknown = "I do not know that group, or I am no longer in it." intro = "{{.Group}}\nGroup balance: {{.Balance}}\n\nWhat you buy here belongs to the group: a pass covers every member, credits are spent by the group's rules." +# --- Mini App ---------------------------------------------------------------- +# Everything under [app] is shown inside the Mini App, as plain text (no +# HTML). The app also reads the product, unit, btn, settings, quality and +# language tables, so names shared with the chat are written once. + [app] unavailable = "The app is not set up on this bot." open = "Open the app to manage downloads, passes and groups." +title = "Downloads" +retry = "Try again" +save = "Save" +saved = "Saved." +add = "Add" +close = "Close" +done = "Done" +copied = "Copied." +on = "On" +off = "Off" +untitled = "Untitled" +see_plans = "See passes and credits" +sent_to_chat = "Started. The file arrives in our chat." +pass_until = "Pass until {{.Until}}" +balance_is = "Balance: {{.Balance}}" + +[app.error] +unauthorized = "Open this page from Telegram, with the Open app button of the bot." +banned = "This account cannot use the bot." +bad_link = "That does not look like a link I can use." +bad_settings = "Some of these settings are not valid." +network = "No connection. Check your network and try again." +generic = "Something went wrong. Try again." +not_found = "That is not there anymore." + +[app.tab] +home = "Home" +queue = "Queue" +buy = "Buy" +groups = "Groups" +me = "Me" + +[app.home] +hello = "Hi {{.Name}}" +pass_active = "Pass active" +plan_free = "Free plan" +plan_free_hint = "A pass lifts the limits and skips the line." +balance = "Balance" +today = "Today" +downloads = "Downloads" +volume = "Volume" +used_of = "{{.Used}} of {{.Max}}" +used_unlimited = "{{.Used}}, no limit" +paste_title = "New download" +paste_placeholder = "Paste a link" +look_up = "Look up" +recent = "Recent downloads" +all_history = "All" + +[app.queue] +title = "Your downloads" +note = "Files arrive in your chat with the bot." +empty = "Nothing in the queue." +waiting = "Position {{.Position}}, about {{.Wait}}" +downloading = "Downloading" +downloading_pct = "Downloading, {{.Percent}}" +processing = "Processing" +sending = "Sending to Telegram" +prioritize = "Prioritize · {{.Price}}" +prioritized = "Moved to the front." +cancel_confirm = "Cancel \"{{.Title}}\"?" +cancelled = "Cancelled." + +[app.buy] +unavailable = "Payments are not set up on this bot." +step = "Step {{.Step}} of {{.Total}}" +target_title = "Who is it for?" +target_note = "A group pass and group credits work for the members of that group." +for_me = "Me" +for_group = "Group" +pass_title = "Pass for {{.Target}}" +pass_note = "A pass gives the higher limits and the priority lane until it ends. Buying again adds time." +credits_title = "Credits" +credits_note = "Without a pass, a download beyond the free limits costs {{.Price}}." +paid_title = "With a pass or credits" + +[app.buy.credits_downloads] +one = "about {{.Count}} download" +other = "about {{.Count}} downloads" + +[app.limit] +size = "Size per download" +duration = "Length per download" +per_day = "Downloads per day" +at_once = "At the same time" +none = "No limit" + +[app.invoice] +qr_alt = "Lightning invoice as a QR code" +copy = "Copy invoice" +waiting = "Waiting for payment · {{.Time}}" +checking = "Checking for the payment…" +cancel = "Cancel this invoice" +paid = "Paid" +paid_text = "{{.Product}} for {{.Amount}}. Thank you." +expired = "Invoice expired" +cancelled = "Invoice cancelled" +closed_text = "Nothing was charged. A payment that still arrives is added to the balance." + +[app.history] +title = "History" +note = "Sending again counts as a new download. It is usually instant." +empty = "No downloads yet." +resend = "Send again" + +[app.groups] +title = "Your groups" +note = "Groups where you are an admin and the bot is a member." +empty = "No groups yet. Add the bot to a group where you are an admin and send a command there once." +no_pass = "No pass" + +[app.group] +balance = "Group balance" +pass = "Group pass" +pass_on = "Active" +pass_off = "None" +language = "Language" +auto_detect_hint = "Fetch links that members paste, without a command." +caps_title = "Caps for this group" +caps_note = "Leave empty for the normal limit ({{.Size}} per file). A cap can only lower it." +max_size = "Largest file, in MB" +max_minutes = "Longest video, in minutes" +allowed_title = "Allowed sites" +allowed_note = "When this list has entries, only these sites work in the group." +blocked_title = "Blocked sites" +blocked_note = "Links to these sites are refused in the group." +site_placeholder = "example.com" +remove_site = "Remove {{.Site}}" +top_up = "Top up or buy a pass" +rules_title = "Spending rules" +rules_note = "Group credits pay for members who are over their own limits. An empty cap means no cap." +spend_cap = "Sats per person per day" +daily_cap = "Sats per day for the whole group" +usage_empty = "No downloads in this period." +col_member = "Member" +col_downloads = "Downloads" +col_volume = "Volume" +col_spent = "Spent" + +[app.group.tab] +overview = "Overview" +settings = "Settings" +wallet = "Wallet" +usage = "Usage" + +[app.group.usage_title] +one = "Usage, last day" +other = "Usage, last {{.Count}} days" + +[app.me] +downloads_title = "Downloads" +quality_note = "With a default set, a link starts right away instead of asking for a format." +audio_only = "Audio only" +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}}." +copy_link = "Copy link" +share = "Share" +invited = "Invited so far" +support = "Support" + +[app.me.invited_count] +one = "{{.Count}} person" +other = "{{.Count}} people" # --- Static pages ------------------------------------------------------------ diff --git a/web/miniapp/dist/assets/app.js b/web/miniapp/dist/assets/app.js new file mode 100644 index 0000000..fb9cb6e --- /dev/null +++ b/web/miniapp/dist/assets/app.js @@ -0,0 +1,9 @@ +var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports);(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function ee(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var te=ee.prototype=new b;te.constructor=ee,_(te,y.prototype),te.isPureReactComponent=!0;var ne=Array.isArray;function re(){}var x={H:null,A:null,T:null,S:null},ie=Object.prototype.hasOwnProperty;function S(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function ae(e,t){return S(e.type,t,e.props)}function oe(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function se(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ce=/\/+/g;function le(e,t){return typeof e==`object`&&e&&e.key!=null?se(``+e.key):t.toString(36)}function ue(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(re,re):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function de(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,de(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+le(e,0):a,ne(o)?(i=``,c!=null&&(i=c.replace(ce,`$&/`)+`/`),de(o,r,i,``,function(e){return e})):o!=null&&(oe(o)&&(o=ae(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(ce,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(ne(e))for(var u=0;u{n.exports=t()})),r=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,te||(te=!0,ae());else{var t=n(l);t!==null&&ce(ee,t.startTime-e)}}}var te=!1,ne=-1,re=5,x=-1;function ie(){return g?!0:!(e.unstable_now()-xt&&ie());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ce(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ae():te=!1}}}var ae;if(typeof y==`function`)ae=function(){y(S)};else if(typeof MessageChannel<`u`){var oe=new MessageChannel,se=oe.port2;oe.port1.onmessage=S,ae=function(){se.postMessage(null)}}else ae=function(){_(S,0)};function ce(t,n){ne=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ne),ne=-1):h=!0,ce(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,te||(te=!0,ae()))),r},e.unstable_shouldYield=ie,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),i=e(((e,t)=>{t.exports=r()})),a=e((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=a()})),s=e((e=>{var t=i(),r=n(),a=o();function s(e){var t=`https://react.dev/errors/`+e;if(1Ee||(e.current=Te[Ee],Te[Ee]=null,Ee--)}function k(e,t){Ee++,Te[Ee]=e.current,e.current=t}var ke=De(null),Ae=De(null),je=De(null),Me=De(null);function Ne(e,t){switch(k(je,t),k(Ae,e),k(ke,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?up(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=up(t),e=dp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Oe(ke),k(ke,e)}function Pe(){Oe(ke),Oe(Ae),Oe(je)}function Fe(e){var t=e.memoizedState;t!==null&&(sh._currentValue=t.memoizedState,k(Me,e)),t=ke.current;var n=dp(t,e.type);t!==n&&(k(Ae,e),k(ke,n))}function Ie(e){Ae.current===e&&(Oe(ke),Oe(Ae)),Me.current===e&&(Oe(Me),sh._currentValue=we)}var Le,Re;function ze(e){if(Le===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Le=t&&t[1]||``,Re=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Be=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?ze(n):``}function He(e,t){switch(e.tag){case 26:case 27:case 5:return ze(e.type);case 16:return ze(`Lazy`);case 13:return e.child!==t&&t!==null?ze(`Suspense Fallback`):ze(`Suspense`);case 19:return ze(`SuspenseList`);case 0:case 15:return Ve(e.type,!1);case 11:return Ve(e.type.render,!1);case 1:return Ve(e.type,!0);case 31:return ze(`Activity`);case 30:return ze(`ViewTransition`);default:return``}}function Ue(e){try{var t=``,n=null;do t+=He(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +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:t,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?``:e.quality,onChange:e=>void a({quality:e}),options: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`:``})})})]}),(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 diff --git a/web/miniapp/dist/assets/index.css b/web/miniapp/dist/assets/index.css new file mode 100644 index 0000000..08620d2 --- /dev/null +++ b/web/miniapp/dist/assets/index.css @@ -0,0 +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)} diff --git a/web/miniapp/dist/index.html b/web/miniapp/dist/index.html new file mode 100644 index 0000000..05900ab --- /dev/null +++ b/web/miniapp/dist/index.html @@ -0,0 +1,15 @@ + + + + + + + Noderunners Download Bot + + + + + +
+ + diff --git a/web/miniapp/dist/source.sha256 b/web/miniapp/dist/source.sha256 new file mode 100644 index 0000000..ad07685 --- /dev/null +++ b/web/miniapp/dist/source.sha256 @@ -0,0 +1 @@ +4c14cc42a4c45e760e0f6a38118cf48fac686831914bdc7eb0712bd2c2580fcc diff --git a/web/miniapp/e2e/run.sh b/web/miniapp/e2e/run.sh new file mode 100755 index 0000000..89af9ae --- /dev/null +++ b/web/miniapp/e2e/run.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Runs the browser test of the Mini App: a complete core in test mode +# (fake Telegram, fake LNbits, scripted yt-dlp) and headless Chromium +# clicking through the built app. +# +# web/miniapp/e2e/run.sh [screenshot dir] +# +# Needs Node.js with "npm ci" done in web/miniapp, and a Chromium that +# Playwright can start: "npx playwright-core install chromium", or +# CHROMIUM_PATH pointing at a Chrome or Chromium binary. +set -euo pipefail + +root="$(cd "$(dirname "$0")/../../.." && pwd)" +stage="$(mktemp -d)" +shots="${1:-}" +log="$stage/core.log" + +cleanup() { + touch "$stage/stop" + wait "$core" 2>/dev/null || true + rm -rf "$stage" +} + +cd "$root" +(cd web/miniapp && npm run build >/dev/null) + +DLBOT_STAGE_DIR="$stage" go test ./internal/app/ -run '^TestMiniAppStage$' -count=1 -timeout 20m >"$log" 2>&1 & +core=$! +trap cleanup EXIT + +for _ in $(seq 1 600); do + [ -f "$stage/stage.json" ] && break + if ! kill -0 "$core" 2>/dev/null; then + echo "the core did not start:" >&2 + cat "$log" >&2 + exit 1 + fi + sleep 0.2 +done +[ -f "$stage/stage.json" ] || { echo "timed out waiting for the core" >&2; cat "$log" >&2; exit 1; } + +(cd web/miniapp && node e2e/smoke.mjs "$stage" "$shots") diff --git a/web/miniapp/e2e/smoke.mjs b/web/miniapp/e2e/smoke.mjs new file mode 100644 index 0000000..182887b --- /dev/null +++ b/web/miniapp/e2e/smoke.mjs @@ -0,0 +1,294 @@ +// Browser test of the Mini App against a running core. +// +// It opens the built app in headless Chromium, with a stand-in for +// Telegram's bridge script that hands the app signed initData, and clicks +// through the flows a user has: look a link up and download it, cancel a +// download, resend from history, buy a pass, manage a group, top up a +// group wallet, change preferences. Any error in the page's console fails +// the run. +// +// Usage: node e2e/smoke.mjs [screenshot dir] +// The stage dir holds stage.json, written by TestMiniAppStage. Run both +// together with "make miniapp-e2e" from the repository root. +// CHROMIUM_PATH picks the browser binary when Playwright's own is absent. + +import { chromium } from "playwright-core"; +import { mkdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +const stageDir = process.argv[2]; +const shotDir = process.argv[3] || ""; +if (!stageDir) { + console.error("usage: node e2e/smoke.mjs [screenshot dir]"); + process.exit(2); +} +const stage = JSON.parse(readFileSync(join(stageDir, "stage.json"), "utf8")); +if (shotDir) mkdirSync(shotDir, { recursive: true }); + +// What the app sees instead of telegram-web-app.js. +const bridge = (initData) => ` + window.__opened = []; + window.__back = { shown: false, cb: null }; + window.Telegram = { WebApp: { + initData: ${JSON.stringify(initData)}, + initDataUnsafe: {}, + colorScheme: "light", + version: "8.0", + isVersionAtLeast: () => true, + ready() {}, expand() {}, close() {}, + openLink(u) { window.__opened.push(u); }, + openTelegramLink(u) { window.__opened.push(u); }, + showConfirm(message, cb) { window.__confirmed = message; cb(true); }, + BackButton: { + show() { window.__back.shown = true; }, + hide() { window.__back.shown = false; }, + onClick(cb) { window.__back.cb = cb; }, + offClick() {}, + }, + HapticFeedback: { impactOccurred() {}, notificationOccurred() {}, selectionChanged() {} }, + } }; +`; + +const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined }); +const problems = []; +let step = "start"; + +async function open(initData, tweak) { + const context = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: "en-US" }); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const page = await context.newPage(); + await page.route("https://telegram.org/**", (route) => + route.fulfill({ contentType: "application/javascript", body: bridge(initData) }), + ); + if (tweak) await tweak(page); + page.on("console", (m) => { + if (m.type() === "error") problems.push(`[${step}] console: ${m.text()}`); + }); + page.on("pageerror", (e) => problems.push(`[${step}] page error: ${e.message}`)); + await page.goto(stage.url); + return page; +} + +let shots = 0; +async function shot(page, name) { + if (shotDir) await page.screenshot({ path: join(shotDir, `${String(++shots).padStart(2, "0")}-${name}.png`) }); +} + +const tab = (page, name) => page.getByRole("navigation").getByRole("button", { name: new RegExp("^" + name) }); +const toast = (page, text) => page.getByRole("status").filter({ hasText: text }).waitFor(); +const back = (page) => page.evaluate(() => window.__back.cb && window.__back.cb()); + +async function expectText(page, text) { + await page.getByText(text, { exact: false }).first().waitFor({ timeout: 10000 }); +} + +async function run(name, fn) { + step = name; + const started = Date.now(); + await fn(); + console.log(`ok ${name} (${Date.now() - started} ms)`); +} + +try { + const page = await open(stage.init_data.admin); + + await run("home shows the plan, usage and recent downloads", async () => { + await expectText(page, "Free plan"); + await expectText(page, "1 of "); + await page.getByText("Test Video").first().waitFor(); + await page.getByRole("button", { name: "Send again" }).first().waitFor(); + await shot(page, "home"); + }); + + await run("a pasted link is looked up and started", async () => { + await page.getByPlaceholder("Paste a link").fill("https://example.com/watch?v=browser"); + await page.getByRole("button", { name: "Look up" }).click(); + await page.getByRole("button", { name: /^Best/ }).waitFor(); + await shot(page, "lookup"); + await page.getByRole("button", { name: /^Best/ }).click(); + await toast(page, "Started"); + // The app moves to the queue by itself. + await expectText(page, "Your downloads"); + await page.getByText(/Downloading|Position|Sending/).first().waitFor(); + await shot(page, "queue"); + }); + + await run("a running download can be cancelled", async () => { + await page.getByRole("button", { name: "Cancel", exact: true }).click(); + await toast(page, "Cancelled"); + await expectText(page, "Nothing in the queue."); + const asked = await page.evaluate(() => window.__confirmed); + if (!asked || !asked.includes("Test Video")) throw new Error("no confirmation was asked: " + asked); + }); + + await run("history sends a file again", async () => { + await tab(page, "Home").click(); + await page.getByRole("button", { name: "All", exact: true }).click(); + await expectText(page, "History"); + if (!(await page.evaluate(() => window.__back.shown))) throw new Error("no back button on a sub page"); + await page.getByRole("button", { name: "Send again" }).first().click(); + await toast(page, "Started"); + await shot(page, "history"); + await back(page); + await expectText(page, "New download"); + }); + + await run("buying a pass shows an invoice and notices the payment", async () => { + await tab(page, "Buy").click(); + await expectText(page, "Who is it for?"); + await shot(page, "buy-target"); + await page.getByRole("button", { name: /^Me Balance/ }).click(); + await expectText(page, "Pass for Me"); + await shot(page, "buy-product"); + await page.getByRole("button", { name: /Day pass/ }).click(); + await page.getByAltText("Lightning invoice as a QR code").waitFor(); + await expectText(page, "Waiting for payment"); + await shot(page, "invoice"); + await page.getByRole("button", { name: "Copy invoice" }).click(); + await toast(page, "Copied"); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + if (!copied.startsWith("lnbc")) throw new Error("clipboard holds " + copied.slice(0, 20)); + await page.getByRole("button", { name: "Open in wallet" }).click(); + const opened = await page.evaluate(() => window.__opened.at(-1)); + if (!/\/pay\/[0-9A-Za-z]+$/.test(opened || "")) throw new Error("wallet link = " + opened); + // The stage pays the invoice after three seconds. + await page.getByText("Paid", { exact: true }).waitFor({ timeout: 15000 }); + await shot(page, "paid"); + await page.getByRole("button", { name: "Done" }).click(); + await expectText(page, "Pass active"); + await shot(page, "home-with-pass"); + }); + + await run("group settings can be changed by an admin", async () => { + await tab(page, "Groups").click(); + await expectText(page, "Your groups"); + await shot(page, "groups"); + await page.locator("button.cell").first().click(); + await page.getByRole("tab", { name: "Overview" }).waitFor(); + await shot(page, "group-overview"); + await page.getByRole("tab", { name: "Settings" }).click(); + const detect = page.getByRole("switch", { name: "Detect pasted links" }); + if ((await detect.getAttribute("aria-checked")) !== "false") throw new Error("auto detect starts on"); + await detect.click(); + await page.getByLabel("Who can use it").selectOption("admins"); + await page.getByLabel("Largest file, in MB").fill("25"); + await page.getByPlaceholder("example.com").last().fill("https://www.Blocked.example/x"); + await page.getByRole("button", { name: "Add" }).last().click(); + await page.getByRole("button", { name: "Remove blocked.example" }).waitFor(); + await shot(page, "group-settings"); + await page.getByRole("button", { name: "Save" }).click(); + await toast(page, "Saved"); + // What the core stored is what a fresh load shows. + await page.reload(); + await tab(page, "Groups").click(); + await page.locator("button.cell").first().click(); + await page.getByRole("tab", { name: "Settings" }).click(); + if ((await page.getByRole("switch", { name: "Detect pasted links" }).getAttribute("aria-checked")) !== "true") + throw new Error("auto detect was not saved"); + if ((await page.getByLabel("Who can use it").inputValue()) !== "admins") throw new Error("who can use was not saved"); + if ((await page.getByLabel("Largest file, in MB").inputValue()) !== "25") throw new Error("size cap was not saved"); + await page.getByRole("button", { name: "Remove blocked.example" }).waitFor(); + }); + + await run("a group wallet is topped up and its rules are set", async () => { + await page.getByRole("tab", { name: "Wallet" }).click(); + await expectText(page, "0 sats"); + await page.getByLabel("Group credits").selectOption("capped"); + await page.getByLabel("Sats per person per day").fill("200"); + await page.getByRole("button", { name: "Save" }).click(); + await toast(page, "Saved"); + await page.getByRole("button", { name: "Top up or buy a pass" }).click(); + await expectText(page, "Credits"); + await page.getByRole("button", { name: /^1,000 sats/ }).click(); + await page.getByAltText("Lightning invoice as a QR code").waitFor(); + await page.getByText("Paid", { exact: true }).waitFor({ timeout: 15000 }); + await page.getByRole("button", { name: "Done" }).click(); + // Back in the group, the balance is there. + await page.getByRole("tab", { name: "Wallet" }).click(); + await expectText(page, "1,000 sats"); + await shot(page, "group-wallet"); + await page.getByRole("tab", { name: "Usage" }).click(); + await page.getByText(/Usage, last 7 days/).waitFor(); + await shot(page, "group-usage"); + }); + + await run("preferences are saved", async () => { + await tab(page, "Me").click(); + await page.getByLabel("Default quality").selectOption("720"); + await toast(page, "Saved"); + await page.getByRole("switch", { name: "Audio only" }).click(); + await page.locator('[role="switch"][aria-checked="true"]').waitFor(); + await page.getByRole("button", { name: "Copy link" }).click(); + const link = await page.evaluate(() => navigator.clipboard.readText()); + if (!/\?start=ref_\d+$/.test(link)) throw new Error("referral link = " + link); + await page.getByRole("button", { name: "Share" }).click(); + const shared = await page.evaluate(() => window.__opened.at(-1)); + if (!shared.startsWith("https://t.me/share/url?url=")) throw new Error("share link = " + shared); + await shot(page, "me"); + }); + await page.context().close(); + + await run("a member who is not an admin sees no groups", async () => { + const member = await open(stage.init_data.member); + await tab(member, "Groups").click(); + await expectText(member, "No groups yet."); + await member.context().close(); + }); + + await run("a deep link opens the group it names", async () => { + const deep = await open(stage.init_data.admin, (p) => + p.route("**/app/api/me", async (route) => { + const res = await route.fetch(); + const me = await res.json(); + me.start_param = "group_" + stage.group; + await route.fulfill({ response: res, json: me }); + }), + ); + await deep.getByRole("tab", { name: "Settings" }).waitFor(); + await deep.getByRole("switch", { name: "Detect pasted links" }).waitFor(); + await deep.context().close(); + }); + + await run("a right-to-left language mirrors the layout", async () => { + const rtl = await open(stage.init_data.admin, (p) => + p.route("**/app/api/i18n", async (route) => { + const res = await route.fetch(); + const body = await res.json(); + body.dir = "rtl"; + await route.fulfill({ response: res, json: body }); + }), + ); + await expectText(rtl, "Recent downloads"); + const layout = await rtl.evaluate(() => { + const first = document.querySelector("nav button").getBoundingClientRect(); + const last = [...document.querySelectorAll("nav button")].at(-1).getBoundingClientRect(); + const title = document.querySelector(".section-title span").getBoundingClientRect(); + return { dir: document.documentElement.dir, firstTabX: first.x, lastTabX: last.x, titleRight: title.right, width: innerWidth }; + }); + if (layout.dir !== "rtl" || layout.firstTabX < layout.lastTabX || layout.titleRight < layout.width / 2) + throw new Error("layout is not mirrored: " + JSON.stringify(layout)); + await shot(rtl, "rtl"); + await rtl.context().close(); + }); + + await run("outside Telegram the app explains itself", async () => { + const stranger = await open(""); + await expectText(stranger, "Open this page from Telegram"); + await shot(stranger, "outside-telegram"); + await stranger.context().close(); + // The refused calls show up as console errors; they are the point. + for (let i = problems.length - 1; i >= 0; i--) { + if (problems[i].startsWith(`[${step}]`) && problems[i].includes("401")) problems.splice(i, 1); + } + }); +} catch (err) { + problems.push(`[${step}] ${err.stack || err}`); +} finally { + await browser.close(); +} + +if (problems.length > 0) { + console.error("\nFAILED:\n" + problems.join("\n")); + process.exit(1); +} +console.log("\nall browser checks passed"); diff --git a/web/miniapp/embed.go b/web/miniapp/embed.go new file mode 100644 index 0000000..5031b64 --- /dev/null +++ b/web/miniapp/embed.go @@ -0,0 +1,25 @@ +// Package miniapp holds the built Mini App front end, so the core binary +// serves it without any files next to it. +// +// The dist directory is the output of "npm run build" in this directory +// (or "make miniapp" from the repository root). It is committed, so a +// plain "go build" works on a machine without Node.js. After changing +// anything under src, rebuild and commit dist together with the change. +package miniapp + +import ( + "embed" + "io/fs" +) + +//go:embed all:dist +var dist embed.FS + +// FS returns the built app, with index.html at its root. +func FS() fs.FS { + sub, err := fs.Sub(dist, "dist") + if err != nil { + panic(err) // the directory is embedded at build time + } + return sub +} diff --git a/web/miniapp/embed_test.go b/web/miniapp/embed_test.go new file mode 100644 index 0000000..53b7a6a --- /dev/null +++ b/web/miniapp/embed_test.go @@ -0,0 +1,132 @@ +package miniapp_test + +import ( + "crypto/sha256" + "encoding/hex" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" + + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/locales" + "github.com/noderunners/dlbot/web/miniapp" +) + +// sourceFiles are the files the build is made from, as paths relative to +// this directory. The list matches sourceStamp in vite.config.ts. +func sourceFiles(t *testing.T) []string { + t.Helper() + files := []string{"index.html", "package.json", "package-lock.json", "tsconfig.json", "vite.config.ts"} + err := filepath.WalkDir("src", func(path string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() { + files = append(files, filepath.ToSlash(path)) + } + return err + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(files) + return files +} + +// TestBuildIsCurrent fails when the committed build was not made from the +// committed sources. Fix it with "make miniapp" and commit the result. +func TestBuildIsCurrent(t *testing.T) { + h := sha256.New() + for _, f := range sourceFiles(t) { + data, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + h.Write([]byte(f + "\x00")) + h.Write(data) + h.Write([]byte{0}) + } + want := hex.EncodeToString(h.Sum(nil)) + got, err := fs.ReadFile(miniapp.FS(), "source.sha256") + if err != nil { + t.Fatalf("the build has no source stamp, run \"make miniapp\": %v", err) + } + if strings.TrimSpace(string(got)) != want { + t.Fatal("web/miniapp/dist is older than the sources. Run \"make miniapp\" and commit dist.") + } +} + +func TestBuildIsComplete(t *testing.T) { + index, err := fs.ReadFile(miniapp.FS(), "index.html") + if err != nil { + t.Fatal(err) + } + refs := regexp.MustCompile(`(?:src|href)="/app/([^"]+)"`).FindAllStringSubmatch(string(index), -1) + if len(refs) < 2 { + t.Fatalf("index.html names %d files of its own, want a script and a style sheet", len(refs)) + } + for _, r := range refs { + if st, err := fs.Stat(miniapp.FS(), r[1]); err != nil || st.Size() == 0 { + t.Errorf("index.html names %s, which is not in the build", r[1]) + } + } + if !strings.Contains(string(index), "https://telegram.org/js/telegram-web-app.js") { + t.Error("index.html does not load Telegram's bridge script") + } +} + +var ( + literalKey = regexp.MustCompile(`\bt\("([a-z0-9_.]+)"[,)]`) + prefixKey = regexp.MustCompile(`\bt\("([a-z0-9_.]+\.)" \+`) + rawText = regexp.MustCompile(`>\s*([A-Z][a-z]+(?: [a-z]+)+)\s*<`) +) + +// TestEveryTextIsInTheCatalog checks that each message the app asks for +// exists in the English catalog, and that no sentence is written into the +// markup directly. +func TestEveryTextIsInTheCatalog(t *testing.T) { + bundle, err := i18n.Load(locales.FS, nil) + if err != nil { + t.Fatal(err) + } + // 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 k := range bundle.Section("en", table) { + exported[table+"."+k] = true + } + } + seen := 0 + for _, f := range sourceFiles(t) { + if !strings.HasPrefix(f, "src/") || !(strings.HasSuffix(f, ".ts") || strings.HasSuffix(f, ".tsx")) { + continue + } + data, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + src := string(data) + for _, m := range literalKey.FindAllStringSubmatch(src, -1) { + seen++ + if exported[m[1]] == nil { + t.Errorf("%s uses %q, which the app does not get from the catalog", f, m[1]) + } + } + for _, m := range prefixKey.FindAllStringSubmatch(src, -1) { + found := false + for k := range exported { + found = found || strings.HasPrefix(k, m[1]) + } + if !found { + t.Errorf("%s builds keys from %q, and the catalog has none", f, m[1]) + } + } + for _, m := range rawText.FindAllStringSubmatch(src, -1) { + t.Errorf("%s has literal text %q in its markup; it belongs in the catalog", f, m[1]) + } + } + if seen < 100 { + t.Fatalf("found only %d message lookups; the pattern no longer matches the code", seen) + } +} diff --git a/web/miniapp/index.html b/web/miniapp/index.html new file mode 100644 index 0000000..ff19efe --- /dev/null +++ b/web/miniapp/index.html @@ -0,0 +1,14 @@ + + + + + + + Noderunners Download Bot + + + +
+ + + diff --git a/web/miniapp/package-lock.json b/web/miniapp/package-lock.json new file mode 100644 index 0000000..93436eb --- /dev/null +++ b/web/miniapp/package-lock.json @@ -0,0 +1,1061 @@ +{ + "name": "dlbot-miniapp", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "dlbot-miniapp", + "version": "1.0.0", + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^6.3.0", + "playwright-core": "^1.65.1", + "typescript": "^5.6.0", + "vite": "^8.3.8" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/web/miniapp/package.json b/web/miniapp/package.json new file mode 100644 index 0000000..2b0e335 --- /dev/null +++ b/web/miniapp/package.json @@ -0,0 +1,24 @@ +{ + "name": "dlbot-miniapp", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/node": "^24.19.2", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^6.3.0", + "playwright-core": "^1.65.1", + "typescript": "^5.6.0", + "vite": "^8.3.8" + } +} diff --git a/web/miniapp/src/App.tsx b/web/miniapp/src/App.tsx new file mode 100644 index 0000000..ff1bc18 --- /dev/null +++ b/web/miniapp/src/App.tsx @@ -0,0 +1,166 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { api, ApiError, type Job, type Me, type Messages } from "./api"; +import { setMessages, t } from "./i18n"; +import { haptic } from "./tg"; +import { AppContext, errorText, Spinner, useBack, type Ctx, type Route, type Tab } from "./ui"; +import { Home } from "./pages/Home"; +import { Queue } from "./pages/Queue"; +import { Buy } from "./pages/Buy"; +import { History } from "./pages/History"; +import { Groups } from "./pages/Groups"; +import { GroupPage } from "./pages/GroupPage"; +import { Profile } from "./pages/Profile"; + +const icons: Record = { + 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", +}; + +const tabs: Tab[] = ["home", "queue", "buy", "groups", "me"]; + +// firstRoute turns the start parameter of a deep link into a page: +// "group_" opens that group, "buy" the shop. A button in the chat +// cannot carry a start parameter, so it names the page in the address. +function firstRoute(start: string): Route { + const param = new URLSearchParams(window.location.search).get("page") ?? start; + if (param.startsWith("group_")) return { tab: "groups", group: param.slice(6), view: "settings" }; + if (param === "buy") return { tab: "buy" }; + if (param === "queue") return { tab: "queue" }; + return { tab: "home" }; +} + +export function App() { + const [me, setMe] = useState(null); + const [error, setError] = useState(null); + const [stack, setStack] = useState([{ tab: "home" }]); + const [toast, setToast] = useState<{ text: string; bad: boolean } | null>(null); + const [active, setActive] = useState(0); + const toastTimer = useRef(undefined); + const started = useRef(false); + + const load = useCallback(async () => { + const [m, msgs] = await Promise.all([api("GET", "me"), api("GET", "i18n")]); + setMessages(msgs); + document.title = t("app.title"); + setMe(m); + return m; + }, []); + + useEffect(() => { + if (started.current) return; + started.current = true; + load() + .then((m) => setStack([firstRoute(m.start_param)])) + .catch(setError); + }, [load]); + + // The badge on the Queue tab follows the number of active downloads. + useEffect(() => { + if (!me) return; + let alive = true; + const poll = () => { + if (document.hidden) return; + api<{ jobs: Job[] }>("GET", "queue") + .then((q) => alive && setActive(q.jobs.length)) + .catch(() => undefined); + }; + poll(); + const timer = window.setInterval(poll, 5000); + return () => { + alive = false; + window.clearInterval(timer); + }; + }, [me]); + + const route = stack[stack.length - 1]; + + const notify = useCallback((text: string, bad = false) => { + window.clearTimeout(toastTimer.current); + setToast({ text, bad }); + haptic(bad ? "error" : "success"); + toastTimer.current = window.setTimeout(() => setToast(null), 3500); + }, []); + + const ctx = useMemo(() => { + if (!me) return null; + return { + me, + route, + go: (r) => { + // A tab is a fresh start; anything deeper goes on the stack so + // the back button returns to where the user came from. + const deep = "page" in r || "group" in r || "target" in r; + setStack((s) => (deep ? [...s, r] : [r])); + window.scrollTo(0, 0); + }, + back: () => setStack((s) => (s.length > 1 ? s.slice(0, -1) : [{ tab: s[0].tab }])), + notify, + fail: (err) => notify(errorText(err), true), + reload: async () => { + await load(); + }, + }; + }, [me, route, notify, load]); + + useBack(ctx && stack.length > 1 ? ctx.back : null); + + if (error) { + // Before the catalog is loaded the only text available is the one the + // core sent with the refusal. + const message = error instanceof ApiError ? error.message : ""; + return ( +
+
+

:(

+

{message}

+ {!(error instanceof ApiError && error.status === 401) && ( + + )} +
+
+ ); + } + if (!ctx) { + return ( +
+ +
+ ); + } + + let page; + if ("group" in route) page = ; + else if ("page" in route) page = ; + else if (route.tab === "queue") page = ; + else if (route.tab === "buy") page = ; + else if (route.tab === "groups") page = ; + else if (route.tab === "me") page = ; + else page = ; + + return ( + +
{page}
+ {toast && ( +
+ {toast.text} +
+ )} + +
+ ); +} diff --git a/web/miniapp/src/Invoice.tsx b/web/miniapp/src/Invoice.tsx new file mode 100644 index 0000000..5204f9e --- /dev/null +++ b/web/miniapp/src/Invoice.tsx @@ -0,0 +1,124 @@ +import { useEffect, useRef, useState } from "react"; +import { api, type Purchase } from "./api"; +import { clock, dateTime, sats, t } from "./i18n"; +import { copyText, haptic, openExternal } from "./tg"; +import { Button, useApp } from "./ui"; + +// Invoice shows a Lightning invoice and waits for it to be paid. It asks +// the core every few seconds; the core asks the payment backend. Nothing +// here decides that a payment happened. +export function Invoice(props: { purchase: Purchase; onDone(): void; onPaid?(p: Purchase): void }) { + const { notify, fail, reload } = useApp(); + const [p, setP] = useState(props.purchase); + const [now, setNow] = useState(Date.now()); + const onPaid = useRef(props.onPaid); + onPaid.current = props.onPaid; + + useEffect(() => { + if (p.status !== "pending") return; + let alive = true; + const poll = window.setInterval(() => { + if (document.hidden) return; + api("GET", "purchase/" + p.id) + .then((next) => { + if (!alive || next.status === "pending") return; + setP((old) => ({ ...old, ...next })); + if (next.status === "paid") { + haptic("success"); + void reload(); + onPaid.current?.(next); + } + }) + .catch(() => undefined); + }, 2500); + const tick = window.setInterval(() => setNow(Date.now()), 1000); + return () => { + alive = false; + window.clearInterval(poll); + window.clearInterval(tick); + }; + }, [p.id, p.status, reload]); + + const title = t("product." + p.product); + + if (p.status === "paid") { + return ( +
+
✓
+
{t("app.invoice.paid")}
+
{t("app.invoice.paid_text", { Product: title, Amount: sats(p.amount) })}
+ {p.pass_until ?
{t("app.pass_until", { Until: dateTime(p.pass_until) })}
: null} + {p.balance !== undefined &&
{t("app.balance_is", { Balance: sats(p.balance) })}
} + +
+ ); + } + + if (p.status !== "pending") { + return ( +
+
{t("app.invoice." + p.status)}
+
{t("app.invoice.closed_text")}
+ +
+ ); + } + + const left = Math.max(0, Math.floor((p.expires_at - now) / 1000)); + const bolt11 = p.bolt11 ?? ""; + + return ( +
+
+
{title}
+
{sats(p.amount)}
+
+ {p.qr && {t("app.invoice.qr_alt")}} +
+ {bolt11.slice(0, 24)}…{bolt11.slice(-12)} +
+
+
+ +
+
+ +
+
+
+ {left > 0 ? t("app.invoice.waiting", { Time: clock(left) }) : t("app.invoice.checking")} +
+
+ +
+
+ ); +} diff --git a/web/miniapp/src/api.ts b/web/miniapp/src/api.ts new file mode 100644 index 0000000..b8f1518 --- /dev/null +++ b/web/miniapp/src/api.ts @@ -0,0 +1,172 @@ +import { initData } from "./tg"; + +// Every call carries the initData string Telegram gave the app. The core +// validates it each time; the app holds no session of its own. + +export class ApiError extends Error { + constructor( + public status: number, + public code: string, + message: string, + public upgradable = false, + ) { + super(message); + } +} + +export async function api(method: "GET" | "POST" | "PUT", path: string, body?: unknown): Promise { + let res: Response; + try { + res = await fetch("/app/api/" + path, { + method, + headers: { + Authorization: "tma " + initData(), + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch { + throw new ApiError(0, "network", ""); + } + let data: unknown = null; + try { + data = await res.json(); + } catch { + data = null; + } + if (!res.ok) { + const e = (data ?? {}) as { error?: string; message?: string; upgradable?: boolean }; + throw new ApiError(res.status, e.error ?? "internal", e.message ?? "", e.upgradable ?? false); + } + return data as T; +} + +export interface Tier { + max_size: number; + max_duration: number; + active_jobs: number; + daily_downloads: number; + daily_bytes: number; +} + +export interface Me { + id: number; + name: string; + lang: string; + lang_override: string; + dir: "ltr" | "rtl"; + languages: { code: string; name: string }[]; + quality: string; + pass_until: number; + balance: number; + source: string; + usage: { downloads: number; bytes: number }; + limits: Tier; + payments: boolean; + referral_link: string; + referral_count: number; + referral_reward: number; + support: string; + start_param: string; + bot: string; +} + +export interface Messages { + lang: string; + dir: "ltr" | "rtl"; + messages: Record>; +} + +export interface ProbeOption { + profile: string; + size?: number; +} + +export interface Probe { + url: string; + title: string; + uploader: string; + duration: number; + site: string; + options: ProbeOption[]; +} + +export interface Job { + id: string; + title: string; + profile: string; + status: "queued" | "running" | "delivering"; + stage?: string; + position?: number; + wait_seconds?: number; + progress: number; + can_cancel: boolean; + can_prioritize: boolean; + skip_price?: number; +} + +export interface HistoryItem { + id: string; + title: string; + profile: string; + size: number; + at: number; +} + +export interface Products { + enabled: boolean; + passes: { product: string; price: number }[]; + credit_packs: number[]; + credit_per_download: number; + paid: Tier; + invoice_seconds: number; +} + +export interface Purchase { + id: string; + product: string; + amount: number; + status: "pending" | "paid" | "expired" | "cancelled"; + expires_at: number; + paid_at: number; + bolt11?: string; + qr?: string; + balance?: number; + pass_until?: number; +} + +export interface Group { + id: string; + title: string; + balance: number; + pass_until: number; +} + +export interface GroupSettings { + enabled: boolean; + auto_detect: boolean; + delete_commands: boolean; + who_can_use: "everyone" | "pass_holders" | "admins"; + spend_rule: "anyone" | "admins" | "capped"; + spend_cap: number; + daily_cap: number; + max_size_mb: number; + max_duration: number; + quality: string; + lang: string; + allowed: string[]; + blocked: string[]; +} + +export interface GroupDetail extends Group { + settings: GroupSettings; + tier_max_size_mb: number; + tier_max_duration: number; +} + +export interface MemberUsage { + name: string; + downloads: number; + sats: number; + bytes: number; +} diff --git a/web/miniapp/src/i18n.ts b/web/miniapp/src/i18n.ts new file mode 100644 index 0000000..dddfed3 --- /dev/null +++ b/web/miniapp/src/i18n.ts @@ -0,0 +1,103 @@ +import type { Messages } from "./api"; + +// Texts come from the core, out of the same catalogs the bot uses. There +// is no literal user-facing text in this app. + +type Entry = string | Record; + +let messages: Record = {}; +let locale = "en"; +let plural = new Intl.PluralRules("en"); + +function supported(lang: string): string { + try { + return Intl.NumberFormat.supportedLocalesOf([lang])[0] ?? "en"; + } catch { + return "en"; + } +} + +export function setMessages(m: Messages): void { + messages = m.messages; + locale = supported(m.lang); + plural = new Intl.PluralRules(locale); + document.documentElement.lang = m.lang; + document.documentElement.dir = m.dir; +} + +export type Args = Record; + +// t looks a message up. A "Count" argument selects the plural form. +// A missing key shows as the key itself, so the gap is visible. +export function t(key: string, args?: Args): string { + let m = messages[key]; + if (m === undefined) return key; + if (typeof m !== "string") { + m = m[plural.select(Number(args?.Count ?? 0))] ?? m.other ?? ""; + } + return m.replace(/\{(\w+)\}/g, (_, name: string) => (args && name in args ? String(args[name]) : "")); +} + +export function has(key: string): boolean { + return key in messages; +} + +export function num(n: number): string { + return new Intl.NumberFormat(locale).format(n); +} + +export function sats(n: number): string { + return t("unit.sats", { Count: n, N: num(n) }); +} + +export function percent(fraction: number): string { + return new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(fraction); +} + +// size formats bytes the way the bot does: binary units, in the user's +// number format. +export function size(bytes: number): string { + const f = (v: number, digits: number) => + new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(v); + const k = 1024; + if (bytes < k) return f(bytes, 0) + " B"; + if (bytes < k * k) return f(bytes / k, 0) + " KB"; + if (bytes < k * k * k) { + const v = bytes / (k * k); + return f(v, v >= 100 ? 0 : 1) + " MB"; + } + return f(bytes / (k * k * k), 2) + " GB"; +} + +// clock formats a media length: 4:05 or 1:02:03. +export function clock(seconds: number): string { + const s = Math.max(0, Math.floor(seconds)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const pad = (n: number) => String(n).padStart(2, "0"); + return h > 0 ? `${h}:${pad(m)}:${pad(s % 60)}` : `${m}:${pad(s % 60)}`; +} + +// span says a waiting time in words, in the coarsest fitting unit. +export function span(seconds: number): string { + if (seconds < 60) return t("unit.seconds", { Count: Math.max(1, Math.round(seconds)) }); + if (seconds < 3600) return t("unit.minutes", { Count: Math.round(seconds / 60) }); + return t("unit.hours", { Count: Math.round(seconds / 3600) }); +} + +export function dateTime(ms: number): string { + return new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(new Date(ms)); +} + +export function day(ms: number): string { + return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(ms)); +} + +// profile names a download format the way the chat buttons do. +export function profile(p: string): string { + if (p === "best") return t("btn.best"); + if (/^\d+$/.test(p)) return t("btn.res", { Height: p }); + if (p === "mp3" || p === "m4a" || p === "thumb") return t("btn." + p); + if (p.startsWith("subs:")) return t("btn.subs", { Lang: p.slice(5) }); + return p; +} diff --git a/web/miniapp/src/main.tsx b/web/miniapp/src/main.tsx new file mode 100644 index 0000000..c1ea4ab --- /dev/null +++ b/web/miniapp/src/main.tsx @@ -0,0 +1,14 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; +import { tg } from "./tg"; +import "./styles.css"; + +tg?.ready(); +tg?.expand(); + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/web/miniapp/src/pages/Buy.tsx b/web/miniapp/src/pages/Buy.tsx new file mode 100644 index 0000000..7720fbf --- /dev/null +++ b/web/miniapp/src/pages/Buy.tsx @@ -0,0 +1,140 @@ +import { useState } from "react"; +import { api, type Group, type Products, type Purchase } from "../api"; +import { clock, num, sats, size, t } from "../i18n"; +import { Invoice } from "../Invoice"; +import { Cell, Empty, Loading, Section, useApp, useBack, useLoad } from "../ui"; + +// Buy is three steps: who it is for, what to buy, and the invoice. The +// price of a product is set by the core when the invoice is made; the +// numbers shown here are the same price list, for display. +export function Buy(props: { target?: string }) { + const { me, go, back, fail } = useApp(); + const products = useLoad(() => api("GET", "products"), []); + const groups = useLoad(() => api<{ groups: Group[] }>("GET", "groups"), []); + const [target, setTarget] = useState(props.target ?? null); + const [purchase, setPurchase] = useState(null); + const [busy, setBusy] = useState(false); + + const step = purchase ? 3 : target ? 2 : 1; + // Inside the flow the back button walks the steps before it leaves. + useBack( + step === 2 && !props.target + ? () => setTarget(null) + : step === 3 && purchase?.status !== "pending" + ? () => setPurchase(null) + : null, + ); + + const buy = async (product: string, amount: number) => { + if (busy) return; + setBusy(true); + try { + setPurchase(await api("POST", "purchase", { target, product, amount })); + } catch (e) { + fail(e); + } + setBusy(false); + }; + + const group = groups.data?.groups.find((g) => g.id === target); + const targetName = target === "me" ? t("app.buy.for_me") : (group?.title ?? t("app.buy.for_group")); + + return ( + + {(p) => + !p.enabled ? ( + {t("app.buy.unavailable")} + ) : ( + <> +
+ {[1, 2, 3].map((n) => ( + + ))} +
+ + {step === 1 && ( +
+ setTarget("me")} + /> + {groups.data?.groups.map((g) => ( + setTarget(g.id)} + /> + ))} +
+ )} + + {step === 2 && ( + <> +
+ {p.passes.map((x) => ( + {sats(x.price)}} + chevron + onClick={() => buy(x.product, 0)} + /> + ))} +
+
+ {p.credit_packs.map((amount) => ( + 0 + ? t("app.buy.credits_downloads", { Count: Math.floor(amount / p.credit_per_download) }) + : undefined + } + chevron + onClick={() => buy("credits", amount)} + /> + ))} +
+
+ + + + +
+ + )} + + {step === 3 && purchase && ( +
+
+ setPurchase((old) => (old ? { ...old, ...paid } : old))} + onDone={() => { + setPurchase(null); + // Opened from a group's wallet: return there. + if (props.target) back(); + else go({ tab: "home" }); + }} + /> +
+
+ )} + + ) + } +
+ ); +} + +function limit(value: number, format: (n: number) => string): string { + return value > 0 ? format(value) : t("app.limit.none"); +} diff --git a/web/miniapp/src/pages/GroupPage.tsx b/web/miniapp/src/pages/GroupPage.tsx new file mode 100644 index 0000000..384ba5b --- /dev/null +++ b/web/miniapp/src/pages/GroupPage.tsx @@ -0,0 +1,371 @@ +import { useEffect, useState } from "react"; +import { api, type GroupDetail, type GroupSettings, type MemberUsage } from "../api"; +import { dateTime, num, profile, sats, size, t } from "../i18n"; +import { Button, Cell, Empty, Loading, Section, Segmented, Select, Switch, useApp, useLoad, type GroupView } from "../ui"; + +const views: GroupView[] = ["overview", "settings", "wallet", "usage"]; +const qualities = ["", "best", "1080", "720", "480", "mp3"]; + +export function qualityOptions(askLabel: string) { + return qualities.map((q) => ({ value: q, label: q === "" ? askLabel : profile(q) })); +} + +export function GroupPage(props: { id: string; view: GroupView }) { + const [view, setView] = useState(props.view); + const group = useLoad(() => api("GET", "groups/" + props.id), [props.id]); + + return ( + + {(g) => ( + <> +
+ {g.title} +
+ value={view} onChange={setView} options={views.map((v) => ({ value: v, label: t("app.group.tab." + v) }))} /> + {view === "overview" && } + {view === "settings" && group.set({ ...g, settings: s })} />} + {view === "wallet" && group.set({ ...g, settings: s })} />} + {view === "usage" && } + + )} +
+ ); +} + +function who(s: GroupSettings): string { + return t("settings.who_" + s.who_can_use); +} + +function spend(s: GroupSettings): string { + return t("settings.spend_" + s.spend_rule); +} + +function Overview(props: { group: GroupDetail; open(v: GroupView): void }) { + const g = props.group; + const s = g.settings; + const pass = g.pass_until > Date.now(); + return ( + <> +
+
+
{t("app.group.balance")}
+
{sats(g.balance)}
+
+
+
{t("app.group.pass")}
+
{pass ? t("app.group.pass_on") : t("app.group.pass_off")}
+ {pass &&
{t("app.pass_until", { Until: dateTime(g.pass_until) })}
} +
+
+
+ + + + +
+
+
+ +
+
+ +
+
+ + ); +} + +// useDraft keeps an editable copy of the settings and saves it as a +// whole. The core validates every field again. +function useDraft(group: GroupDetail, onSaved: (s: GroupSettings) => void) { + const { notify, fail } = useApp(); + const [draft, setDraft] = useState(group.settings); + useEffect(() => setDraft(group.settings), [group.settings]); + const dirty = JSON.stringify(draft) !== JSON.stringify(group.settings); + const set = (key: K, value: GroupSettings[K]) => setDraft((d) => ({ ...d, [key]: value })); + const save = async () => { + try { + const r = await api<{ settings: GroupSettings }>("PUT", "groups/" + group.id + "/settings", draft); + onSaved(r.settings); + notify(t("app.saved")); + } catch (e) { + fail(e); + } + }; + return { draft, set, dirty, save }; +} + +function NumberInput(props: { value: number; onChange(n: number): void; label: string; max?: number }) { + return ( + { + const n = Math.max(0, Math.floor(Number(e.target.value) || 0)); + props.onChange(props.max && n > props.max ? props.max : n); + }} + /> + ); +} + +function Sites(props: { title: string; note: string; value: string[]; onChange(v: string[]): void }) { + const [text, setText] = useState(""); + const add = () => { + // Accept a pasted link as well as a bare host name. + const host = text + .trim() + .toLowerCase() + .replace(/^[a-z]+:\/\//, "") + .replace(/\/.*$/, "") + .replace(/^www\./, ""); + if (host && !props.value.includes(host)) props.onChange([...props.value, host]); + setText(""); + }; + return ( +
+
+ {props.value.length > 0 && ( +
+ {props.value.map((h) => ( + + ))} +
+ )} +
+ setText(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") add(); + }} + /> + +
+
+
+ ); +} + +function Settings(props: { group: GroupDetail; onSaved(s: GroupSettings): void }) { + const { me } = useApp(); + const { draft, set, dirty, save } = useDraft(props.group, props.onSaved); + const g = props.group; + return ( + <> +
+ set("enabled", v)} />} + /> + set("auto_detect", v)} />} + /> + set("delete_commands", v)} /> + } + /> +
+
+ set("who_can_use", v as GroupSettings["who_can_use"])} + options={(["everyone", "pass_holders", "admins"] as const).map((v) => ({ value: v, label: t("settings.who_" + v) }))} + /> + } + /> + set("quality", v)} + options={qualityOptions(t("quality.ask"))} + /> + } + /> + set("lang", v)} + options={[{ value: "", label: t("settings.lang_auto") }, ...me.languages.map((l) => ({ value: l.code, label: l.name }))]} + /> + } + /> +
+
+ set("max_size_mb", n)} + /> + } + /> + set("max_duration", n * 60)} + /> + } + /> +
+ set("allowed", v)} + /> + set("blocked", v)} + /> + + + ); +} + +function Wallet(props: { group: GroupDetail; onSaved(s: GroupSettings): void }) { + const { go, me } = useApp(); + const { draft, set, dirty, save } = useDraft(props.group, props.onSaved); + const g = props.group; + const pass = g.pass_until > Date.now(); + return ( + <> +
+
+
+
{t("app.group.balance")}
+
{sats(g.balance)}
+
{pass ? t("app.pass_until", { Until: dateTime(g.pass_until) }) : t("app.groups.no_pass")}
+
+ {me.payments && ( + + )} +
+
+
+ set("spend_rule", v as GroupSettings["spend_rule"])} + options={(["admins", "anyone", "capped"] as const).map((v) => ({ value: v, label: t("settings.spend_" + v) }))} + /> + } + /> + {draft.spend_rule === "capped" && ( + set("spend_cap", n)} />} + /> + )} + set("daily_cap", n)} />} + /> +
+ + + ); +} + +function Usage(props: { id: string }) { + const usage = useLoad(() => api<{ days: number; members: MemberUsage[] }>("GET", "groups/" + props.id + "/usage"), [props.id]); + return ( + + {(u) => ( +
+ {u.members.length === 0 ? ( + {t("app.group.usage_empty")} + ) : ( + + + + + + + + + + + {u.members.map((m, i) => ( + + + + + + + ))} + +
{t("app.group.col_member")}{t("app.group.col_downloads")}{t("app.group.col_volume")}{t("app.group.col_spent")}
{m.name}{num(m.downloads)}{size(m.bytes)}{sats(m.sats)}
+ )} +
+ )} +
+ ); +} diff --git a/web/miniapp/src/pages/Groups.tsx b/web/miniapp/src/pages/Groups.tsx new file mode 100644 index 0000000..97cdd3d --- /dev/null +++ b/web/miniapp/src/pages/Groups.tsx @@ -0,0 +1,32 @@ +import { api, type Group } from "../api"; +import { day, sats, t } from "../i18n"; +import { Cell, Empty, Loading, Section, useApp, useLoad } from "../ui"; + +export function Groups() { + const { go } = useApp(); + const groups = useLoad(() => api<{ groups: Group[] }>("GET", "groups"), []); + return ( +
+ + {(d) => + d.groups.length === 0 ? ( + {t("app.groups.empty")} + ) : ( + d.groups.map((g) => ( + Date.now() ? t("app.pass_until", { Until: day(g.pass_until) }) : t("app.groups.no_pass"), + ].join(" · ")} + chevron + onClick={() => go({ tab: "groups", group: g.id })} + /> + )) + ) + } + +
+ ); +} diff --git a/web/miniapp/src/pages/History.tsx b/web/miniapp/src/pages/History.tsx new file mode 100644 index 0000000..1f26de9 --- /dev/null +++ b/web/miniapp/src/pages/History.tsx @@ -0,0 +1,15 @@ +import { api, type HistoryItem } from "../api"; +import { t } from "../i18n"; +import { Empty, Loading, Section, useLoad } from "../ui"; +import { HistoryRow } from "./Home"; + +export function History() { + const list = useLoad(() => api<{ items: HistoryItem[] }>("GET", "history"), []); + return ( +
+ + {(d) => (d.items.length === 0 ? {t("app.history.empty")} : d.items.map((it) => ))} + +
+ ); +} diff --git a/web/miniapp/src/pages/Home.tsx b/web/miniapp/src/pages/Home.tsx new file mode 100644 index 0000000..b40b9e7 --- /dev/null +++ b/web/miniapp/src/pages/Home.tsx @@ -0,0 +1,189 @@ +import { useState } from "react"; +import { api, ApiError, type HistoryItem, type Probe } from "../api"; +import { clock, dateTime, num, profile, sats, size, t } from "../i18n"; +import { Button, Cell, errorText, Meter, Section, useApp, useLoad } from "../ui"; + +export function Home() { + const { me, go } = useApp(); + const recent = useLoad(() => api<{ items: HistoryItem[] }>("GET", "history?limit=5"), []); + const passActive = me.pass_until > Date.now(); + const lim = me.limits; + + return ( + <> +
+
+
{t("app.home.hello", { Name: me.name })}
+
{passActive ? t("app.home.pass_active") : t("app.home.plan_free")}
+
+ {passActive ? t("app.pass_until", { Until: dateTime(me.pass_until) }) : t("app.home.plan_free_hint")} +
+
+ {sats(me.balance)}} + chevron={me.payments} + onClick={me.payments ? () => go({ tab: "buy" }) : undefined} + /> +
+ +
+
+ + +
+
+ + + +
go({ tab: "home", page: "history" })}> + {t("app.home.all_history")} + + } + > + {recent.data && recent.data.items.length > 0 ? ( + recent.data.items.map((it) => ) + ) : ( +
{recent.loading ? "" : t("app.history.empty")}
+ )} +
+ + ); +} + +function Usage(props: { label: string; used: number; max: number; format(n: number): string }) { + const unlimited = props.max <= 0; + return ( +
+
+ {props.label} + + {unlimited + ? t("app.home.used_unlimited", { Used: props.format(props.used) }) + : t("app.home.used_of", { Used: props.format(props.used), Max: props.format(props.max) })} + +
+ +
+ ); +} + +export function HistoryRow(props: { item: HistoryItem }) { + const { notify, fail } = useApp(); + const it = props.item; + return ( + 0 ? size(it.size) : "", dateTime(it.at)].filter(Boolean).join(" · ")} + after={ + + } + /> + ); +} + +// PasteBox looks a link up and offers the formats, like a card in chat. +// What the user may download is decided by the core when a format is +// picked; this view only shows the answer. +function PasteBox() { + const { go, notify } = useApp(); + const [url, setUrl] = useState(""); + const [found, setFound] = useState(null); + const [error, setError] = useState<{ text: string; upgradable: boolean } | null>(null); + + const show = (e: unknown) => setError({ text: errorText(e), upgradable: e instanceof ApiError && e.upgradable }); + + const lookUp = async () => { + setError(null); + setFound(null); + try { + setFound(await api("POST", "probe", { url: url.trim() })); + } catch (e) { + show(e); + } + }; + + const start = async (p: string) => { + if (!found) return; + setError(null); + try { + await api("POST", "download", { url: found.url, profile: p }); + setFound(null); + setUrl(""); + notify(t("app.sent_to_chat")); + go({ tab: "queue" }); + } catch (e) { + show(e); + } + }; + + return ( +
+
+
+ setUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && url.trim()) void lookUp(); + }} + /> + +
+ {error && ( +
+
{error.text}
+ {error.upgradable && ( + + )} +
+ )} + {found && ( + <> +
+
{found.title || t("app.untitled")}
+
+ {[found.uploader, found.duration > 0 ? clock(found.duration) : "", found.site].filter(Boolean).join(" · ")} +
+
+
+ {found.options.map((o) => ( + + ))} +
+ + )} +
+
+ ); +} diff --git a/web/miniapp/src/pages/Profile.tsx b/web/miniapp/src/pages/Profile.tsx new file mode 100644 index 0000000..e6403ea --- /dev/null +++ b/web/miniapp/src/pages/Profile.tsx @@ -0,0 +1,105 @@ +import { api } from "../api"; +import { sats, t } from "../i18n"; +import { copyText, openTelegram } from "../tg"; +import { Button, Cell, Section, Select, Switch, useApp } from "../ui"; +import { qualityOptions } from "./GroupPage"; + +// Profile is the "Me" tab: preferences, the referral link and support. +export function Profile() { + const { me, go, notify, fail, reload } = useApp(); + + const update = async (body: { quality?: string; lang?: string }) => { + try { + await api("PUT", "me", body); + // A new language changes every text and maybe the direction, so + // the profile and the catalog are fetched again. + await reload(); + notify(t("app.saved")); + } catch (e) { + fail(e); + } + }; + + const audioOnly = me.quality === "mp3"; + const support = me.support.startsWith("@") ? "https://t.me/" + me.support.slice(1) : ""; + + return ( + <> +
+ void update({ quality: v })} + options={qualityOptions(t("quality.ask")).filter((o) => o.value !== "mp3")} + /> + } + /> + void update({ quality: v ? "mp3" : "" })} />} + /> +
+ +
+ void update({ lang: v || "auto" })} + options={[{ value: "", label: t("language.auto") }, ...me.languages.map((l) => ({ value: l.code, label: l.name }))]} + /> + } + /> +
+ +
0 ? t("app.me.referral_note", { Reward: sats(me.referral_reward) }) : undefined} + > +
+
{me.referral_link}
+
+
+ +
+
+ +
+
+
+ +
+ +
+ go({ tab: "home", page: "history" })} /> + openTelegram(support) : undefined} + /> +
+ + ); +} diff --git a/web/miniapp/src/pages/Queue.tsx b/web/miniapp/src/pages/Queue.tsx new file mode 100644 index 0000000..d9c7019 --- /dev/null +++ b/web/miniapp/src/pages/Queue.tsx @@ -0,0 +1,101 @@ +import { useState } from "react"; +import { api, type Job, type Purchase } from "../api"; +import { percent, profile, sats, span, t } from "../i18n"; +import { Invoice } from "../Invoice"; +import { confirm } from "../tg"; +import { Button, Empty, Loading, Meter, Section, Sheet, useApp, useLoad } from "../ui"; + +export function Queue() { + const { notify, fail } = useApp(); + const queue = useLoad(() => api<{ jobs: Job[] }>("GET", "queue"), [], 2000); + const [invoice, setInvoice] = useState(null); + + const cancel = async (j: Job) => { + if (!(await confirm(t("app.queue.cancel_confirm", { Title: j.title || t("app.untitled") })))) return; + try { + await api("POST", "queue/" + j.id + "/cancel"); + notify(t("app.queue.cancelled")); + } catch (e) { + fail(e); + } + queue.reload(); + }; + + const prioritize = async (j: Job) => { + try { + const r = await api<{ done: boolean; purchase?: Purchase }>("POST", "queue/" + j.id + "/prioritize"); + if (r.done) notify(t("app.queue.prioritized")); + else if (r.purchase) setInvoice(r.purchase); + } catch (e) { + fail(e); + } + queue.reload(); + }; + + return ( + <> +
+ + {(d) => + d.jobs.length === 0 ? ( + {t("app.queue.empty")} + ) : ( + d.jobs.map((j) => cancel(j)} onPrioritize={() => prioritize(j)} />) + ) + } + +
+ {invoice && ( + setInvoice(null)}> + queue.reload()} + onDone={() => { + setInvoice(null); + queue.reload(); + }} + /> + + )} + + ); +} + +function statusText(j: Job): string { + if (j.status === "queued") { + return t("app.queue.waiting", { Position: j.position ?? 1, Wait: span(j.wait_seconds ?? 0) }); + } + if (j.status === "delivering" || j.stage === "uploading") return t("app.queue.sending"); + if (j.stage === "processing") return t("app.queue.processing"); + return j.progress > 0 ? t("app.queue.downloading_pct", { Percent: percent(j.progress) }) : t("app.queue.downloading"); +} + +function JobRow(props: { job: Job; onCancel(): Promise; onPrioritize(): Promise }) { + const j = props.job; + const unknown = j.status !== "queued" && (j.progress <= 0 || j.stage === "processing" || j.status === "delivering"); + return ( +
+
+
{j.title || t("app.untitled")}
+
+ {profile(j.profile)} · {statusText(j)} +
+ {j.status !== "queued" && } + {(j.can_cancel || j.can_prioritize) && ( +
+ {j.can_prioritize && ( + + )} + {j.can_cancel && ( + + )} +
+ )} +
+
+ ); +} diff --git a/web/miniapp/src/styles.css b/web/miniapp/src/styles.css new file mode 100644 index 0000000..c931a0b --- /dev/null +++ b/web/miniapp/src/styles.css @@ -0,0 +1,623 @@ +/* Colors come from the Telegram theme, with fallbacks for a plain browser. + Layout uses logical properties only (inline-start, inline-end), so a + right-to-left language mirrors the whole app without extra rules. */ + +:root { + --bg: var(--tg-theme-secondary-bg-color, #efeff4); + --card: var(--tg-theme-section-bg-color, var(--tg-theme-bg-color, #ffffff)); + --text: var(--tg-theme-text-color, #111111); + --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, #ffffff); + --danger: var(--tg-theme-destructive-text-color, #d93025); + --line: var(--tg-theme-section-separator-color, rgba(128, 128, 128, 0.25)); + --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 { + margin: 0; + background: var(--bg); + color: var(--text); + font: 16px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + overscroll-behavior-y: none; +} + +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; +} + +/* --- sections and cells --------------------------------------------------- */ + +.section { + margin-block: 0 16px; +} + +.section-title { + display: flex; + justify-content: space-between; + align-items: baseline; + gap: 8px; + padding: 8px 12px 6px; + font-size: 13px; + text-transform: uppercase; + letter-spacing: 0.03em; + color: var(--header); +} + +.section-title button { + text-transform: none; + letter-spacing: 0; +} + +.card { + background: var(--card); + border-radius: var(--radius); + overflow: hidden; +} + +.pad { + padding: 12px; +} + +.cell { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + min-height: 48px; + padding: 10px 12px; + background: none; + border: 0; + border-block-end: 1px solid var(--line); + text-align: start; +} + +.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 { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cell-title.wrap { + white-space: normal; +} + +.cell-sub { + font-size: 13px; + color: var(--hint); + overflow-wrap: anywhere; +} + +.cell-after { + flex-shrink: 0; + color: var(--hint); + display: flex; + align-items: center; + gap: 8px; +} + +.chevron { + width: 8px; + height: 8px; + border-block-start: 2px solid var(--hint); + border-inline-end: 2px solid var(--hint); + transform: rotate(45deg); + opacity: 0.6; +} + +[dir="rtl"] .chevron { + transform: rotate(-135deg); +} + +.check { + color: var(--accent); + font-weight: 700; +} + +/* --- text ----------------------------------------------------------------- */ + +.hint { + color: var(--hint); + font-size: 13px; +} + +.note { + padding: 6px 12px 0; + color: var(--hint); + font-size: 13px; +} + +.big { + font-size: 28px; + font-weight: 700; + line-height: 1.15; +} + +.error { + color: var(--danger); +} + +.center { + text-align: center; +} + +.empty { + padding: 28px 16px; + text-align: center; + color: var(--hint); +} + +.mono { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12px; + overflow-wrap: anywhere; + direction: ltr; +} + +/* --- controls ------------------------------------------------------------- */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 44px; + padding: 8px 16px; + border: 0; + border-radius: 10px; + background: var(--accent); + color: var(--on-accent); + font-weight: 600; + cursor: pointer; +} + +.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 { + background: none; + color: var(--link); + padding-inline: 4px; + min-height: 0; + font-weight: 500; +} + +.btn:disabled { + opacity: 0.5; + cursor: default; +} + +.btn:active:not(:disabled) { + filter: brightness(0.93); +} + +.row { + display: flex; + gap: 8px; + align-items: center; +} + +.row.wrap { + flex-wrap: wrap; +} + +.row > .grow { + flex: 1; + min-width: 0; +} + +.stack { + display: flex; + flex-direction: column; + gap: 10px; +} + +.input, +.select { + width: 100%; + min-height: 44px; + padding: 8px 12px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--bg); + outline: none; +} + +.input:focus, +.select:focus { + border-color: var(--accent); +} + +.select:disabled { + opacity: 0.5; +} + +.select.compact, +.input.compact { + width: auto; + max-width: 55vw; + min-height: 36px; + padding: 4px 8px; +} + +.input.number { + width: 110px; + text-align: end; +} + +.switch { + position: relative; + width: 50px; + height: 30px; + flex-shrink: 0; + border: 0; + border-radius: 15px; + background: var(--line); + cursor: pointer; + transition: background 0.15s; +} + +.switch::after { + content: ""; + position: absolute; + inset-block-start: 3px; + inset-inline-start: 3px; + width: 24px; + height: 24px; + border-radius: 50%; + background: #fff; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); + transition: inset-inline-start 0.15s; +} + +.switch[aria-checked="true"] { + background: var(--accent); +} + +.switch[aria-checked="true"]::after { + inset-inline-start: 23px; +} + +.segmented { + display: flex; + padding: 3px; + margin-block-end: 12px; + border-radius: 10px; + background: var(--line); +} + +.segmented button { + flex: 1; + min-height: 34px; + padding: 4px 6px; + border: 0; + border-radius: 8px; + background: none; + font-size: 14px; + cursor: pointer; +} + +.segmented button[aria-selected="true"] { + background: var(--card); + font-weight: 600; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border: 0; + border-radius: 14px; + background: color-mix(in srgb, var(--accent) 14%, transparent); + color: var(--accent); + font-size: 14px; + cursor: pointer; +} + +/* --- progress ------------------------------------------------------------- */ + +.meter { + height: 6px; + margin-block: 6px 2px; + border-radius: 3px; + background: var(--line); + overflow: hidden; +} + +.meter > div { + height: 100%; + border-radius: 3px; + background: var(--accent); + transition: width 0.4s; +} + +.meter.busy > div { + width: 35% !important; + animation: slide 1.2s ease-in-out infinite alternate; +} + +@keyframes slide { + from { + margin-inline-start: 0; + } + to { + margin-inline-start: 65%; + } +} + +.spinner { + width: 22px; + height: 22px; + margin: 24px auto; + border: 3px solid var(--line); + border-block-start-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +.btn .spinner { + width: 16px; + height: 16px; + margin: 0; + border-width: 2px; + border-color: color-mix(in srgb, currentColor 30%, transparent); + border-block-start-color: currentColor; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +/* --- pieces --------------------------------------------------------------- */ + +.stats { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.stat { + padding: 12px; + border-radius: var(--radius); + background: var(--card); +} + +.stat .value { + font-size: 20px; + font-weight: 700; +} + +.steps { + display: flex; + gap: 6px; + margin: 4px 0 14px; +} + +.steps span { + flex: 1; + height: 4px; + border-radius: 2px; + background: var(--line); +} + +.steps span.on { + background: var(--accent); +} + +.qr { + display: block; + width: min(260px, 70vw); + height: auto; + margin: 8px auto; + padding: 8px; + border-radius: 12px; + background: #fff; + image-rendering: pixelated; +} + +.paid-mark { + width: 72px; + height: 72px; + margin: 12px auto; + border-radius: 50%; + background: var(--ok); + color: #fff; + font-size: 40px; + line-height: 72px; + text-align: center; +} + +.table { + width: 100%; + border-collapse: collapse; + font-size: 14px; +} + +.table th, +.table td { + padding: 10px 12px; + border-block-end: 1px solid var(--line); + text-align: end; + white-space: nowrap; +} + +.table th { + color: var(--hint); + font-weight: 500; + font-size: 12px; +} + +.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; +} + +/* --- tab bar, sheet, toast ------------------------------------------------ */ + +.tabs { + position: fixed; + inset-inline: 0; + inset-block-end: 0; + z-index: 10; + display: flex; + justify-content: center; + padding-block-end: var(--safe-bottom); + background: var(--bar); + border-block-start: 1px solid var(--line); +} + +.tabs button { + flex: 1; + max-width: 128px; + min-height: 56px; + padding: 6px 2px 4px; + border: 0; + background: none; + color: var(--hint); + font-size: 11px; + cursor: pointer; + position: relative; +} + +.tabs button[aria-current="page"] { + color: var(--accent); +} + +.tabs svg { + display: block; + width: 24px; + height: 24px; + margin: 0 auto 2px; +} + +.badge { + position: absolute; + inset-block-start: 4px; + inset-inline-start: calc(50% + 6px); + min-width: 18px; + padding: 0 5px; + border-radius: 9px; + background: var(--accent); + color: var(--on-accent); + font-size: 11px; + line-height: 18px; +} + +.sheet-back { + position: fixed; + inset: 0; + z-index: 20; + display: flex; + align-items: flex-end; + justify-content: center; + background: rgba(0, 0, 0, 0.45); +} + +.sheet { + width: 100%; + max-width: 640px; + max-height: 92vh; + overflow-y: auto; + padding: 16px 16px calc(16px + var(--safe-bottom)); + border-radius: 16px 16px 0 0; + background: var(--card); +} + +.toast { + position: fixed; + inset-inline: 12px; + inset-block-end: calc(72px + var(--safe-bottom)); + z-index: 30; + max-width: 616px; + margin: 0 auto; + padding: 12px 14px; + border-radius: 12px; + background: rgba(30, 30, 32, 0.94); + color: #fff; + font-size: 14px; + text-align: center; +} + +.toast.bad { + background: var(--danger); +} diff --git a/web/miniapp/src/tg.ts b/web/miniapp/src/tg.ts new file mode 100644 index 0000000..f6730a2 --- /dev/null +++ b/web/miniapp/src/tg.ts @@ -0,0 +1,90 @@ +// A thin, typed view of the parts of Telegram's Mini App bridge this app +// uses. Everything is optional: outside Telegram the object is missing and +// the app shows a notice instead of working. + +interface BackButton { + show(): void; + hide(): void; + onClick(cb: () => void): void; + offClick(cb: () => void): void; +} + +interface Haptics { + impactOccurred(style: "light" | "medium" | "heavy" | "rigid" | "soft"): void; + notificationOccurred(type: "error" | "success" | "warning"): void; + selectionChanged(): void; +} + +export interface WebApp { + initData: string; + initDataUnsafe: { start_param?: string }; + colorScheme: "light" | "dark"; + version: string; + isVersionAtLeast(v: string): boolean; + ready(): void; + expand(): void; + close(): void; + openLink(url: string): void; + openTelegramLink(url: string): void; + showConfirm(message: string, cb: (ok: boolean) => void): void; + BackButton: BackButton; + HapticFeedback: Haptics; +} + +export const tg: WebApp | undefined = (window as unknown as { Telegram?: { WebApp?: WebApp } }).Telegram?.WebApp; + +export function initData(): string { + return tg?.initData ?? ""; +} + +export function haptic(type: "error" | "success" | "warning" | "tap"): void { + try { + if (type === "tap") tg?.HapticFeedback?.selectionChanged(); + else tg?.HapticFeedback?.notificationOccurred(type); + } catch { + // Old clients have no haptics. Nothing depends on them. + } +} + +// confirm asks a yes or no question with Telegram's native dialog. +export function confirm(message: string): Promise { + return new Promise((resolve) => { + if (tg && tg.isVersionAtLeast("6.2")) tg.showConfirm(message, resolve); + else resolve(window.confirm(message)); + }); +} + +// openExternal opens a page in the system browser, keeping the app open. +export function openExternal(url: string): void { + if (tg) tg.openLink(url); + else window.open(url, "_blank", "noopener"); +} + +// openTelegram opens a t.me link inside Telegram. +export function openTelegram(url: string): void { + if (tg) tg.openTelegramLink(url); + else window.open(url, "_blank", "noopener"); +} + +export async function copyText(text: string): Promise { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + // Some web views refuse the async clipboard. The old way still works. + const el = document.createElement("textarea"); + el.value = text; + el.style.position = "fixed"; + el.style.opacity = "0"; + document.body.appendChild(el); + el.select(); + let ok = false; + try { + ok = document.execCommand("copy"); + } catch { + ok = false; + } + el.remove(); + return ok; + } +} diff --git a/web/miniapp/src/ui.tsx b/web/miniapp/src/ui.tsx new file mode 100644 index 0000000..f5a446a --- /dev/null +++ b/web/miniapp/src/ui.tsx @@ -0,0 +1,306 @@ +import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react"; +import type { Me } from "./api"; +import { ApiError } from "./api"; +import { haptic, tg } from "./tg"; +import { t } from "./i18n"; + +// --- app context ------------------------------------------------------------- + +export type Tab = "home" | "queue" | "buy" | "groups" | "me"; + +export type Route = + | { tab: Tab } + | { tab: "home"; page: "history" } + | { tab: "buy"; target: string } + | { tab: "groups"; group: string; view?: GroupView }; + +export type GroupView = "overview" | "settings" | "wallet" | "usage"; + +export interface Ctx { + me: Me; + route: Route; + go(route: Route): void; + back(): void; + notify(text: string, bad?: boolean): void; + // fail shows an error from the API in the user's language. + fail(err: unknown): void; + reload(): Promise; +} + +export const AppContext = createContext(null); + +export function useApp(): Ctx { + const ctx = useContext(AppContext); + if (!ctx) throw new Error("no app context"); + return ctx; +} + +export function errorText(err: unknown): string { + if (err instanceof ApiError) { + if (err.message) return err.message; + if (err.code === "network") return t("app.error.network"); + } + return t("app.error.generic"); +} + +// --- hooks ------------------------------------------------------------------- + +export interface Loaded { + data: T | null; + error: unknown; + loading: boolean; + reload(): void; + set(v: T): void; +} + +// useLoad fetches once, and again every `every` milliseconds while the +// page is visible. Polling pauses in the background. +export function useLoad(fetcher: () => Promise, deps: unknown[], every = 0): Loaded { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + const [tick, setTick] = useState(0); + const fn = useRef(fetcher); + fn.current = fetcher; + + useEffect(() => { + let alive = true; + let timer: number | undefined; + const run = () => { + fn.current() + .then((v) => { + if (alive) { + setData(v); + setError(null); + } + }) + .catch((e) => alive && setError(e)) + .finally(() => { + if (!alive) return; + setLoading(false); + if (every > 0) timer = window.setTimeout(loop, every); + }); + }; + const loop = () => { + if (document.hidden) timer = window.setTimeout(loop, every); + else run(); + }; + run(); + return () => { + alive = false; + window.clearTimeout(timer); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [...deps, tick, every]); + + return { data, error, loading, reload: () => setTick((n) => n + 1), set: setData }; +} + +// useBack shows Telegram's back button while a handler is set. Several +// can be active at once (a page inside a page); the newest one gets the +// press. +const backHandlers: { current: (() => void) | null }[] = []; +let backWired = false; + +function syncBack(): void { + if (!tg) return; + if (!backWired) { + tg.BackButton.onClick(() => backHandlers[backHandlers.length - 1]?.current?.()); + backWired = true; + } + if (backHandlers.length > 0) tg.BackButton.show(); + else tg.BackButton.hide(); +} + +export function useBack(handler: (() => void) | null): void { + const fn = useRef(handler); + fn.current = handler; + const active = handler !== null; + useEffect(() => { + if (!active) return; + backHandlers.push(fn); + syncBack(); + return () => { + const i = backHandlers.indexOf(fn); + if (i >= 0) backHandlers.splice(i, 1); + syncBack(); + }; + }, [active]); +} + +// --- components -------------------------------------------------------------- + +export function Section(props: { title?: string; action?: ReactNode; note?: string; children: ReactNode }) { + return ( +
+ {(props.title || props.action) && ( +
+ {props.title} + {props.action} +
+ )} +
{props.children}
+ {props.note &&
{props.note}
} +
+ ); +} + +export function Cell(props: { + title: ReactNode; + sub?: ReactNode; + after?: ReactNode; + before?: ReactNode; + wrap?: boolean; + chevron?: boolean; + onClick?: () => void; +}) { + const body = ( + <> + {props.before} +
+
{props.title}
+ {props.sub &&
{props.sub}
} +
+ {(props.after || props.chevron) && ( +
+ {props.after} + {props.chevron && } +
+ )} + + ); + return props.onClick ? ( + + ) : ( +
{body}
+ ); +} + +export function Button(props: { + children: ReactNode; + onClick?: () => void | Promise; + kind?: "primary" | "soft" | "danger" | "plain"; + small?: boolean; + wide?: boolean; + disabled?: boolean; +}) { + const [busy, setBusy] = useState(false); + const alive = useRef(true); + useEffect( + () => () => { + alive.current = false; + }, + [], + ); + const click = () => { + if (busy || !props.onClick) return; + haptic("tap"); + const r = props.onClick(); + if (r instanceof Promise) { + setBusy(true); + r.finally(() => alive.current && setBusy(false)); + } + }; + const cls = ["btn", props.kind && props.kind !== "primary" ? props.kind : "", props.small ? "small" : "", props.wide ? "wide" : ""]; + return ( + + ); +} + +export function Switch(props: { checked: boolean; onChange(v: boolean): void; label: string }) { + return ( + + ))} + + ); +} + +export function Meter(props: { value: number; busy?: boolean }) { + const pct = Math.max(0, Math.min(1, props.value)) * 100; + return ( +
+
+
+ ); +} + +export function Spinner() { + return
; +} + +export function Empty(props: { children: ReactNode }) { + return
{props.children}
; +} + +// Loading renders the three states of a fetch: waiting, failed, ready. +export function Loading(props: { of: Loaded; children(data: T): ReactNode }) { + const { data, error, loading, reload } = props.of; + if (data !== null) return <>{props.children(data)}; + if (loading) return ; + return ( + +

{errorText(error)}

+ +
+ ); +} + +export function Sheet(props: { children: ReactNode; onClose(): void }) { + return ( +
+
e.stopPropagation()}> + {props.children} +
+
+ ); +} diff --git a/web/miniapp/tsconfig.json b/web/miniapp/tsconfig.json new file mode 100644 index 0000000..947ab28 --- /dev/null +++ b/web/miniapp/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2021", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/web/miniapp/vite.config.ts b/web/miniapp/vite.config.ts new file mode 100644 index 0000000..ec00da8 --- /dev/null +++ b/web/miniapp/vite.config.ts @@ -0,0 +1,57 @@ +import { createHash } from "node:crypto"; +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { defineConfig, type Plugin } from "vite"; +import react from "@vitejs/plugin-react"; + +// sourceStamp writes a hash of everything the build is made from next to +// the build. The Go test in this directory computes the same hash, so a +// change under src that was committed without a rebuild fails the tests. +const stamped = ["index.html", "package.json", "package-lock.json", "tsconfig.json", "vite.config.ts"]; + +function walk(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)], + ); +} + +function sourceStamp(): Plugin { + return { + name: "source-stamp", + apply: "build", + closeBundle() { + const hash = createHash("sha256"); + const files = [...stamped, ...walk("src")].map((f) => f.split("\\").join("/")).sort(); + for (const f of files) { + hash.update(f + "\0"); + hash.update(readFileSync(f)); + hash.update("\0"); + } + writeFileSync("dist/source.sha256", hash.digest("hex") + "\n"); + }, + }; +} + +// The app is served by the core under /app/ and embedded in its binary. +// File names are stable so a rebuild changes as few files as possible; +// the core sends an ETag per file, so caches still notice a new build. +export default defineConfig({ + base: "/app/", + plugins: [react(), sourceStamp()], + build: { + outDir: "dist", + emptyOutDir: true, + target: "es2020", + rollupOptions: { + output: { + entryFileNames: "assets/app.js", + chunkFileNames: "assets/[name].js", + assetFileNames: "assets/[name][extname]", + }, + }, + }, + server: { + // npm run dev: API calls go to a core running locally. + proxy: { "/app/api": "http://localhost:8080", "/pay": "http://localhost:8080" }, + }, +});