diff --git a/.env.example b/.env.example index b487bf4..b5e54a7 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,15 @@ PUBLIC_URL= # docs/OPERATIONS.md. The app is served by the core under /app/. MINIAPP_ENABLED=false +# Set the bot's name, description and short description in every language +# from the catalogs (profile.* in locales/*.toml). false keeps whatever is +# set in @BotFather. +TELEGRAM_SET_PROFILE=true + +# Add the pseudo-locale en-XA (accented, bracketed English) for checking +# that every text comes from the catalog. Only owners can pick it. +I18N_PSEUDO=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/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6a070d8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,75 @@ +# Checks for every push and pull request. The same steps run locally with +# "make check", "make test-postgres" and "make miniapp". +name: ci + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + go: + name: Go (SQLite, race detector) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: go.mod + - name: gofmt + run: make fmt + - name: go vet + run: go vet ./... + # Every catalog has every message of the source, with the same + # placeholders, tags and commands; no message is unused and no used + # message is missing. This is the translation completeness check. + - name: Translations + run: go test -count=1 ./locales/ ./internal/i18n/ + - name: Tests + run: go test -race -count=1 ./... + + postgres: + name: Go (Postgres) + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: dlbot + POSTGRES_PASSWORD: dlbot + POSTGRES_DB: dlbot_test + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U dlbot" --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: go.mod + - name: Tests + run: make test-postgres PG_DSN='postgres://dlbot:dlbot@127.0.0.1:5432/dlbot_test?sslmode=disable' + + miniapp: + name: Mini App + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + cache-dependency-path: web/miniapp/package-lock.json + - uses: actions/setup-go@v7 + with: + go-version-file: go.mod + - name: Build + run: make miniapp + # The committed build must be what the sources produce. + - name: Build is committed + run: git diff --exit-code -- web/miniapp/dist + - name: Browser test + run: | + npx --prefix web/miniapp playwright-core install --with-deps chromium + web/miniapp/e2e/run.sh diff --git a/Makefile b/Makefile index 8566a0b..6279171 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 miniapp miniapp-e2e test test-postgres race vet fmt check run e2e acceptance clean +.PHONY: all build faketelegram miniapp miniapp-e2e i18n-check test test-postgres race vet fmt check run e2e acceptance clean all: check build @@ -24,6 +24,11 @@ miniapp: miniapp-e2e: web/miniapp/e2e/run.sh +# Translation checks only: every catalog complete and consistent with the +# source, no unused or missing message IDs, Telegram's length limits. +i18n-check: + $(GO) test -count=1 ./locales/ ./internal/i18n/ + test: $(GO) test ./... diff --git a/README.md b/README.md index a81b52d..afd35a6 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,10 @@ and in groups. Written in Go on top of yt-dlp. 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. +- English, Spanish and Dutch throughout: messages, buttons, command menus, + the bot's profile texts and the Mini App, with numbers, sizes and dates + in the language's own format. Each user's Telegram language is + followed, and `/language` overrides it; `/grouplang` sets a group's. - Friendly, translated error messages. Raw tool output stays in the logs. ## Quick start with docker compose @@ -185,6 +189,7 @@ 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 i18n-check # translation completeness and consistency only make miniapp # rebuild the Mini App front end after changing web/miniapp make miniapp-e2e # click through the Mini App in headless Chromium ``` @@ -202,6 +207,7 @@ change it. A test fails when `dist` is older than its sources. - [docs/OPERATIONS.md](docs/OPERATIONS.md): deploying and running it. - [docs/WORKERS.md](docs/WORKERS.md): adding download workers, tags, drain. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit. +- [docs/TRANSLATING.md](docs/TRANSLATING.md): editing a catalog, adding a language. - [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md): decisions and verified facts. ## Layout diff --git a/config.example.toml b/config.example.toml index 66d4221..fef2988 100644 --- a/config.example.toml +++ b/config.example.toml @@ -12,6 +12,9 @@ public_url = "" # The Mini App, served under /app/. Needs an https public_url. miniapp = false +# Add the pseudo-locale en-XA for testing translations. Owners only. +i18n_pseudo = false + # Who looks links up for the card: "auto", "local" or "worker". probe_mode = "auto" @@ -21,6 +24,7 @@ mode = "polling" # polling or webhook webhook_url = "" max_upload_mb = 50 # 2000 with a local Bot API server update_workers = 8 +set_profile = true # name and descriptions per language from the catalogs [http] listen = ":8080" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ae7ddf6..52f2ee8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -408,8 +408,23 @@ The Docker image rebuilds the front end from source. Handlers never contain user-facing text. They call `i18n.Bundle` with a message ID. `HTML` escapes arguments for Telegram's HTML parse mode, `T` -returns plain text for buttons and callback answers. Sizes, durations and -percentages are formatted per locale. Callback data contains IDs only. +returns plain text for buttons and callback answers. Sizes, numbers, +durations, percentages and dates are formatted per locale. Callback data +contains IDs only. + +Which language a message is in: + +| Where | Language | +| --- | --- | +| Private chat, Mini App | the user's `/language` choice, else their Telegram language, else English | +| Group | the group's `/grouplang`, else the requester's language | +| Invoice memo, receipts | the language of the person who bought | +| Command menu | Telegram picks it by the app's language; a user or group with its own choice gets a chat menu in that language | + +The fallback chain for one message is the exact tag, its base language, +then English, so a partial regional catalog (es-PY) only needs the lines +that differ. `locales/catalog_test.go` keeps the catalogs and the code in +step; see [TRANSLATING.md](TRANSLATING.md). ## Secrets diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index d16980f..1d23648 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -655,3 +655,118 @@ Checked against https://core.telegram.org/bots/webapps on 2026-11-18. 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. + +## Phase 7 + +### Verified Bot API facts + +Checked against https://core.telegram.org/bots/api (Bot API 10.4) on +2026-11-18, and against telego v1.13.0. + +- `setMyCommands` takes at most 100 commands, a scope, and a two-letter + ISO 639-1 `language_code`. Without a code the list applies to users + whose language has no list of its own. A command is 1 to 32 lowercase + letters, digits or underscores; a description 1 to 256 characters. +- Telegram picks the menu in this order: chat scope with the user's + language, chat scope, then all private chats (or, in groups, chat + administrators, chat, all chat administrators, all group chats), then + default, each with and then without the language. +- `setMyName` (0 to 64 characters), `setMyDescription` (0 to 512, shown + in an empty chat) and `setMyShortDescription` (0 to 120, shown on the + profile and when the bot is shared) take the same `language_code`. +- `deleteMyCommands` removes the list of a scope and language. + +### Languages + +- English is the source and the fallback. Spanish and Dutch ship + complete. A user gets their Telegram language when a catalog matches + it, regional variants included (es-PY uses Spanish), and English + otherwise. `/language` (or the Mini App) overrides that per user; + `/grouplang` per group. +- Spanish: neutral Latin American with "tú". Paraguay speaks "vos", but + "tú" is what written Spanish across the region expects and is read + without friction in Paraguay; the vocabulary avoids words that sound + odd there. No opening `¿` or `¡`, as asked; a test enforces it. +- Dutch: informal "je". +- Owner texts are translated too. Owners pick their language like anyone. +- Command names, their arguments (`/spending admins`) and product IDs + stay English in every language. The bot parses them. +- The invoice memo, which wallets show, is the brand name plus the + product in the payer's language. + +### Menus and profile + +- At startup the core publishes three menus in every language: private + chats (download, account and preference commands), group members + (download commands, the group wallet and pass) and group admins (the + same plus the settings commands). Owner commands are never listed. + `/app` is listed only when the Mini App is on. +- The source language is published without a language code, so it is + also the menu for languages without a catalog. +- Telegram chooses menus by the language of the user's app, not by the + bot's setting. So when a user picks a language in the bot, the core + sets a menu for that private chat alone; "follow my Telegram language" + deletes it. `/grouplang` does the same for the group's member and + admin menus. These calls are limited to six per minute per chat. +- Chat menus are not rewritten when a catalog changes. They refresh the + next time that user or group changes language. The general menus are + rewritten at every start and on `/reload i18n`. +- The bot's name, description and short description are set per + language from `profile.*`, but only when the text changed since the + last time it went through, because Telegram limits these calls + hard. `TELEGRAM_SET_PROFILE=false` leaves what was set in @BotFather. + A change made in @BotFather is overwritten only when the catalog text + changes. + +### Formatting + +- Numbers use the language's grouping and decimal marks (Go's + `golang.org/x/text`, and `Intl` in the Mini App): "1.000 sats", + "10,0 MB" in Spanish and Dutch. +- Dates are written from the catalog (`format.date`, `format.datetime`, + `format.months`): "18 nov 2026, 12:05 UTC". Always UTC, and labeled: + the bot does not know the reader's time zone. Limits reset at midnight + UTC, which the texts say. +- Durations in words use the plural rules of the language ("5 minutos"). + Media lengths are written as 4:05 everywhere. + +### Completeness check + +- `locales/catalog_test.go` is the check CI runs (`make i18n-check`). + For every catalog it fails on: a message missing or extra compared with + the source, a plural that is plain elsewhere or lacks `one`, a changed + set of placeholders, HTML tags or commands, broken braces, empty + texts, stray spaces, em dashes, inverted marks in Spanish, menu and + profile texts over Telegram's limits, button labels over 40 + characters, a month list that is not twelve long, and a duplicate + language name. It also flags longer texts identical to English, except + where they are meant to be (the brand name in the invoice memo). +- It also reads the code. Every message of the source must be used, + either by its full ID or by a prefix or suffix the code builds IDs from + (`"error." + code`, `name + ".list"`), and every ID-shaped string in the + code whose table exists must be in the catalog. Tests are not counted. + `web/miniapp/embed_test.go` does the same for the Mini App. +- `.github/workflows/ci.yml` runs this, the whole suite with the race + detector, the suite on Postgres, and the Mini App build and browser + test. It was written for GitHub Actions and has not run there yet; + every step in it was run here by hand. + +### Pseudo-locale + +- `I18N_PSEUDO=true` makes `en-XA` from the English catalog at load time: + accented letters, brackets, a third longer, with placeholders, tags, + entities, commands, links and mentions kept. Plurals and dates keep + working. +- It is hidden from users and offered to owners only, in `/language`, + `/grouplang` and the Mini App. It is never published to Telegram + (not a two-letter code). + +### Fixed on the way + +- The test helper that sets up a waiting download picked the first "In + the queue" status edit after the second user's press, from any chat. + Under load a late edit of the first user's status could match, and the + test then pressed the wrong button. It now matches the second user's + chat only. This is the likely cause of the one Postgres failure of + `TestSkipTheQueueWithInvoice` reported in Phase 4, which uses the same + helper. The bot itself was right in both cases. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 393468a..1b883d6 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -174,6 +174,20 @@ 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. +## Languages, menus and the bot's profile + +At every start the core publishes its command menus in every language it +has a catalog for, and sets the bot's name, description and short +description per language from the catalogs. The profile texts are only +sent again when they change, because Telegram rate limits those calls. + +- To keep a name or description you set in @BotFather, set + `TELEGRAM_SET_PROFILE=false`. Or edit `profile.*` in the catalogs. +- To change any text, edit `locales/*.toml` and rebuild, or run with + `LOCALES_DIR` pointing at a copy of `locales/` and send `/reload i18n`. +- `I18N_PSEUDO=true` adds a test language for owners, see + [TRANSLATING.md](TRANSLATING.md). + ## Health and logs - `GET /healthz` on the core answers 200 while the database is reachable. diff --git a/docs/TRANSLATING.md b/docs/TRANSLATING.md new file mode 100644 index 0000000..89615d8 --- /dev/null +++ b/docs/TRANSLATING.md @@ -0,0 +1,88 @@ +# Translating the bot + +Every text the bot and the Mini App show lives in one catalog per language +in `locales/`. English (`en.toml`) is the source. Spanish (`es.toml`) and +Dutch (`nl.toml`) ship complete. + +## How a catalog looks + +```toml +[status] +queued = "In the queue. Position {{.Position}}, about {{.Wait}}." + +[unit.minutes] +one = "{{.Count}} minute" +other = "{{.Count}} minutes" +``` + +- A table plus a key is a message ID: `status.queued`. +- `{{.Name}}` is filled in by the bot. Keep it exactly as it is; you may + move it within the sentence. +- A table whose keys are `one`, `other` (and for some languages `few`, + `many`, ...) is a plural. The bot picks the form from `Count` using the + CLDR rules of the language. Give at least `one` and `other`. +- Most chat texts are Telegram HTML. Keep ``, ``, `` and the + line breaks. Do not add new tags. +- Commands (`/dl`, `/help`) and the arguments shown in `` examples + (`/spending admins`) are not translated: the bot only understands them + as they are. +- The `[app]` table is the Mini App. It is plain text, no HTML. +- `[menu]` is Telegram's command menu (up to 256 characters each, one + line). `[profile]` is the bot's name (64), the description shown in an + empty chat (512) and the short description on the profile (120). +- `[format]` says how dates are written: twelve short month names, and + the order of day, month, year and time. +- Do not use the words `id`, `description`, `hash`, `leftdelim`, + `rightdelim`, `zero`, `one`, `two`, `few`, `many` or `other` as a key + name. The library reserves them. +- No em dashes anywhere. + +## Adding a language + +1. Copy `en.toml` to `.toml`, where the code is a two-letter ISO + 639-1 language code (`pt.toml`, `de.toml`). Telegram publishes menus + and profile texts per two-letter code only. A regional catalog + (`pt-BR.toml`) works for messages, but shares the menu of its base + language. +2. Translate every value. Change `language.name` to the language's own + name for itself ("Português"). +3. Run the checks: + + ```sh + make i18n-check + ``` + + They fail on a missing or extra message, a changed placeholder, tag or + command, a missing plural form, a text over Telegram's length limit, an + em dash, and on longer texts left identical to English. +4. Restart the core. The new language shows up in `/language`, in the + Mini App, in the menus and on the bot's profile. Users whose Telegram + is set to that language get it without doing anything. + +Without a restart: run the core with `LOCALES_DIR=/path/to/locales` and +send `/reload i18n` as an owner. A catalog that fails to load leaves the +old ones in use and says why. + +A right-to-left language (Arabic, Hebrew, Persian, Urdu) needs nothing +extra. The Mini App mirrors its layout by itself. + +## Checking a translation in place + +`I18N_PSEUDO=true` adds a pseudo-locale, `en-XA`: English with every +letter accented and every text in brackets, a third longer. Owners can +pick it with `/language` or in the Mini App. Text that still reads as +plain English while it is on did not come from the catalog; text cut off +before its closing bracket has too little room. + +## The Spanish catalog + +Neutral Latin American Spanish, with words that read naturally in +Paraguay: "tú" forms, "enlace", "descargar" and "bajar", "billetera", +"fila" for the queue, "factura" for a Lightning invoice. Questions and +exclamations are written without the opening `¿` and `¡`; the checks +enforce that. + +## The Dutch catalog + +Informal ("je"), as most Dutch apps are. "Pas", "tegoed", "factuur", +"wachtrij"; "wallet" is left as it is, as Dutch Lightning users say it. diff --git a/internal/api/miniapp.go b/internal/api/miniapp.go index 22c351a..b5101cb 100644 --- a/internal/api/miniapp.go +++ b/internal/api/miniapp.go @@ -222,7 +222,7 @@ func (m *MiniApp) me(w http.ResponseWriter, r *http.Request, s *session) { refs, _ := m.Store.CountReferrals(ctx, s.user.ID) var langs []map[string]string for _, l := range m.I18n.Langs() { - if !m.I18n.Hidden(l) { + if !m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID) { langs = append(langs, map[string]string{"code": l, "name": m.I18n.T(l, "language.name", nil)}) } } @@ -284,7 +284,7 @@ func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { lang := "" if *in.Lang != "" && *in.Lang != "auto" { for _, l := range m.I18n.Langs() { - if l == *in.Lang { + if l == *in.Lang && (!m.I18n.Hidden(l) || m.Cfg.IsOwner(s.user.ID)) { lang = l } } @@ -297,6 +297,9 @@ func (m *MiniApp) updateMe(w http.ResponseWriter, r *http.Request, s *session) { m.explain(w, s, err) return } + if lang != s.user.LangOverride { + m.Bot.SyncUserMenu(ctx, s.user.ID, lang) + } } m.ok(w, map[string]bool{"ok": true}) } @@ -736,10 +739,14 @@ func (m *MiniApp) groupSettings(w http.ResponseWriter, r *http.Request, s *sessi MaxSizeMB: in.MaxSizeMB, MaxDuration: in.MaxDuration, Quality: in.Quality, Lang: in.Lang, Allowed: allowed, Blocked: blocked, } + old, _ := m.Store.GetGroupSettings(r.Context(), g.ChatID) if err := m.Store.SaveGroupSettings(r.Context(), st); err != nil { m.explain(w, s, err) return } + if old != nil && old.Lang != st.Lang { + m.Bot.SyncGroupMenu(r.Context(), g.ChatID, st.Lang) + } m.Log.Info("group settings changed in the mini app", "chat_id", g.ChatID, "by", s.user.ID) m.ok(w, map[string]any{"settings": toSettingsJSON(st)}) } diff --git a/internal/app/app.go b/internal/app/app.go index f38e96d..8ef11a7 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -197,7 +197,11 @@ func New(ctx context.Context, opts Options) (*App, error) { if cfg.LocalesDir != "" { catalogs = os.DirFS(cfg.LocalesDir) } - tr, err := i18n.Load(catalogs, log) + var i18nOpts []i18n.Option + if cfg.Pseudo { + i18nOpts = append(i18nOpts, i18n.WithPseudo()) + } + tr, err := i18n.Load(catalogs, log, i18nOpts...) if err != nil { return fail(err) } diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 3355890..858cad9 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -778,29 +778,6 @@ func TestRestartResumesQueuedJob(t *testing.T) { h.waitJobs(db.JobDone, 1) } -func TestCommandMenuIsRegistered(t *testing.T) { - h := start(t, nil, nil) - calls := h.srv.Calls("setMyCommands") - if len(calls) == 0 { - t.Fatal("setMyCommands was not called") - } - var cmds []struct { - Command string `json:"command"` - Description string `json:"description"` - } - if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil { - t.Fatal(err) - } - if len(cmds) != 10 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" { - t.Fatalf("commands = %+v", cmds) - } - for _, c := range cmds { - if c.Command != strings.ToLower(c.Command) || strings.HasPrefix(c.Description, "menu.") { - t.Errorf("bad menu entry %+v", c) - } - } -} - func TestHealthEndpoint(t *testing.T) { h := start(t, nil, nil) resp, err := http.Get("http://" + h.app.HTTP.Addr() + "/healthz") diff --git a/internal/app/i18n_test.go b/internal/app/i18n_test.go new file mode 100644 index 0000000..dabfa05 --- /dev/null +++ b/internal/app/i18n_test.go @@ -0,0 +1,315 @@ +package app_test + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + "unicode/utf8" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +type menuEntry struct { + Command string `json:"command"` + Description string `json:"description"` +} + +type scope struct { + Type string `json:"type"` + ChatID int64 `json:"chat_id"` +} + +func menuOf(t *testing.T, c fakeserver.Call) []menuEntry { + t.Helper() + var cmds []menuEntry + if err := json.Unmarshal([]byte(c.Params["commands"]), &cmds); err != nil { + t.Fatalf("commands of %+v: %v", c.Params, err) + } + return cmds +} + +func scopeOf(c fakeserver.Call) scope { + var s scope + _ = json.Unmarshal([]byte(c.Params["scope"]), &s) + return s +} + +// menuFor finds the setMyCommands call for a scope and language code. +func menuFor(t *testing.T, calls []fakeserver.Call, scopeType, lang string, chat int64) []menuEntry { + t.Helper() + var found []menuEntry + for _, c := range calls { + if s := scopeOf(c); s.Type == scopeType && s.ChatID == chat && c.Params["language_code"] == lang { + found = menuOf(t, c) + } + } + if found == nil { + t.Fatalf("no setMyCommands for scope %s, chat %d, language %q", scopeType, chat, lang) + } + return found +} + +func describe(menu []menuEntry, cmd string) string { + for _, e := range menu { + if e.Command == cmd { + return e.Description + } + } + return "" +} + +// --- acceptance: menus and profile in every language ------------------------ + +func TestMenusAndProfileArePublishedPerLanguage(t *testing.T) { + h := start(t, nil, nil) + calls := h.srv.Calls("setMyCommands") + + want := map[string]string{"": "Download a video from a link", "es": "Descargar un video desde un enlace", "nl": "Een video downloaden via een link"} + for lang, dl := range want { + private := menuFor(t, calls, "all_private_chats", lang, 0) + groups := menuFor(t, calls, "all_group_chats", lang, 0) + admins := menuFor(t, calls, "all_chat_administrators", lang, 0) + if describe(private, "dl") != dl || describe(groups, "dl") != dl { + t.Errorf("%q: /dl is described as %q", lang, describe(private, "dl")) + } + // Admin commands are only offered to admins, money commands only in private. + if describe(groups, "settings") != "" || describe(admins, "settings") == "" || describe(groups, "buy") != "" || describe(private, "buy") == "" { + t.Errorf("%q: commands are in the wrong scopes", lang) + } + // The app is not set up here, so it is not offered. + if describe(private, "app") != "" { + t.Errorf("%q: /app is listed without a Mini App", lang) + } + for _, menu := range [][]menuEntry{private, groups, admins} { + if len(menu) > 100 { + t.Errorf("%q: %d commands, Telegram allows 100", lang, len(menu)) + } + for _, e := range menu { + if n := utf8.RuneCountInString(e.Description); n < 1 || n > 256 || strings.HasPrefix(e.Description, "menu.") { + t.Errorf("%q: bad entry %+v", lang, e) + } + } + } + } + // The pseudo-locale is never published: Telegram wants two letters. + for _, c := range calls { + if l := c.Params["language_code"]; l != "" && len(l) != 2 { + t.Errorf("menu published for language code %q", l) + } + } + + profile := map[string]map[string]string{} + for _, method := range []string{"setMyName", "setMyDescription", "setMyShortDescription"} { + for _, c := range h.srv.Calls(method) { + lang := c.Params["language_code"] + if profile[lang] == nil { + profile[lang] = map[string]string{} + } + for _, k := range []string{"name", "description", "short_description"} { + if v := c.Params[k]; v != "" { + profile[lang][k] = v + } + } + } + } + if len(profile) != 3 || !strings.Contains(profile["es"]["description"], "Envíame") || + !strings.Contains(profile["nl"]["short_description"], "Stuur een link") || profile[""]["name"] != "Noderunners Download Bot" { + t.Fatalf("profile texts = %+v", profile) + } + + // Those calls are rate limited by Telegram, so a restart with the same + // texts does not repeat them. + h.stop() + before := len(h.srv.Calls("setMyName")) + h.boot() + if n := len(h.srv.Calls("setMyName")); n != before { + t.Fatalf("setMyName was called %d more times after a restart", n-before) + } +} + +func TestProfileIsLeftAloneWhenTurnedOff(t *testing.T) { + h := start(t, nil, func(c *config.Config) { c.Telegram.SetProfile = false }) + for _, m := range []string{"setMyName", "setMyDescription", "setMyShortDescription"} { + if n := len(h.srv.Calls(m)); n != 0 { + t.Errorf("%s was called %d times with TELEGRAM_SET_PROFILE=false", m, n) + } + } + if len(h.srv.Calls("setMyCommands")) == 0 { + t.Fatal("the menus must still be published") + } +} + +// --- acceptance: switching language changes everything ---------------------- + +func TestTelegramLanguageIsFollowed(t *testing.T) { + h := start(t, &ytdlptest.Fake{FileSize: 2000}, nil) + seq := h.srv.Seq() + // Paraguayan Spanish falls back to Spanish. + h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("es-PY")) + h.wait(seq, "sendMessage", textHas("te damos la bienvenida")) + + card := h.card(bob, bob, link, fakeserver.Lang("nl")) + if labels := card.Buttons(); labels[0].Text != "Beste · 10,0 MB" || labels[len(labels)-1].Text != "Annuleren" { + t.Fatalf("Dutch card buttons = %+v", labels) + } + // A language without a catalog gets English. + seq = h.srv.Seq() + h.srv.PushMessage(44, 44, "/start", fakeserver.Lang("ja")) + h.wait(seq, "sendMessage", textHas("welcome")) +} + +func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) { + h := startApp(t, &ytdlptest.Fake{FileSize: 2000}, nil) + appKey := func() string { + msgs, _ := h.must(alice, "GET", "i18n", nil).Body["messages"].(map[string]any) + s, _ := msgs["app.tab.home"].(string) + return s + } + if got := appKey(); got != "Home" { + t.Fatalf("app text before = %q", got) + } + + // /language, then pick Spanish. + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/language") + pick := h.wait(seq, "sendMessage", textHas("Pick a language")) + var names []string + for _, b := range pick.Buttons() { + names = append(names, b.Text) + } + if strings.Join(names, "|") != "English|Español|Nederlands|Follow my Telegram language" { + t.Fatalf("language buttons = %v", names) + } + seq = h.press(alice, alice, pick, "lg:es") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { return c.Params["text"] == "Guardado." }) + h.wait(seq, "editMessageText", textHas("Idioma: Español")) + + // The menu of this chat follows, whatever language the app is in. + menuCall := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) + menu := menuOf(t, menuCall) + if describe(menu, "dl") != "Descargar un video desde un enlace" || describe(menu, "app") != "Abrir la app" || menuCall.Params["language_code"] != "" { + t.Fatalf("chat menu = %+v (%s)", menu, menuCall.Params["language_code"]) + } + + // Messages and buttons. + card := h.card(alice, alice, link) + labels := card.Buttons() + if labels[0].Text != "Mejor · 10,0 MB" || labels[len(labels)-1].Text != "Cancelar" { + t.Fatalf("Spanish card buttons = %+v", labels) + } + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", nil) + h.wait(seq, edits, textHas("Listo. Que lo disfrutes.")) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/account") + acct := h.wait(seq, "sendMessage", textHas("Tu cuenta")) + if !strings.Contains(acct.Text(), "Descargas: 1 de 5") { + t.Fatalf("account in Spanish = %q", acct.Text()) + } + + // The Mini App. + if got := appKey(); got != "Inicio" { + t.Fatalf("app text after = %q", got) + } + me := h.must(alice, "GET", "me", nil) + if me.str("lang") != "es" || me.str("lang_override") != "es" { + t.Fatalf("me = %s", me.Raw) + } + + // Switching in the app works the same way, and back to automatic + // removes the chat's own menu. + seq = h.srv.Seq() + h.must(alice, "PUT", "me", map[string]any{"lang": "nl"}) + menuCall = h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) + if describe(menuOf(t, menuCall), "dl") != "Een video downloaden via een link" { + t.Fatalf("chat menu after the app switch = %+v", menuOf(t, menuCall)) + } + if got := appKey(); got != "Start" { + t.Fatalf("app text in Dutch = %q", got) + } + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/language") + pick = h.wait(seq, "sendMessage", textHas("Kies een taal")) + seq = h.press(alice, alice, pick, "lg:auto") + h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: alice} }) + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/help") + h.wait(seq, "sendMessage", textHas("How to use me")) + if got := appKey(); got != "Home" { + t.Fatalf("app text after auto = %q", got) + } +} + +func TestGroupLanguageChangesTheGroup(t *testing.T) { + h := startApp(t, nil, nil) + h.meetGroup(alice, bob) + seq := h.srv.Seq() + h.srv.PushMessage(group, bob, "/grouplang nl") + h.wait(seq, "sendMessage", textHas("De bot spreekt nu Nederlands")) + members := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: group} }) + admins := h.wait(seq, "setMyCommands", func(c fakeserver.Call) bool { + return scopeOf(c) == scope{Type: "chat_administrators", ChatID: group} + }) + if describe(menuOf(t, members), "dl") != "Een video downloaden via een link" || describe(menuOf(t, members), "settings") != "" || + describe(menuOf(t, admins), "settings") != "Groepsinstellingen" { + t.Fatalf("group menus = %+v / %+v", menuOf(t, members), menuOf(t, admins)) + } + // Everybody gets Dutch in the group, whatever their own language. + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl", fakeserver.Lang("es")) + h.wait(seq, "sendMessage", textHas("Zet een link achter het commando")) + + // The Mini App's group settings switch it back. + seq = h.srv.Seq() + st := h.must(bob, "GET", "groups/-1001234567890", nil).Body["settings"].(map[string]any) + st["lang"] = "" + h.must(bob, "PUT", "groups/-1001234567890/settings", st) + h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { return scopeOf(c) == scope{Type: "chat", ChatID: group} }) + h.wait(seq, "deleteMyCommands", func(c fakeserver.Call) bool { + return scopeOf(c) == scope{Type: "chat_administrators", ChatID: group} + }) +} + +// --- the pseudo-locale ------------------------------------------------------ + +func TestPseudoLocaleIsForOwners(t *testing.T) { + const owner = int64(7) + h := startApp(t, nil, func(c *config.Config) { + c.Pseudo = true + c.Owners = []int64{owner} + }) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/language") + pick := h.wait(seq, "sendMessage", textHas("Pick a language")) + if _, ok := pick.Button("lg:" + i18n.Pseudo); ok { + t.Fatal("a user is offered the pseudo-locale") + } + h.srv.PushCallback(alice, alice, pick.MessageID, "lg:"+i18n.Pseudo) + h.wait(seq, "answerCallbackQuery", textHas("")) + if r := h.call(alice, "PUT", "me", map[string]any{"lang": i18n.Pseudo}); r.Status != http.StatusBadRequest { + t.Fatalf("a user set the pseudo-locale in the app: %d", r.Status) + } + + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/language") + pick = h.wait(seq, "sendMessage", textHas("Pick a language")) + seq = h.press(owner, owner, pick, "lg:"+i18n.Pseudo) + h.wait(seq, "editMessageText", textHas("Ļáñĝûáĝé")) + seq = h.srv.Seq() + h.srv.PushMessage(owner, owner, "/help") + help := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == owner }) + if !strings.Contains(help.Text(), "/dl") || strings.Contains(help.Text(), "How to use me") || !strings.Contains(help.Text(), "[") { + t.Fatalf("help in the pseudo-locale = %q", help.Text()) + } + // Never published as a menu language. + for _, c := range h.srv.Calls("setMyCommands") { + if c.Params["language_code"] == i18n.Pseudo { + t.Fatal("the pseudo-locale was published to Telegram") + } + } +} diff --git a/internal/app/money_test.go b/internal/app/money_test.go index 709d029..6838b8f 100644 --- a/internal/app/money_test.go +++ b/internal/app/money_test.go @@ -735,7 +735,11 @@ func (h *moneyHarness) queued() fakeserver.Call { h.waitJobs(db.JobRunning, 1) second := h.card(bob, bob, "https://example.com/waiting") seq := h.press(bob, bob, second, "dl:") - return h.wait(seq, edits, textHas("In the queue")) + // Only bob's status: a late status edit of alice's job, from before it + // started, can also read "In the queue". + return h.wait(seq, edits, func(c fakeserver.Call) bool { + return c.ChatID() == bob && strings.Contains(c.Text(), "In the queue") + }) } func TestSkipTheQueueWithCredits(t *testing.T) { diff --git a/internal/bot/groups.go b/internal/bot/groups.go index fea3114..67099a4 100644 --- a/internal/bot/groups.go +++ b/internal/bot/groups.go @@ -263,22 +263,25 @@ func (b *Bot) cmdGroupLang(ctx context.Context, m *telego.Message, act actor) { return } arg := strings.ToLower(strings.TrimSpace(commandArgs(m))) + usage := i18n.Args{"Langs": strings.Join(b.visibleLangs(act.user.ID), ", ")} + changed, newLang := false, "" b.changeSettings(ctx, m, act, func(st *db.GroupSettings) (string, i18n.Args) { if arg == "" { - return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")} + return "!grouplang.usage", usage } if arg == "auto" { - st.Lang = "" + st.Lang, changed = "", true return "grouplang.auto", nil } - for _, l := range b.tr.Langs() { - if l == arg { - st.Lang = l - return "grouplang.set", i18n.Args{"Lang": b.tr.T(l, "language.name", nil)} - } + if l := b.findLang(arg, act.user.ID); l != "" { + st.Lang, changed, newLang = l, true, l + return "grouplang.set", i18n.Args{"Lang": b.tr.T(l, "language.name", nil)} } - return "!grouplang.usage", i18n.Args{"Langs": strings.Join(b.tr.Langs(), ", ")} + return "!grouplang.usage", usage }) + if changed { + b.SyncGroupMenu(ctx, m.Chat.ID, newLang) + } } func (b *Bot) cmdAutoDetect(ctx context.Context, m *telego.Message, act actor) { @@ -566,10 +569,7 @@ func (b *Bot) cbSetQuality(ctx context.Context, q *telego.CallbackQuery, act act func (b *Bot) cmdLanguage(ctx context.Context, m *telego.Message, act actor) { var row []telego.InlineKeyboardButton var rows [][]telego.InlineKeyboardButton - for _, l := range b.tr.Langs() { - if b.tr.Hidden(l) { - continue - } + for _, l := range b.visibleLangs(act.user.ID) { // Each language is listed under its own name. row = append(row, button(b.tr.T(l, "language.name", nil), cbData(cbLanguage, l))) if len(row) == 3 { @@ -584,12 +584,7 @@ func (b *Bot) cmdLanguage(ctx context.Context, m *telego.Message, act actor) { func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act actor, value string) { lang := "" if value != "auto" { - for _, l := range b.tr.Langs() { - if l == value { - lang = l - } - } - if lang == "" { + if lang = b.findLang(value, act.user.ID); lang == "" { b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) return } @@ -602,6 +597,7 @@ func (b *Bot) cbSetLanguage(ctx context.Context, q *telego.CallbackQuery, act ac if shown == "" { shown = b.tr.Resolve(act.user.Lang) } + b.SyncUserMenu(ctx, act.user.ID, lang) b.answer(ctx, q, b.tr.T(shown, "notice.saved", nil), false) if q.Message != nil { _ = b.edit(ctx, q.Message.GetChat().ID, int64(q.Message.GetMessageID()), false, diff --git a/internal/bot/menu.go b/internal/bot/menu.go index 7142914..4d4f113 100644 --- a/internal/bot/menu.go +++ b/internal/bot/menu.go @@ -2,31 +2,187 @@ package bot import ( "context" + "crypto/sha256" + "encoding/hex" + "strings" + "time" "github.com/mymmrac/telego" ) -// menuCommands are the commands shown in Telegram's command menu, in -// order. Names are lowercase ASCII in every language; only descriptions -// are translated, under "menu.". -var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "history", "account", "buy", "help"} +// The command menus. Names are lowercase ASCII in every language; only the +// descriptions are translated, under "menu.". Each list is published +// for every language, in three scopes: private chats, group members and +// group admins. Owner commands are never listed. +var ( + privateMenu = []string{ + "dl", "audio", "thumb", "subs", "info", "queue", "cancel", "history", + "account", "buy", "credits", "limits", "redeem", "referral", "donate", + "quality", "language", "app", "support", "privacy", "terms", "help", + } + groupMenu = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "groupwallet", "grouppass", "app", "help"} + adminMenu = append(append([]string{}, groupMenu...), + "settings", "grouplang", "autodetect", "allow", "block", "spending", "groupstats") +) -// RegisterCommands publishes the command menu. A failure is logged and -// otherwise ignored: the bot works without a menu. +func (b *Bot) menu(lang string, names []string) []telego.BotCommand { + cmds := make([]telego.BotCommand, 0, len(names)) + for _, name := range names { + if name == "app" && !b.cfg.MiniAppEnabled() { + continue + } + cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, "menu."+name, nil)}) + } + return cmds +} + +// menuLangs are the languages menus and profile texts are published for. +// Telegram takes a two-letter code only, so a regional catalog (es-PY) +// shares its base language's slot, and the pseudo-locale is left out. +func (b *Bot) menuLangs() []string { + var out []string + seen := map[string]bool{} + for _, l := range b.tr.Langs() { + if b.tr.Hidden(l) || len(l) != 2 || seen[l] { + continue + } + seen[l] = true + out = append(out, l) + } + return out +} + +// RegisterCommands publishes the command menus and the bot's profile texts +// in every language. The source language is also the default for clients +// in languages without a catalog. A failure is logged and otherwise +// ignored: the bot works without a menu. func (b *Bot) RegisterCommands(ctx context.Context) { - for _, lang := range b.tr.Langs() { - cmds := make([]telego.BotCommand, 0, len(menuCommands)) - for _, name := range menuCommands { - cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, "menu."+name, nil)}) + scopes := []struct { + scope telego.BotCommandScope + names []string + }{ + {&telego.BotCommandScopeAllPrivateChats{Type: telego.ScopeTypeAllPrivateChats}, privateMenu}, + {&telego.BotCommandScopeAllGroupChats{Type: telego.ScopeTypeAllGroupChats}, groupMenu}, + {&telego.BotCommandScopeAllChatAdministrators{Type: telego.ScopeTypeAllChatAdministrators}, adminMenu}, + } + for i, lang := range b.menuLangs() { + code := lang + if i == 0 { + code = "" // the default menu } - params := &telego.SetMyCommandsParams{Commands: cmds} - if lang != b.tr.Langs()[0] { - // The source language is the default menu; the others are - // registered for their own language code. - params.LanguageCode = lang + for _, s := range scopes { + err := b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{ + Commands: b.menu(lang, s.names), Scope: s.scope, LanguageCode: code, + }) + if err != nil { + b.log.Warn("setMyCommands failed", "lang", lang, "scope", s.scope.ScopeType(), "err", err) + } } - if err := b.api.SetMyCommands(ctx, params); err != nil { - b.log.Warn("setMyCommands failed", "lang", lang, "err", err) + if b.cfg.Telegram.SetProfile { + b.setProfile(ctx, lang, code) } } } + +// setProfile sets the bot's name and descriptions for one language. These +// calls are rate limited hard by Telegram, so they are made only when the +// catalog text changed since the last time they went through. +func (b *Bot) setProfile(ctx context.Context, lang, code string) { + name := b.tr.T(lang, "profile.name", nil) + about := b.tr.T(lang, "profile.about", nil) + short := b.tr.T(lang, "profile.short", nil) + sum := sha256.Sum256([]byte(name + "\x00" + about + "\x00" + short)) + hash := hex.EncodeToString(sum[:]) + key := "profile:" + lang + if old, _ := b.store.GetKV(ctx, key); old == hash { + return + } + steps := []func() error{ + func() error { return b.api.SetMyName(ctx, &telego.SetMyNameParams{Name: name, LanguageCode: code}) }, + func() error { + return b.api.SetMyDescription(ctx, &telego.SetMyDescriptionParams{Description: about, LanguageCode: code}) + }, + func() error { + return b.api.SetMyShortDescription(ctx, &telego.SetMyShortDescriptionParams{ShortDescription: short, LanguageCode: code}) + }, + } + for _, step := range steps { + if err := step(); err != nil { + // Not recorded, so the next start tries again. + b.log.Warn("setting the bot profile failed", "lang", lang, "err", err) + return + } + } + if err := b.store.SetKV(ctx, key, hash); err != nil { + b.log.Warn("remember bot profile", "lang", lang, "err", err) + } +} + +// SyncUserMenu makes the command menu of a private chat follow the user's +// language setting. Telegram picks a menu by the language of the app, so a +// user who chose another language in the bot gets a menu for that chat +// alone. An empty lang removes it, and the app's language applies again. +func (b *Bot) SyncUserMenu(ctx context.Context, userID int64, lang string) { + if !b.rate.allow("menu:"+itoa(userID), 6, time.Minute) { + return + } + scope := &telego.BotCommandScopeChat{Type: telego.ScopeTypeChat, ChatID: telego.ChatID{ID: userID}} + var err error + if lang == "" { + err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: scope}) + } else { + err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, privateMenu), Scope: scope}) + } + if err != nil { + b.log.Warn("set the menu of a chat", "chat_id", userID, "err", err) + } +} + +// SyncGroupMenu does the same for a group with its own language: one menu +// for its members and one for its admins. +func (b *Bot) SyncGroupMenu(ctx context.Context, chatID int64, lang string) { + if !b.rate.allow("menu:"+itoa(chatID), 6, time.Minute) { + return + } + id := telego.ChatID{ID: chatID} + scopes := []struct { + scope telego.BotCommandScope + names []string + }{ + {&telego.BotCommandScopeChat{Type: telego.ScopeTypeChat, ChatID: id}, groupMenu}, + {&telego.BotCommandScopeChatAdministrators{Type: telego.ScopeTypeChatAdministrators, ChatID: id}, adminMenu}, + } + for _, s := range scopes { + var err error + if lang == "" { + err = b.api.DeleteMyCommands(ctx, &telego.DeleteMyCommandsParams{Scope: s.scope}) + } else { + err = b.api.SetMyCommands(ctx, &telego.SetMyCommandsParams{Commands: b.menu(lang, s.names), Scope: s.scope}) + } + if err != nil { + b.log.Warn("set the menu of a group", "chat_id", chatID, "err", err) + } + } +} + +// visibleLangs lists the languages a user may pick. The pseudo-locale is +// for owners only. +func (b *Bot) visibleLangs(userID int64) []string { + var out []string + for _, l := range b.tr.Langs() { + if !b.tr.Hidden(l) || b.cfg.IsOwner(userID) { + out = append(out, l) + } + } + return out +} + +// findLang matches a language code typed by a user against the catalogs. +func (b *Bot) findLang(code string, userID int64) string { + for _, l := range b.visibleLangs(userID) { + if strings.EqualFold(l, code) { + return l + } + } + return "" +} diff --git a/internal/config/config.go b/internal/config/config.go index 44b07f5..085158c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -83,6 +83,9 @@ type Config struct { // directory instead of the ones built into the binary, and makes // "/reload i18n" pick up edits without a restart. LocalesDir string `toml:"locales_dir" env:"LOCALES_DIR"` + // Pseudo adds the pseudo-locale en-XA, for checking that every text + // comes from the catalog. Owners can pick it with /language. + Pseudo bool `toml:"i18n_pseudo" env:"I18N_PSEUDO"` // PublicURL is the HTTPS base URL this server is reachable at from the // internet, without a trailing slash. It is used for payment webhooks, @@ -108,6 +111,10 @@ type Telegram struct { MaxUploadMB int64 `toml:"max_upload_mb" env:"TELEGRAM_MAX_UPLOAD_MB"` // UpdateWorkers is the number of goroutines that handle updates. UpdateWorkers int `toml:"update_workers" env:"TELEGRAM_UPDATE_WORKERS"` + // SetProfile lets the bot set its name, description and short + // description in every language from the catalogs (profile.*). Turn it + // off to keep what was set in @BotFather. + SetProfile bool `toml:"set_profile" env:"TELEGRAM_SET_PROFILE"` } // HTTP holds the settings of the embedded HTTP server. @@ -291,6 +298,7 @@ func Default() Config { Mode: "polling", MaxUploadMB: 50, UpdateWorkers: 8, + SetProfile: true, }, ProbeMode: "auto", HTTP: HTTP{Listen: ":8080"}, diff --git a/internal/i18n/format.go b/internal/i18n/format.go index 14acfe4..56e4d5e 100644 --- a/internal/i18n/format.go +++ b/internal/i18n/format.go @@ -2,6 +2,8 @@ package i18n import ( "fmt" + "strconv" + "strings" "time" ) @@ -77,8 +79,26 @@ func (b *Bundle) Sats(lang string, n int64) string { return b.T(lang, "unit.sats", Args{"Count": n, "N": b.Number(lang, n)}) } -// DateTime formats a point in time. The numeric form reads the same in -// every language and always states the time zone. -func (b *Bundle) DateTime(_ string, t time.Time) string { - return t.UTC().Format("2006-01-02 15:04") + " UTC" +// DateTime formats a point in time the way the language writes dates, +// from format.datetime and format.months in its catalog. It is always in +// UTC and says so: the bot does not know the reader's time zone. +func (b *Bundle) DateTime(lang string, t time.Time) string { + return b.T(lang, "format.datetime", b.dateArgs(lang, t)) +} + +// Date formats a day, from format.date and format.months. +func (b *Bundle) Date(lang string, t time.Time) string { + return b.T(lang, "format.date", b.dateArgs(lang, t)) +} + +func (b *Bundle) dateArgs(lang string, t time.Time) Args { + t = t.UTC() + month := strconv.Itoa(int(t.Month())) + if names := strings.Split(b.T(lang, "format.months", nil), ","); len(names) == 12 { + month = strings.TrimSpace(names[t.Month()-1]) + } + return Args{ + "Day": t.Day(), "Month": month, "MonthNumber": fmt.Sprintf("%02d", int(t.Month())), "Year": t.Year(), + "Hour": fmt.Sprintf("%02d", t.Hour()), "Minute": fmt.Sprintf("%02d", t.Minute()), + } } diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index f094f0c..7ee22c1 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -3,6 +3,7 @@ package i18n import ( + "bytes" "fmt" "html" "io/fs" @@ -34,6 +35,7 @@ type Bundle struct { names []string matcher language.Matcher log *slog.Logger + opts []Option // raw keeps each catalog as parsed TOML, for exporting the Mini App's // messages to the browser. raw map[string]map[string]any @@ -43,13 +45,27 @@ type Bundle struct { printers map[string]*message.Printer } +// Option changes how catalogs are loaded. +type Option func(*options) + +type options struct{ pseudo bool } + +// WithPseudo adds the pseudo-locale (Pseudo), made from the English +// catalog, for testing translations. +func WithPseudo() Option { return func(o *options) { o.pseudo = true } } + // Load reads every *.toml catalog in fsys. The file name is the language // tag, for example en.toml or es.toml. -func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { +func Load(fsys fs.FS, log *slog.Logger, opts ...Option) (*Bundle, error) { if log == nil { log = slog.Default() } + var o options + for _, opt := range opts { + opt(&o) + } b := &Bundle{ + opts: opts, bundle: goi18n.NewBundle(language.English), log: log, localizers: map[string]*goi18n.Localizer{}, @@ -83,6 +99,17 @@ func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { if !hasDefault { return nil, fmt.Errorf("i18n: the %s catalog is missing", Default) } + if o.pseudo { + doc := pseudoDoc(b.raw[Default], "") + var buf bytes.Buffer + if err := toml.NewEncoder(&buf).Encode(doc); err != nil { + return nil, fmt.Errorf("i18n: pseudo-locale: %w", err) + } + if _, err := b.bundle.ParseMessageFileBytes(buf.Bytes(), Pseudo+".toml"); err != nil { + return nil, fmt.Errorf("i18n: pseudo-locale: %w", err) + } + b.raw[Pseudo] = doc + } // English first, so it is the matcher's default. b.tags = []language.Tag{language.English} for _, t := range b.bundle.LanguageTags() { @@ -109,7 +136,7 @@ func (b *Bundle) Hidden(lang string) bool { return strings.EqualFold(lang, Pseud // Reload replaces the catalogs with the ones in fsys. When they do not // load, the old ones stay in use and the error says why. func (b *Bundle) Reload(fsys fs.FS) error { - fresh, err := Load(fsys, b.log) + fresh, err := Load(fsys, b.log, b.opts...) if err != nil { return err } diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index a41b2a7..0f70a8a 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -200,3 +200,96 @@ func TestDir(t *testing.T) { } } } + +func TestPseudoLocale(t *testing.T) { + b, err := i18n.Load(locales.FS, nil, i18n.WithPseudo()) + if err != nil { + t.Fatal(err) + } + if !b.Hidden(i18n.Pseudo) { + t.Fatal("the pseudo-locale must be hidden from users") + } + found := false + for _, l := range b.Langs() { + found = found || l == i18n.Pseudo + } + if !found { + t.Fatalf("languages = %v, want %s among them", b.Langs(), i18n.Pseudo) + } + got := b.HTML(i18n.Pseudo, "start.private", i18n.Args{"Name": "Ana"}) + if !strings.Contains(got, "") || !strings.Contains(got, "Ana") || !strings.Contains(got, "/help") || + strings.Contains(got, "welcome") || !strings.Contains(got, "[") { + t.Fatalf("pseudo start = %q", got) + } + // Plurals keep working. + if one, many := b.T(i18n.Pseudo, "unit.sats", i18n.Args{"Count": 1, "N": "1"}), b.T(i18n.Pseudo, "unit.sats", i18n.Args{"Count": 5, "N": "5"}); one == many || !strings.Contains(many, "5") { + t.Fatalf("pseudo plurals = %q, %q", one, many) + } + if d := b.DateTime(i18n.Pseudo, time.Date(2026, 3, 4, 5, 6, 0, 0, time.UTC)); !strings.Contains(d, "Ṁáŕ") || !strings.Contains(d, "05:06") { + t.Fatalf("pseudo date = %q", d) + } + // The Mini App gets it too. + if s, _ := b.Section(i18n.Pseudo, "app")["tab.home"].(string); !strings.HasPrefix(s, "[Ĥöḿé") { + t.Fatalf("pseudo app text = %q", s) + } + // Without the option it does not exist. + plain := load(t) + for _, l := range plain.Langs() { + if l == i18n.Pseudo { + t.Fatal("the pseudo-locale is loaded without being asked for") + } + } +} + +func TestPseudolocalizeKeepsMarkup(t *testing.T) { + for in, want := range map[string]string{ + "Hi {{.Name}}": "[Ĥî {{.Name}} ~]", + "Paid & done": "[Þáîð & ðöñé ~~~]", + "Try /help or https://x.y/a?b=c": "[Ţŕý /help öŕ https://x.y/a?b=c ~~]", + "\nTwo\nlines\n": "\n[Ţŵö\nļîñéš ~~~]\n", + } { + if got := i18n.Pseudolocalize(in); got != want { + t.Errorf("Pseudolocalize(%q) = %q, want %q", in, got, want) + } + } +} + +func TestDatesFollowTheCatalog(t *testing.T) { + b := load(t) + at := time.Date(2026, 11, 18, 9, 5, 0, 0, time.FixedZone("PYT", -3*3600)) + if got := b.DateTime("en", at); got != "18 Nov 2026, 12:05 UTC" { + t.Errorf("en = %q", got) + } + if got := b.Date("en", at); got != "18 Nov 2026" { + t.Errorf("en date = %q", got) + } + for lang, want := range map[string]string{"es": "18 nov 2026, 12:05 UTC", "es-PY": "18 nov 2026, 12:05 UTC", "nl": "18 nov 2026, 12:05 UTC"} { + if got := b.DateTime(lang, at); got != want { + t.Errorf("%s = %q, want %q", lang, got, want) + } + } + if got := b.DateTime("nl", time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)); got != "1 mrt 2026, 00:00 UTC" { + t.Errorf("nl March = %q", got) + } +} + +func TestNumbersAndUnitsPerLanguage(t *testing.T) { + b := load(t) + cases := []struct{ lang, got, want string }{ + {"en", b.Sats("en", 10000), "10,000 sats"}, + {"es", b.Sats("es", 10000), "10.000 sats"}, + {"nl", b.Sats("nl", 10000), "10.000 sats"}, + {"es", b.Sats("es", 1), "1 sat"}, + {"es", b.Size("es", 5<<20), "5,0 MB"}, + {"nl", b.Size("nl", 3<<29), "1,50 GB"}, + {"es", b.Span("es", 5*time.Minute), "5 minutos"}, + {"nl", b.Span("nl", time.Minute), "1 minuut"}, + {"nl", b.Span("nl", 3*time.Hour), "3 uur"}, + {"es-PY", b.T("es-PY", "status.done", nil), "Listo. Que lo disfrutes."}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("%s: %q, want %q", c.lang, c.got, c.want) + } + } +} diff --git a/internal/i18n/pseudo.go b/internal/i18n/pseudo.go new file mode 100644 index 0000000..1f57a28 --- /dev/null +++ b/internal/i18n/pseudo.go @@ -0,0 +1,87 @@ +package i18n + +import ( + "regexp" + "strings" +) + +// The pseudo-locale is made from the English catalog when the bundle is +// loaded with WithPseudo. Every letter gets an accent and every message is +// wrapped in brackets and made about a third longer. Switch to it and any +// text that still looks like plain English did not come from the catalog, +// any text cut off at the bracket is too long for its place, and broken +// accents point at an encoding problem. + +var accents = map[rune]rune{ + 'a': 'á', 'b': 'ƀ', 'c': 'ç', 'd': 'ð', 'e': 'é', 'f': 'ƒ', 'g': 'ĝ', 'h': 'ĥ', 'i': 'î', 'j': 'ĵ', + 'k': 'ķ', 'l': 'ļ', 'm': 'ḿ', 'n': 'ñ', 'o': 'ö', 'p': 'þ', 'q': 'ǫ', 'r': 'ŕ', 's': 'š', 't': 'ţ', + 'u': 'û', 'v': 'ṽ', 'w': 'ŵ', 'x': 'ẋ', 'y': 'ý', 'z': 'ž', + 'A': 'Å', 'B': 'Ɓ', 'C': 'Ç', 'D': 'Ð', 'E': 'É', 'F': 'Ƒ', 'G': 'Ĝ', 'H': 'Ĥ', 'I': 'Î', 'J': 'Ĵ', + 'K': 'Ķ', 'L': 'Ļ', 'M': 'Ṁ', 'N': 'Ñ', 'O': 'Ö', 'P': 'Þ', 'Q': 'Ǫ', 'R': 'Ŕ', 'S': 'Š', 'T': 'Ţ', + 'U': 'Û', 'V': 'Ṽ', 'W': 'Ŵ', 'X': 'Ẋ', 'Y': 'Ý', 'Z': 'Ž', +} + +// keep matches what must survive unchanged: placeholders, HTML tags and +// entities, bot commands, links, and the list separators of format.months. +var keep = regexp.MustCompile(`\{\{[^}]*\}\}|]*>|&[a-z]+;|/[a-z_]+|https?://\S+|@\w+|,`) + +// Pseudolocalize turns one English message into its pseudo-locale form. +func Pseudolocalize(s string) string { + var sb strings.Builder + letters := 0 + last := 0 + for _, loc := range keep.FindAllStringIndex(s, -1) { + letters += accentInto(&sb, s[last:loc[0]]) + sb.WriteString(s[loc[0]:loc[1]]) + last = loc[1] + } + letters += accentInto(&sb, s[last:]) + body := sb.String() + // Leading and trailing line breaks stay outside the brackets. + trimmed := strings.Trim(body, "\n") + lead := body[:strings.Index(body, trimmed)] + trail := body[len(lead)+len(trimmed):] + pad := strings.Repeat("~", (letters+2)/3) + return lead + "[" + trimmed + " " + pad + "]" + trail +} + +func accentInto(sb *strings.Builder, s string) int { + n := 0 + for _, r := range s { + if a, ok := accents[r]; ok { + sb.WriteRune(a) + n++ + } else { + sb.WriteRune(r) + } + } + return n +} + +// pseudoDoc applies Pseudolocalize to every text of a parsed catalog. +// format.months is a list, not a sentence: its names are accented without +// brackets so it still splits into twelve. +func pseudoDoc(in map[string]any, path string) map[string]any { + out := make(map[string]any, len(in)) + for k, v := range in { + key := k + if path != "" { + key = path + "." + k + } + switch x := v.(type) { + case string: + if key == "format.months" { + var sb strings.Builder + accentInto(&sb, x) + out[k] = sb.String() + } else { + out[k] = Pseudolocalize(x) + } + case map[string]any: + out[k] = pseudoDoc(x, key) + default: + out[k] = v + } + } + return out +} diff --git a/internal/tg/api.go b/internal/tg/api.go index b84f016..3e33e1c 100644 --- a/internal/tg/api.go +++ b/internal/tg/api.go @@ -28,6 +28,10 @@ type API interface { DeleteMessage(ctx context.Context, params *telego.DeleteMessageParams) error AnswerCallbackQuery(ctx context.Context, params *telego.AnswerCallbackQueryParams) error SetMyCommands(ctx context.Context, params *telego.SetMyCommandsParams) error + DeleteMyCommands(ctx context.Context, params *telego.DeleteMyCommandsParams) error + SetMyName(ctx context.Context, params *telego.SetMyNameParams) error + SetMyDescription(ctx context.Context, params *telego.SetMyDescriptionParams) error + SetMyShortDescription(ctx context.Context, params *telego.SetMyShortDescriptionParams) error GetChatMember(ctx context.Context, params *telego.GetChatMemberParams) (telego.ChatMember, error) } diff --git a/locales/catalog_test.go b/locales/catalog_test.go new file mode 100644 index 0000000..ea2a773 --- /dev/null +++ b/locales/catalog_test.go @@ -0,0 +1,447 @@ +package locales_test + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" + "unicode/utf8" + + "github.com/BurntSushi/toml" + + "github.com/noderunners/dlbot/locales" +) + +// These tests are the translation checks CI runs. They fail when a catalog +// is missing a message, has one the source does not have, changed a +// placeholder or a tag, or when the code and the source catalog disagree +// about which messages exist. + +const source = "en" + +// required are the languages that must ship complete. +var required = []string{"en", "es", "nl"} + +var pluralForms = map[string]bool{"zero": true, "one": true, "two": true, "few": true, "many": true, "other": true} + +// catalog is a flattened catalog: message ID to its forms. A plain +// message has the single form "". +type catalog map[string]map[string]string + +func flatten(prefix string, in map[string]any, out catalog) { + for k, v := range in { + key := k + if prefix != "" { + key = prefix + "." + k + } + switch x := v.(type) { + case string: + out[key] = map[string]string{"": x} + case map[string]any: + plural := len(x) > 0 + for form, text := range x { + if _, ok := text.(string); !ok || !pluralForms[form] { + plural = false + } + } + if !plural { + flatten(key, x, out) + continue + } + forms := map[string]string{} + for form, text := range x { + forms[form] = text.(string) + } + out[key] = forms + } + } +} + +func loadCatalogs(t *testing.T) map[string]catalog { + t.Helper() + files, err := fs.Glob(locales.FS, "*.toml") + if err != nil { + t.Fatal(err) + } + out := map[string]catalog{} + for _, name := range files { + data, err := fs.ReadFile(locales.FS, name) + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := toml.Unmarshal(data, &doc); err != nil { + t.Fatalf("%s: %v", name, err) + } + c := catalog{} + flatten("", doc, c) + out[strings.TrimSuffix(name, ".toml")] = c + } + return out +} + +func keys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +var ( + placeholder = regexp.MustCompile(`\{\{\s*\.(\w+)\s*\}\}`) + anyBraces = regexp.MustCompile(`\{\{[^}]*\}\}`) + htmlTag = regexp.MustCompile(`]*>`) + codeBlock = regexp.MustCompile(`(?s).*?`) +) + +// marks returns the sorted placeholders and tags of all forms of a +// message. Placeholders are compared as a set, because a plural form may +// leave the number out ("last day"). Tags are compared one by one. +func marks(forms map[string]string) (holders, tags string) { + set := map[string]bool{} + var tagList []string + for _, form := range keys(forms) { + for _, m := range placeholder.FindAllStringSubmatch(forms[form], -1) { + set[m[1]] = true + } + if form == "" || form == "other" { + tagList = htmlTag.FindAllString(forms[form], -1) + } + } + sort.Strings(tagList) + return strings.Join(keys(set), ","), strings.Join(tagList, "") +} + +func TestRequiredCatalogsExist(t *testing.T) { + all := loadCatalogs(t) + for _, lang := range required { + if all[lang] == nil { + t.Errorf("locales/%s.toml is missing", lang) + } + } +} + +func TestCatalogsMatchTheSource(t *testing.T) { + all := loadCatalogs(t) + src := all[source] + if len(src) < 300 { + t.Fatalf("the source catalog has only %d messages; the loader is broken", len(src)) + } + for _, lang := range keys(all) { + if lang == source { + continue + } + cat := all[lang] + t.Run(lang, func(t *testing.T) { + for _, id := range keys(src) { + forms, ok := cat[id] + if !ok { + t.Errorf("missing: %s", id) + continue + } + srcPlural, plural := src[id][""] == "" && len(src[id]) > 0 && src[id]["other"] != "", forms["other"] != "" + if srcPlural != plural { + t.Errorf("%s: plural in one catalog and plain in the other", id) + continue + } + if plural && forms["one"] == "" { + t.Errorf("%s: plural message without the form \"one\"", id) + } + for form, text := range forms { + if strings.TrimSpace(text) == "" { + t.Errorf("%s %s: empty text", id, form) + } + // Anything in braces must be a well formed placeholder. + for _, b := range anyBraces.FindAllString(text, -1) { + if !placeholder.MatchString(b) { + t.Errorf("%s: broken placeholder %s", id, b) + } + } + if strings.Count(text, "{{") != len(placeholder.FindAllString(text, -1)) || strings.Count(text, "{{") != strings.Count(text, "}}") { + t.Errorf("%s: unbalanced braces in %q", id, text) + } + } + wantHolders, wantTags := marks(src[id]) + gotHolders, gotTags := marks(forms) + if gotHolders != wantHolders { + t.Errorf("%s: placeholders are {%s}, the source has {%s}", id, gotHolders, wantHolders) + } + if gotTags != wantTags { + t.Errorf("%s: tags are %s, the source has %s", id, gotTags, wantTags) + } + // Commands are the same in every language. + if cmds, want := commandsIn(forms), commandsIn(src[id]); cmds != want { + t.Errorf("%s: commands are [%s], the source has [%s]", id, cmds, want) + } + } + for _, id := range keys(cat) { + if _, ok := src[id]; !ok { + t.Errorf("not in the source catalog: %s", id) + } + } + }) + } +} + +var slashCommand = regexp.MustCompile(`(?:^|[\s(>])(/[a-z_]+)\b`) + +func commandsIn(forms map[string]string) string { + set := map[string]bool{} + for _, text := range forms { + for _, m := range slashCommand.FindAllStringSubmatch(text, -1) { + set[m[1]] = true + } + } + return strings.Join(keys(set), " ") +} + +// TestCatalogRules checks what holds for every catalog, the source +// included: Telegram's length limits and the project's writing rules. +func TestCatalogRules(t *testing.T) { + all := loadCatalogs(t) + names := map[string]string{} + for _, lang := range keys(all) { + cat := all[lang] + text := func(id string) string { return cat[id][""] } + limit := func(id string, min, max int) { + if n := utf8.RuneCountInString(text(id)); n < min || n > max { + t.Errorf("%s: %s is %d characters, Telegram allows %d to %d", lang, id, n, min, max) + } + } + for id, forms := range cat { + for _, s := range forms { + if strings.Contains(s, "\u2014") { + t.Errorf("%s: %s contains an em dash", lang, id) + } + // Spanish is written without the opening marks here. + if strings.HasPrefix(lang, "es") && strings.ContainsAny(s, "¿¡") { + t.Errorf("%s: %s has an inverted question or exclamation mark", lang, id) + } + if s != strings.TrimSpace(s) && !strings.HasPrefix(s, "\n") { + t.Errorf("%s: %s has stray space around it", lang, id) + } + } + switch { + case strings.HasPrefix(id, "menu."): + limit(id, 1, 256) + if strings.ContainsAny(text(id), "<>\n") { + t.Errorf("%s: %s must be one line of plain text", lang, id) + } + case strings.HasPrefix(id, "btn.") || strings.HasPrefix(id, "product."): + // Button labels share a row; long ones get cut off. + if n := utf8.RuneCountInString(text(id)); n > 40 { + t.Errorf("%s: %s is %d characters, too long for a button", lang, id, n) + } + } + } + limit("profile.name", 1, 64) + limit("profile.about", 1, 512) + limit("profile.short", 1, 120) + if n := len(strings.Split(text("format.months"), ",")); n != 12 { + t.Errorf("%s: format.months has %d entries, want 12", lang, n) + } + name := text("language.name") + if other, dup := names[name]; dup || name == "" { + t.Errorf("%s: language.name %q is empty or the same as in %s", lang, name, other) + } + names[name] = lang + } +} + +// sameEverywhere are messages that are meant to read the same in every +// language, such as the brand name in the invoice memo. +var sameEverywhere = map[string]bool{"invoice.memo": true} + +// TestCatalogsAreTranslated catches a catalog that is a copy of the +// source with a few lines changed. Short labels are often the same in two +// languages, so only longer texts count. +func TestCatalogsAreTranslated(t *testing.T) { + all := loadCatalogs(t) + src := all[source] + for _, lang := range keys(all) { + if lang == source { + continue + } + var same []string + long := 0 + for id, forms := range all[lang] { + text := forms[""] + forms["other"] + // Code samples, placeholders and markup are the same in every + // language; only the words around them count. + words := codeBlock.ReplaceAllString(text, " ") + words = placeholder.ReplaceAllString(words, " ") + words = htmlTag.ReplaceAllString(words, " ") + if len(strings.Fields(words)) < 4 { + continue + } + long++ + if text == src[id][""]+src[id]["other"] && !sameEverywhere[id] { + same = append(same, id) + } + } + sort.Strings(same) + if len(same) > 0 { + t.Errorf("%s: %d of %d longer messages are identical to the source: %s", lang, len(same), long, strings.Join(same, ", ")) + } + } +} + +// --- code and catalog agree ------------------------------------------------ + +func repoRoot(t *testing.T) string { + t.Helper() + dir, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("go.mod not found") + } + dir = parent + } +} + +var stringLiteral = regexp.MustCompile("\"((?:[^\"\\\\\n]|\\\\.)*)\"") + +// literals collects every string literal of the code that could name a +// message: Go under cmd and internal (tests excluded), and the Mini App. +func literals(t *testing.T) map[string][]string { + t.Helper() + root := repoRoot(t) + out := map[string][]string{} + for _, dir := range []string{"cmd", "internal", "web/miniapp/src"} { + err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + ext := filepath.Ext(path) + if (ext != ".go" && ext != ".ts" && ext != ".tsx") || strings.HasSuffix(path, "_test.go") { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + for _, m := range stringLiteral.FindAllStringSubmatch(string(data), -1) { + // The group commands mark a refusal with a leading "!". + lit := strings.TrimPrefix(m[1], "!") + out[lit] = append(out[lit], rel) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + } + return out +} + +var keyShape = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z0-9_]+)+$`) + +var suffixShape = regexp.MustCompile(`^\.[a-z0-9_]+$`) + +// isPrefix reports whether a literal is the start of message IDs built at +// run time: "error." + code, "settings.who_" + value. +func isPrefix(lit string) bool { + return (strings.HasSuffix(lit, ".") || strings.HasSuffix(lit, "_")) && keyShape.MatchString(lit+"x") +} + +// TestEveryMessageIsUsed fails for a message no code asks for. A message +// counts as used when its ID is written out in the code, or when the code +// builds IDs it would match: from a prefix ("error." + code) or from a +// suffix (name + ".list"). +func TestEveryMessageIsUsed(t *testing.T) { + src := loadCatalogs(t)[source] + lits := literals(t) + var prefixes, suffixes []string + for lit := range lits { + if isPrefix(lit) { + prefixes = append(prefixes, lit) + } + if suffixShape.MatchString(lit) { + suffixes = append(suffixes, lit) + } + } + for _, id := range keys(src) { + if _, ok := lits[id]; ok { + continue + } + used := false + for _, p := range prefixes { + used = used || strings.HasPrefix(id, p) + } + for _, sfx := range suffixes { + used = used || strings.HasSuffix(id, sfx) + } + if !used { + t.Errorf("unused message: %s", id) + } + } +} + +// TestEveryUsedMessageExists fails for a message ID written in the code +// that the source catalog does not have. +func TestEveryUsedMessageExists(t *testing.T) { + src := loadCatalogs(t)[source] + tables := map[string]bool{} + for id := range src { + tables[strings.SplitN(id, ".", 2)[0]] = true + } + for lit, files := range literals(t) { + if !keyShape.MatchString(lit) || !tables[strings.SplitN(lit, ".", 2)[0]] { + continue + } + if _, ok := src[lit]; ok { + continue + } + // A literal may also be the start of longer IDs, or something + // that only looks like an ID (a file name). + starts := false + for id := range src { + if strings.HasPrefix(id, lit+".") || strings.HasPrefix(id, lit+"_") || (isPrefix(lit) && strings.HasPrefix(id, lit)) { + starts = true + break + } + } + if !starts && !notMessages[lit] { + t.Errorf("%s is used in %s but is not in the source catalog", lit, strings.Join(uniq(files), ", ")) + } + } +} + +// notMessages are string literals that have the shape of a message ID and +// start with the name of a catalog table, but are something else. +var notMessages = map[string]bool{ + "invoice.png": true, // the file name of the QR code picture +} + +func uniq(in []string) []string { + seen := map[string]bool{} + var out []string + for _, s := range in { + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + return out +} + +func Example_flatten() { + c := catalog{} + flatten("", map[string]any{"unit": map[string]any{"sats": map[string]any{"one": "{{.N}} sat", "other": "{{.N}} sats"}}, "a": map[string]any{"b": "x"}}, c) + fmt.Println(len(c), c["a.b"][""], c["unit.sats"]["one"]) + // Output: 2 x {{.N}} sat +} diff --git a/locales/en.toml b/locales/en.toml index 808b6a3..d5ee2b4 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -71,6 +71,44 @@ history = "Your past downloads" account = "Your pass, balance and usage" buy = "Get a pass or credits" help = "How to use the bot" +subs = "Get the subtitles of a video" +credits = "Buy credits" +limits = "Your limits" +redeem = "Redeem a gift code" +referral = "Invite friends and earn sats" +donate = "Tip the bot" +quality = "Set your default format" +language = "Change the language" +app = "Open the app" +support = "Get help" +privacy = "What is stored about you" +terms = "Terms of use" +settings = "Group settings" +grouplang = "Language of the bot in this group" +autodetect = "Fetch pasted links without a command" +allow = "Only allow some sites" +block = "Block a site" +spending = "Who may spend group credits" +groupwallet = "Group balance and top up" +grouppass = "Buy a pass for the group" +groupstats = "Downloads by member" + +# The bot's name and the texts on its profile, set with setMyName, +# setMyDescription and setMyShortDescription. Plain text. Telegram allows +# 64 characters for the name, 512 for the description (shown in an empty +# chat, before the user presses Start) and 120 for the short one (shown on +# the profile and when the bot is shared). +[profile] +name = "Noderunners Download Bot" +about = "Send me a link to a video or a song and I send you the file.\n\nWorks with thousands of sites, in private chats and in groups. Free to try. Passes and credits are paid in sats over Lightning." +short = "Send a link, get the video or the audio. Free to try, more with sats over Lightning." + +# How dates are written. "months" holds the twelve short month names in +# order, separated by commas. The time is always UTC, and says so. +[format] +months = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec" +date = "{{.Day}} {{.Month}} {{.Year}}" +datetime = "{{.Day}} {{.Month}} {{.Year}}, {{.Hour}}:{{.Minute}} UTC" [hint] send_link = "Send me a link to a video or a song and I will fetch it. /help has the details." diff --git a/locales/es.toml b/locales/es.toml new file mode 100644 index 0000000..9549464 --- /dev/null +++ b/locales/es.toml @@ -0,0 +1,811 @@ +# Catálogo en español: neutro latinoamericano, con palabras que se leen +# bien en Paraguay. Se usa "tú". Sin signos de apertura (¿ ¡) al inicio de +# las oraciones. Debe tener exactamente las mismas claves que en.toml. +# +# Reglas: +# - Lo que está entre {{.Llaves}} es un marcador. No se traduce. +# - Se mantienen las etiquetas HTML (, , ) y los saltos de línea. +# - Los comandos (/dl, /help) no se traducen. + +[start] +private = """ +Hola {{.Name}}, te damos la bienvenida a The Noderunners Download Bot. + +Envíame el enlace de un video o una canción y te lo bajo. + +/help muestra todo lo que puedo hacer.""" +group = """ +The Noderunners Download Bot ya está en el grupo. + +Usa /dl con un enlace, o responde /dl a un mensaje que tenga un enlace.""" + +[help] +text = """ +Cómo usarme + +En un chat privado, solo envía un enlace. Te muestro una tarjeta y eliges el formato. +En un grupo, usa /dl con un enlace, o responde /dl a un mensaje que tenga un enlace. + +Comandos +/dl enlace - descargar un video +/audio enlace - descargar el audio en MP3 +/thumb enlace - obtener la miniatura +/subs enlace - obtener los subtítulos +/info enlace - ver formatos y tamaños sin descargar +/fresh enlace - descargar de nuevo en vez de usar una copia guardada +/history - tus descargas anteriores, para pedirlas otra vez con un toque +/queue - tus descargas en curso +/cancel - cancelar tus descargas +/quality - tu formato por defecto +/language - cambiar mi idioma + +Cuenta +/account - tu pase, saldo y uso +/limits - los límites que tienes +/buy - comprar un pase o créditos +/credits - tu saldo y cargar más +/redeem código - usar un código de regalo +/referral - invitar amigos y ganar sats +/donate - dejar una propina + +En grupos +/groupwallet y /grouppass - el saldo y el pase del grupo +/settings - ajustes del grupo, para administradores + +Tus límites +Hasta {{.MaxSize}} y {{.MaxDuration}} por descarga.""" + +[cmd] +unknown = "No conozco ese comando. Prueba con /help." + +[menu] +dl = "Descargar un video desde un enlace" +audio = "Descargar el audio en MP3" +thumb = "Obtener la miniatura" +info = "Ver formatos y tamaños" +queue = "Tus descargas en curso" +cancel = "Cancelar tus descargas" +history = "Tus descargas anteriores" +account = "Tu pase, saldo y uso" +buy = "Comprar un pase o créditos" +help = "Cómo usar el bot" +subs = "Obtener los subtítulos de un video" +credits = "Comprar créditos" +limits = "Tus límites" +redeem = "Canjear un código de regalo" +referral = "Invitar amigos y ganar sats" +donate = "Dejar una propina" +quality = "Elegir tu formato por defecto" +language = "Cambiar el idioma" +app = "Abrir la app" +support = "Pedir ayuda" +privacy = "Qué datos tuyos se guardan" +terms = "Condiciones de uso" +settings = "Ajustes del grupo" +grouplang = "Idioma del bot en este grupo" +autodetect = "Bajar enlaces pegados sin comando" +allow = "Permitir solo algunos sitios" +block = "Bloquear un sitio" +spending = "Quién puede gastar créditos del grupo" +groupwallet = "Saldo del grupo y recarga" +grouppass = "Comprar un pase para el grupo" +groupstats = "Descargas por miembro" + +[profile] +name = "Noderunners Download Bot" +about = "Envíame el enlace de un video o una canción y te mando el archivo.\n\nFunciona con miles de sitios, en chats privados y en grupos. Puedes probarlo gratis. Los pases y créditos se pagan en sats por Lightning." +short = "Envía un enlace y recibe el video o el audio. Gratis para probar, más con sats por Lightning." + +[format] +months = "ene,feb,mar,abr,may,jun,jul,ago,sep,oct,nov,dic" +date = "{{.Day}} {{.Month}} {{.Year}}" +datetime = "{{.Day}} {{.Month}} {{.Year}}, {{.Hour}}:{{.Minute}} UTC" + +[hint] +send_link = "Envíame el enlace de un video o una canción y te lo bajo. En /help están los detalles." + +[dl] +usage = "Agrega un enlace después del comando, o responde a un mensaje que tenga un enlace.\nEjemplo: /dl https://example.com/video" + +[info] +usage = "Agrega un enlace después del comando.\nEjemplo: /info https://example.com/video" +line = "{{.Label}}: {{.Size}}" +size_unknown = "tamaño desconocido" + +[queue] +empty = "No tienes descargas en curso." + +[queue.header] +one = "Tienes {{.Count}} descarga en curso" +other = "Tienes {{.Count}} descargas en curso" + +[cancel] +nothing = "No hay nada para cancelar." + +[cancel.done] +one = "Se canceló {{.Count}} descarga." +other = "Se cancelaron {{.Count}} descargas." + +[card] +looking = "Buscando el enlace…" +pick = "Elige un formato:" +cancelled = "Cancelado." + +[btn] +full_settings = "Abrir todos los ajustes" +add_group_credits = "Cargar créditos al grupo" +buy_group_pass = "Comprar pase de grupo" +open_app = "Abrir la app" +best = "Mejor" +res = "{{.Height}}p" +mp3 = "MP3" +m4a = "M4A" +thumb = "Miniatura" +subs = "Subtítulos ({{.Lang}})" +with_size = "{{.Label}} · {{.Size}}" +cancel = "Cancelar" +skip_queue = "Saltar la fila" +open_private = "Abrir un chat privado" +open_wallet = "Abrir en la billetera" +check_payment = "Verificar el pago" +this_file = "Solo este archivo" +buy_for_me = "Comprar para mí" +subs_auto = "{{.Lang}} (automático)" +resend = "{{.N}}. {{.Title}}" + +[status] +queued = "En la fila. Posición {{.Position}}, unos {{.Wait}}." +downloading = "Descargando…" +downloading_bytes = "Descargando… {{.Done}}" +downloading_progress = "Descargando…\n{{.Bar}} {{.Percent}}\n{{.Done}} de {{.Total}}" +processing = "Procesando el archivo…" +uploading = "Enviándolo a Telegram…" +preparing = "Preparando todo…" +done = "Listo. Que lo disfrutes." +cancelled = "Cancelado." +failed = "No funcionó. {{.Reason}}" +refunded = "Se devolvieron {{.Amount}} a tu saldo." + +[notice] +group_only = "Este comando funciona en grupos." +admins_only = "Solo los administradores del grupo pueden hacer eso." +saved = "Guardado." +cancelled = "Cancelado." +not_yours = "Estos botones son de la persona que hizo el pedido." +too_late = "Ya es tarde para cancelar eso." +expired = "Esta tarjeta venció. Envía el enlace otra vez." +already_chosen = "Ya hay una descarga en curso desde esta tarjeta." +private_only = "Esto funciona en un chat privado conmigo." +rate_limited = "Son muchos enlaces seguidos. Espera un minuto y vuelve a intentar." +paid = "Pago recibido." +not_paid_yet = "Todavía no está pagado. Puede tardar unos segundos después de pagar." +invoice_closed = "Esta factura ya está cerrada." +skipped = "Listo. Tu descarga pasó al frente." +skip_too_late = "Esta descarga ya no está esperando en la fila." +skip_private = "Abre un chat privado conmigo para pagar esto." + +[limit] +group_disabled = "El bot está apagado en este grupo." +group_admins_only = "En este grupo solo los administradores pueden usar el bot." +group_pass_only = "En este grupo necesitas un pase para usar el bot. Usa /buy en un chat privado conmigo." +group_site = "Los administradores de este grupo no permiten descargas de ese sitio." +maintenance = "Estoy en mantenimiento. Vuelve a intentar en un rato." +too_large = "Este archivo supera tu límite de {{.MaxSize}}. Prueba con una calidad más baja." +too_long = "Esto dura más que tu límite de {{.MaxDuration}}." +live = "Las transmisiones en vivo no se pueden descargar." +queue_full = "La fila está llena en este momento. Vuelve a intentar en unos minutos." +blocked = "Este contenido no está disponible en este bot." +daily_volume = "Llegaste a tu volumen diario de {{.MaxVolume}}. Se reinicia a la medianoche UTC." + +[limit.daily_downloads] +one = "Ya usaste tu {{.Count}} descarga de hoy. Se reinicia a la medianoche UTC." +other = "Ya usaste tus {{.Count}} descargas de hoy. Se reinicia a la medianoche UTC." + +[limit.active_jobs] +one = "Ya tienes {{.Count}} descarga en curso. Espera a que termine o usa /cancel." +other = "Ya tienes {{.Count}} descargas en curso. Espera a que termine una o usa /cancel." + +[unit.sats] +one = "{{.N}} sat" +other = "{{.N}} sats" + +[unit.seconds] +one = "{{.Count}} segundo" +other = "{{.Count}} segundos" + +[unit.minutes] +one = "{{.Count}} minuto" +other = "{{.Count}} minutos" + +[unit.hours] +one = "{{.Count}} hora" +other = "{{.Count}} horas" + +[error] +unsupported_url = "No puedo descargar desde ese enlace." +not_found = "No se encontró nada en ese enlace. Puede que lo hayan borrado." +private = "Este contenido es privado o solo para miembros." +login_required = "Este contenido requiere iniciar sesión en el sitio, así que no lo puedo bajar." +geo_blocked = "Este contenido no está disponible en la región desde donde descargo." +site_blocked = "El sitio rechazó la descarga por ahora. Vuelve a intentar más tarde." +rate_limited = "El sitio está limitando los pedidos por ahora. Vuelve a intentar en unos minutos." +live_stream = "Las transmisiones en vivo no se pueden descargar." +drm = "Este contenido tiene protección anticopia y no se puede descargar." +too_large = "El archivo supera tu límite. Prueba con una calidad más baja." +too_long = "Esto dura más que tu límite." +no_media = "No se encontró video ni audio en el formato que elegiste." +no_subtitles = "No se encontraron subtítulos en ese idioma." +network = "Un problema de red cortó la descarga. Vuelve a intentar." +timeout = "La descarga tardó demasiado y se detuvo." +processing_failed = "El archivo se descargó pero no se pudo procesar." +cancelled = "La descarga se canceló." +worker_lost = "La descarga se interrumpió. Vuelve a intentar." +internal = "Algo falló de mi lado. Vuelve a intentar." +unknown = "La descarga falló. Vuelve a intentar más tarde." +playlist = "Ese enlace es una lista de reproducción. Envíamelo como mensaje normal para elegir un formato para toda la lista." +playlist_nested = "Este elemento es una lista en sí, así que lo salté." +send_failed = "No pude enviar el archivo a Telegram. Vuelve a intentar." + +[product] +pass_day = "Pase de un día" +pass_week = "Pase semanal" +pass_month = "Pase mensual" +credits = "Créditos" +one_off = "Descarga única" +skip_queue = "Saltar la fila" +donation = "Donación" + +[source] +one_off = "Descarga única" +own_pass = "Tu pase" +group_pass = "Pase del grupo" +group_credits = "Créditos del grupo" +own_credits = "Tus créditos" +free = "Gratis" + +[buy] +intro = """ +Pases y créditos + +Un pase sube tus límites a {{.MaxSize}} y {{.MaxDuration}} por descarga y te pone en la fila prioritaria mientras dure. + +Los créditos pagan por descarga, {{.PerDownload}} cada una, con los mismos límites y la misma prioridad. No vencen nunca. + +Pagas en sats por Lightning.""" +unavailable = "Los pagos todavía no están configurados en este bot." +backend_down = "No puedo conectarme con el servicio de pagos en este momento. Vuelve a intentar en un momento." +backend_down_short = "El servicio de pagos no responde en este momento. Vuelve a intentar en un momento." +bad_amount = "Ese monto no es posible." + +[credits] +text = """ +Tu saldo: {{.Balance}} + +Una descarga cuesta {{.PerDownload}}. Carga saldo:""" + +[donate] +intro = "Gracias por apoyar el bot. Elige un monto:" + +[account] +title = "Tu cuenta" +pass_active = "Pase: activo hasta el {{.Until}}" +pass_none = "Pase: ninguno" +balance = "Saldo: {{.Balance}}" +today = "Hoy" +usage_downloads = "Descargas: {{.Used}} de {{.Max}}" +usage_volume = "Volumen: {{.Used}} de {{.Max}}" +unlimited = "sin límite" + +[limits] +text = """ +Tus límites ({{.Tier}}) + +Tamaño por descarga: {{.MaxSize}} +Duración por descarga: {{.MaxDuration}} +Descargas al mismo tiempo: {{.ActiveJobs}} +Descargas por día: {{.DailyDownloads}} +Volumen por día: {{.DailyVolume}}""" + +[referral.text] +one = """ +Invita a tus amigos + +Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}. + +{{.Link}} + +Hasta ahora invitaste a {{.Count}} persona.""" +other = """ +Invita a tus amigos + +Comparte tu enlace. Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}. + +{{.Link}} + +Hasta ahora invitaste a {{.Count}} personas.""" + +[redeem] +usage = "Envía el código después del comando.\nEjemplo: /redeem NR-ABCD-EFGH-JKMN" +invalid = "Ese código no es válido." +used = "Ese código ya se usó o venció." +credits = "Listo. Se agregaron {{.Amount}} a tu saldo." +pass = "Listo. Tu pase está activo hasta el {{.Until}}." +cashu_off = "Este bot no acepta tokens Cashu." +cashu_mint = "No acepto tokens de esa casa de moneda (mint)." + +[invoice] +for_group = "Para el grupo {{.Group}}" +group_balance = "El saldo del grupo ahora es {{.Balance}}." +group_pass_until = "El pase del grupo está activo hasta el {{.Until}}." +memo = "The Noderunners Download Bot: {{.Title}}" +caption = """ +{{.Title}} · {{.Amount}} + +{{.Invoice}} + +Escanea el código o toca la factura para copiarla. Vale por {{.Valid}}.""" +paid = "Pagado. {{.Title}} · {{.Amount}}" +balance = "Tu saldo ahora es {{.Balance}}." +pass_until = "Tu pase está activo hasta el {{.Until}}." +thanks = "Gracias por el apoyo." +expired = "Esta factura de {{.Title}} venció. No se cobró nada." +cancelled = "Factura cancelada." + +[pay] +title = "Pagar con Lightning" +hint = "Tu billetera Lightning debería abrirse ahora." +open = "Abrir en la billetera" +gone = "Esta factura ya no está abierta." +too_late_skip = "Tu pago llegó, pero la descarga ya había salido de la fila. En cambio se agregaron {{.Amount}} a tu saldo." +too_late_file = "Tu pago llegó, pero la descarga no se pudo iniciar. En cambio se agregaron {{.Amount}} a tu saldo." +not_started = "La descarga no se pudo iniciar. {{.Reason}}" +skip_not_needed = "Esa descarga ya no está esperando en la fila, así que no hay nada que pagar." + +[over] +options = "Puedes levantar el límite:" +started = "Tus límites ya lo permiten. La descarga empezó." + +[playlist] +empty = "No encontré ningún elemento en esa lista." +item_failed = "{{.Title}}\nSaltado. {{.Reason}}" + +[playlist.card] +one = """ +{{.Title}} +Lista con {{.Count}} elemento. Voy a bajar {{.Take}}, uno después de otro. + +Elige un formato para todos:""" +other = """ +{{.Title}} +Lista con {{.Count}} elementos. Voy a bajar {{.Take}}, uno después de otro. + +Elige un formato para todos:""" + +[playlist.queued] +one = "{{.Title}}\n{{.Count}} elemento está en espera. Empieza apenas tengas un lugar libre. /cancel lo detiene." +other = "{{.Title}}\n{{.Count}} elementos están en espera. Empiezan uno tras otro a medida que tengas lugares libres. /cancel los detiene." + +[subs] +pick = "Elige el idioma de los subtítulos:" +none = "Este video no tiene subtítulos." + +[history] +empty = "Todavía no tienes descargas anteriores." +header = "Tus descargas anteriores\nToca una para recibirla otra vez." +line = "{{.N}}. {{.Title}} · {{.Label}}" + +[owner] +books_ok = "el libro mayor y los saldos coinciden" +ln_ok = "disponible" +ln_down = "NO disponible" +queue_empty = "No hay trabajos en la fila ni en curso." +queue_line = "{{.ID}} {{.Status}} · {{.Lane}} · {{.Profile}} · trabajador {{.Worker}} · etiquetas {{.Tags}}\n{{.Title}}" +user_usage = "Ejemplo: /user 123456789" +group_usage = "Ejemplo: /group -1001234567890" +not_found = "No encontrado." +user = """ +Usuario {{.ID}} +Nombre: {{.Name}} (@{{.Username}}) +Idioma: {{.Lang}} +Bloqueado: {{.Banned}} +Pase hasta: {{.Pass}} +Saldo: {{.Balance}} +Hoy: {{.Downloads}} descargas, {{.Volume}} +Referidos: {{.Referrals}} +Visto por primera vez: {{.Since}}""" +group = """ +Grupo {{.ID}} +Título: {{.Title}} +Estado del bot: {{.Status}} +Bot activado: {{.Enabled}} +Quién puede usarlo: {{.Who}} +Gasto de créditos: {{.Spend}} +Pase hasta: {{.Pass}} +Saldo: {{.Balance}}""" +ban_usage = "Ejemplo: /ban 123456789 y /unban 123456789" +ban_owner = "No se puede bloquear a un dueño." +banned = "El usuario {{.ID}} está bloqueado." +unbanned = "El usuario {{.ID}} ya no está bloqueado." +grant_usage = """ +Dar un pase a un usuario o a un grupo (los grupos tienen ID negativos): +/grant 123456789 week +Crear un código de regalo: +/grant code credits 1000 5 +/grant code month""" +gift_code = "Código de regalo: {{.Code}}\nUsos: {{.Uses}}" +granted = "Listo. El pase de {{.ID}} dura hasta el {{.Until}}." +credit_usage = "Ejemplo: /credit 123456789 500" +refund_usage = "Ejemplos:\n/refund 123456789 500\n/refund 123456789 pass 24h" +no_pass = "Esa billetera no tiene un pase activo para extender." +credited = "Listo. Se agregaron {{.Amount}} a {{.ID}}. Saldo: {{.Balance}}." +blocklist_empty = "La lista de bloqueo está vacía." +blocklist_header = "Lista de bloqueo" +blocklist_line = "{{.Kind}}: {{.Value}} {{.Reason}}" +blocklist_usage = """ +/blocklist +/blocklist add site example.com spam +/blocklist add key youtube:VIDEOID +/blocklist remove site example.com""" +blocked = "Bloqueado: {{.Value}}" +unblocked = "Desbloqueado: {{.Value}}" +maint_usage = "Usa /maint on o /maint off." +maint_on = "El modo mantenimiento está activado. Se rechazan las descargas nuevas de todos menos de los dueños." +maint_off = "El modo mantenimiento está desactivado." +reload_usage = "Usa /reload i18n." +reload_builtin = "Las traducciones vienen dentro del binario. Configura LOCALES_DIR para cargarlas desde una carpeta." +reload_failed = "No se pudo recargar, se siguen usando las traducciones anteriores.\n{{.Error}}" +reloaded = "Traducciones recargadas: {{.Langs}}" +broadcast_usage = "Ejemplo: /broadcast El bot estará caído esta noche desde las 22:00 UTC." +broadcast_preview = "Vista previa\n\n{{.Text}}" +broadcast_done = "Envío terminado. Enviados: {{.Sent}}. Fallidos: {{.Failed}}." +stats = """ +Estadísticas +Usuarios: {{.Users}} +Últimas 24 horas: {{.Done}} listas, {{.Failed}} fallidas +Fila: {{.Paid}} pagas, {{.Free}} gratis, la más antigua espera {{.Oldest}} +Trabajadores: {{.Running}} de {{.Slots}} lugares ocupados +Aciertos de caché: {{.Rate}}, ahorrado {{.Saved}} +Recibido: {{.Sats}} +Facturas desde el inicio: {{.Created}} creadas, {{.Settled}} pagadas +Lightning: {{.Lightning}} +Libros: {{.Books}} +Mantenimiento: {{.Maint}}""" +never = "nunca" +state_active = "activo" +state_offline = "desconectado" +state_draining = "vaciándose" +state_revoked = "revocado" +worker_embedded = "integrado · {{.Running}} de {{.Capacity}} lugares ocupados" +worker_line = "{{.Name}} · {{.State}} · {{.Running}} de {{.Capacity}} lugares ocupados · visto hace {{.Seen}}\netiquetas: {{.Tags}} · yt-dlp {{.Version}}" +worker_unknown = "No hay ningún trabajador llamado {{.Name}}." +drain_usage = "Indica el trabajador.\nEjemplo: /drain eu-1, y /drain eu-1 off para que vuelva." +drain_on = "El trabajador {{.Name}} se está vaciando. Termina sus trabajos y no recibe nuevos." +drain_off = "El trabajador {{.Name}} vuelve a recibir trabajos." +ytdlp_usage = "Usa /ytdlp update para actualizar yt-dlp en todos los trabajadores." +purge_usage = "Envía un enlace, o una clave como extractor:video_id.\nEjemplo: /purge https://example.com/video aviso de derechos de autor" +cache = """ +Caché +Entradas: {{.Entries}} ({{.Stored}} con copia guardada) +Guardado: {{.Size}} de {{.Budget}} +Aciertos en total: {{.Hits}} +Retirados: {{.Blocked}} + +Desde el último inicio +Tasa de aciertos: {{.Rate}} de {{.Since}} pedidos +Volumen de descarga ahorrado: {{.Saved}}""" + +[owner.workers_header] +one = "Trabajadores\n{{.Slots}} lugares de descarga en línea, {{.Count}} trabajador remoto registrado." +other = "Trabajadores\n{{.Slots}} lugares de descarga en línea, {{.Count}} trabajadores remotos registrados." + +[owner.ytdlp_update] +one = "Se pidió a {{.Count}} trabajador que actualice yt-dlp. Lo hace la próxima vez que busque trabajo." +other = "Se pidió a {{.Count}} trabajadores que actualicen yt-dlp. Lo hacen la próxima vez que busquen trabajo." + +[owner.purged] +one = "Retirado: {{.Key}}\nSe borró {{.Count}} archivo de la caché. La clave queda bloqueada." +other = "Retirado: {{.Key}}\nSe borraron {{.Count}} archivos de la caché. La clave queda bloqueada." + +[owner.books_bad] +one = "{{.Count}} billetera NO COINCIDE con su libro mayor" +other = "{{.Count}} billeteras NO COINCIDEN con sus libros mayores" + +[owner.queue_header] +one = "{{.Count}} trabajo activo" +other = "{{.Count}} trabajos activos" + +[owner.broadcast_send] +one = "Enviar a {{.Count}} usuario" +other = "Enviar a {{.Count}} usuarios" + +[word] +on = "activado" +off = "desactivado" +none = "ninguno" + +[settings] +text = """ +Ajustes del grupo +Saldo: {{.Balance}} · Pase hasta: {{.Pass}} +Idioma: {{.Lang}} +Sitios permitidos: {{.Allowed}} +Sitios bloqueados: {{.Blocked}} +Por persona por día: {{.SpendCap}} · Grupo por día: {{.DailyCap}} + +Toca para cambiar. Hay más con /grouplang, /allow, /block y /spending.""" +button = "{{.Label}}: {{.Value}}" +enabled = "Bot" +auto_detect = "Detectar enlaces pegados" +delete_commands = "Borrar los mensajes de comandos" +who = "Quién puede usarlo" +who_everyone = "todos" +who_pass_holders = "quienes tienen pase" +who_admins = "administradores" +spend = "Créditos del grupo" +spend_anyone = "cualquiera" +spend_admins = "solo administradores" +spend_capped = "cualquiera, con tope" +quality = "Calidad por defecto" +lang_auto = "el de cada miembro" +commands = """ +Ajustes de {{.Group}} + +Envía esto en el grupo, como administrador: +/settings - ajustes rápidos +/grouplang código - idioma del bot en el grupo +/autodetect on - bajar enlaces sin comando +/allow sitio - permitir solo algunos sitios +/block sitio - bloquear un sitio +/spending regla - quién puede gastar créditos del grupo""" + +[quality] +ask = "Preguntar siempre" +pick = "Elige tu formato por defecto. Así empiezo enseguida en vez de preguntarte." +set = "Formato por defecto: {{.Quality}}" + +[language] +name = "Español" +auto = "Seguir el idioma de mi Telegram" +pick = "Elige un idioma:" +set = "Idioma: {{.Lang}}" + +[grouplang] +usage = "Agrega un código de idioma, o auto para seguir a cada miembro.\nDisponibles: {{.Langs}}" +auto = "Ahora el bot le responde a cada miembro en su propio idioma." +set = "Ahora el bot habla {{.Lang}} en este grupo." + +[autodetect] +usage = "Usa /autodetect on o /autodetect off." +on = "Desde ahora bajo los enlaces que se peguen en este grupo, sin comando. Para eso necesito ver los mensajes: hazme administrador, o desactiva la privacidad de grupo para mí en @BotFather." +off = "En este grupo solo respondo a comandos." + +[allow] +list = "Sitios permitidos: {{.Sites}}\nAgrega con /allow example.com, quita con /allow remove example.com, vacía con /allow clear. Con la lista vacía se permiten todos los sitios." + +[block] +list = "Sitios bloqueados: {{.Sites}}\nAgrega con /block example.com, quita con /block remove example.com, vacía con /block clear." + +[sites] +bad_host = "Eso no parece un sitio. Ejemplo: example.com" + +[spending] +usage = """ +Quién puede gastar créditos del grupo: +/spending admins +/spending anyone +/spending capped 200 (sats por persona por día) +/spending daily 5000 (sats por día para todo el grupo, 0 para sin tope)""" +set = "Créditos del grupo: {{.Rule}}.\nPor persona por día: {{.SpendCap}}. Grupo por día: {{.DailyCap}}." + +[groupwallet] +text = "Billetera del grupo\nSaldo: {{.Balance}}\n{{.Pass}}\nQuién puede gastar créditos: {{.Rule}}" +pass_none = "Pase: ninguno" +pass_until = "Pase: activo hasta el {{.Until}}" + +[grouppass] +text = "Pase del grupo\n{{.Pass}}\nCon un pase de grupo, todos aquí descargan con los límites más altos y en la fila prioritaria." + +[groupstats] +empty = "Nadie usó el bot aquí en los últimos 7 días." +header = "Últimos 7 días" + +[groupstats.line] +one = "{{.Name}}: {{.Count}} descarga, {{.Size}}, {{.Sats}}" +other = "{{.Name}}: {{.Count}} descargas, {{.Size}}, {{.Sats}}" + +[groupbuy] +unknown = "No conozco ese grupo, o ya no estoy en él." +intro = "{{.Group}}\nSaldo del grupo: {{.Balance}}\n\nLo que compras aquí es del grupo: un pase cubre a todos los miembros, y los créditos se gastan según las reglas del grupo." + +[app] +unavailable = "La app no está configurada en este bot." +open = "Abre la app para manejar descargas, pases y grupos." +title = "Descargas" +retry = "Reintentar" +save = "Guardar" +saved = "Guardado." +add = "Agregar" +close = "Cerrar" +done = "Listo" +copied = "Copiado." +on = "Activado" +off = "Desactivado" +untitled = "Sin título" +see_plans = "Ver pases y créditos" +sent_to_chat = "Empezó. El archivo llega a nuestro chat." +pass_until = "Pase hasta el {{.Until}}" +balance_is = "Saldo: {{.Balance}}" + +[app.error] +unauthorized = "Abre esta página desde Telegram, con el botón Abrir la app del bot." +banned = "Esta cuenta no puede usar el bot." +bad_link = "Eso no parece un enlace que yo pueda usar." +bad_settings = "Algunos de estos ajustes no son válidos." +network = "Sin conexión. Revisa tu red y vuelve a intentar." +generic = "Algo falló. Vuelve a intentar." +not_found = "Eso ya no está." + +[app.tab] +home = "Inicio" +queue = "Fila" +buy = "Comprar" +groups = "Grupos" +me = "Yo" + +[app.home] +hello = "Hola {{.Name}}" +pass_active = "Pase activo" +plan_free = "Plan gratis" +plan_free_hint = "Un pase levanta los límites y te salta la fila." +balance = "Saldo" +today = "Hoy" +downloads = "Descargas" +volume = "Volumen" +used_of = "{{.Used}} de {{.Max}}" +used_unlimited = "{{.Used}}, sin límite" +paste_title = "Nueva descarga" +paste_placeholder = "Pega un enlace" +look_up = "Buscar" +recent = "Descargas recientes" +all_history = "Todas" + +[app.queue] +title = "Tus descargas" +note = "Los archivos llegan a tu chat con el bot." +empty = "No hay nada en la fila." +waiting = "Posición {{.Position}}, unos {{.Wait}}" +downloading = "Descargando" +downloading_pct = "Descargando, {{.Percent}}" +processing = "Procesando" +sending = "Enviando a Telegram" +prioritize = "Priorizar · {{.Price}}" +prioritized = "Pasó al frente." +cancel_confirm = "Cancelar \"{{.Title}}\"?" +cancelled = "Cancelado." + +[app.buy] +unavailable = "Los pagos no están configurados en este bot." +step = "Paso {{.Step}} de {{.Total}}" +target_title = "Para quién es?" +target_note = "Un pase de grupo y los créditos de grupo sirven para los miembros de ese grupo." +for_me = "Yo" +for_group = "Grupo" +pass_title = "Pase para {{.Target}}" +pass_note = "Un pase da los límites más altos y la fila prioritaria hasta que termine. Si compras otra vez, se suma tiempo." +credits_title = "Créditos" +credits_note = "Sin pase, una descarga que supera los límites gratis cuesta {{.Price}}." +paid_title = "Con un pase o créditos" + +[app.buy.credits_downloads] +one = "unas {{.Count}} descarga" +other = "unas {{.Count}} descargas" + +[app.limit] +size = "Tamaño por descarga" +duration = "Duración por descarga" +per_day = "Descargas por día" +at_once = "Al mismo tiempo" +none = "Sin límite" + +[app.invoice] +qr_alt = "Factura Lightning como código QR" +copy = "Copiar la factura" +waiting = "Esperando el pago · {{.Time}}" +checking = "Verificando el pago…" +cancel = "Cancelar esta factura" +paid = "Pagado" +paid_text = "{{.Product}} por {{.Amount}}. Gracias." +expired = "Factura vencida" +cancelled = "Factura cancelada" +closed_text = "No se cobró nada. Si igual llega un pago, se suma al saldo." + +[app.history] +title = "Historial" +note = "Enviar otra vez cuenta como una descarga nueva. Casi siempre es instantáneo." +empty = "Todavía no hay descargas." +resend = "Enviar otra vez" + +[app.groups] +title = "Tus grupos" +note = "Grupos donde eres administrador y el bot es miembro." +empty = "Todavía no hay grupos. Agrega el bot a un grupo donde seas administrador y envía un comando ahí una vez." +no_pass = "Sin pase" + +[app.group] +balance = "Saldo del grupo" +pass = "Pase del grupo" +pass_on = "Activo" +pass_off = "Ninguno" +language = "Idioma" +auto_detect_hint = "Bajar los enlaces que pegan los miembros, sin comando." +caps_title = "Topes para este grupo" +caps_note = "Déjalo vacío para el límite normal ({{.Size}} por archivo). Un tope solo puede bajarlo." +max_size = "Archivo más grande, en MB" +max_minutes = "Video más largo, en minutos" +allowed_title = "Sitios permitidos" +allowed_note = "Si esta lista tiene sitios, solo esos funcionan en el grupo." +blocked_title = "Sitios bloqueados" +blocked_note = "Los enlaces a estos sitios se rechazan en el grupo." +site_placeholder = "example.com" +remove_site = "Quitar {{.Site}}" +top_up = "Cargar saldo o comprar un pase" +rules_title = "Reglas de gasto" +rules_note = "Los créditos del grupo pagan por los miembros que superan sus propios límites. Un tope vacío significa sin tope." +spend_cap = "Sats por persona por día" +daily_cap = "Sats por día para todo el grupo" +usage_empty = "No hubo descargas en este período." +col_member = "Miembro" +col_downloads = "Descargas" +col_volume = "Volumen" +col_spent = "Gastado" + +[app.group.tab] +overview = "Resumen" +settings = "Ajustes" +wallet = "Billetera" +usage = "Uso" + +[app.group.usage_title] +one = "Uso, último día" +other = "Uso, últimos {{.Count}} días" + +[app.me] +downloads_title = "Descargas" +quality_note = "Con un formato por defecto, un enlace empieza enseguida en vez de preguntar." +audio_only = "Solo audio" +audio_only_hint = "Bajar siempre el sonido en MP3." +language_title = "Idioma" +language = "Idioma" +referral_title = "Invita a tus amigos" +referral_note = "Cuando alguien que invitaste haga su primera compra, recibes {{.Reward}}." +copy_link = "Copiar enlace" +share = "Compartir" +invited = "Invitados hasta ahora" +support = "Soporte" + +[app.me.invited_count] +one = "{{.Count}} persona" +other = "{{.Count}} personas" + +[static] +privacy = """ +Privacidad + +Guardo lo que necesito para funcionar: tu ID y nombre de Telegram, tu idioma, los enlaces que me envías y los archivos hechos a partir de ellos, tu saldo y tus compras, y la cantidad de veces que usas el bot. + +Los archivos descargados se guardan por un tiempo limitado para que repetirlos sea rápido, y después se borran. Los archivos de enlaces que requieren iniciar sesión nunca se guardan ni se comparten. + +No vendo datos y no pregunto quién eres. Los pagos son en sats por Lightning. + +Para que se borren tus datos, escribe a {{.Contact}}.""" +terms = """ +Condiciones + +Usa el bot solo para contenido que tienes derecho a descargar. Eres responsable de lo que bajas y compartes. + +Los pases y créditos no se reembolsan una vez usados. Una descarga que falla se devuelve automáticamente. + +El servicio se ofrece tal como está, sin garantía de que un sitio determinado funcione. El abuso lleva a un bloqueo. + +Consultas: {{.Contact}}""" +support = "Necesitas ayuda? Escribe a {{.Contact}}.\n\n/help muestra lo que puedo hacer." diff --git a/locales/nl.toml b/locales/nl.toml new file mode 100644 index 0000000..599675c --- /dev/null +++ b/locales/nl.toml @@ -0,0 +1,810 @@ +# Nederlandse catalogus. Informeel ("je"). Moet precies dezelfde sleutels +# hebben als en.toml. +# +# Regels: +# - Tekst tussen {{.Accolades}} is een plaatshouder. Niet vertalen. +# - Houd de HTML-tags (, , ) en de regeleinden. +# - Commando's (/dl, /help) worden niet vertaald. + +[start] +private = """ +Hoi {{.Name}}, welkom bij The Noderunners Download Bot. + +Stuur me een link naar een video of een nummer en ik haal het voor je op. + +/help laat zien wat ik kan.""" +group = """ +The Noderunners Download Bot is er. + +Gebruik /dl met een link, of antwoord /dl op een bericht met een link.""" + +[help] +text = """ +Zo gebruik je me + +Stuur in een privéchat gewoon een link. Ik laat een kaart zien en jij kiest het formaat. +Gebruik in een groep /dl met een link, of antwoord /dl op een bericht met een link. + +Commando's +/dl link - een video downloaden +/audio link - de audio als MP3 downloaden +/thumb link - de miniatuur ophalen +/subs link - de ondertitels ophalen +/info link - formaten en groottes bekijken zonder te downloaden +/fresh link - opnieuw downloaden in plaats van een bewaarde kopie te gebruiken +/history - je eerdere downloads, met één tik opnieuw op te halen +/queue - je lopende downloads +/cancel - je downloads annuleren +/quality - je standaardformaat +/language - mijn taal wijzigen + +Account +/account - je pas, saldo en gebruik +/limits - de limieten die voor jou gelden +/buy - een pas of tegoed kopen +/credits - je saldo en opwaarderen +/redeem code - een cadeaucode gebruiken +/referral - vrienden uitnodigen en sats verdienen +/donate - een fooi geven + +In groepen +/groupwallet en /grouppass - het saldo en de pas van de groep +/settings - groepsinstellingen, voor beheerders + +Jouw limieten +Tot {{.MaxSize}} en {{.MaxDuration}} per download.""" + +[cmd] +unknown = "Dat commando ken ik niet. Probeer /help." + +[menu] +dl = "Een video downloaden via een link" +audio = "De audio als MP3 downloaden" +thumb = "De miniatuur ophalen" +info = "Formaten en groottes bekijken" +queue = "Je lopende downloads" +cancel = "Je downloads annuleren" +history = "Je eerdere downloads" +account = "Je pas, saldo en gebruik" +buy = "Een pas of tegoed kopen" +help = "Hoe je de bot gebruikt" +subs = "De ondertitels van een video ophalen" +credits = "Tegoed kopen" +limits = "Je limieten" +redeem = "Een cadeaucode inwisselen" +referral = "Vrienden uitnodigen en sats verdienen" +donate = "De bot een fooi geven" +quality = "Je standaardformaat kiezen" +language = "De taal wijzigen" +app = "De app openen" +support = "Hulp vragen" +privacy = "Wat er over je wordt bewaard" +terms = "Gebruiksvoorwaarden" +settings = "Groepsinstellingen" +grouplang = "Taal van de bot in deze groep" +autodetect = "Geplakte links ophalen zonder commando" +allow = "Alleen bepaalde sites toestaan" +block = "Een site blokkeren" +spending = "Wie groepstegoed mag uitgeven" +groupwallet = "Saldo van de groep en opwaarderen" +grouppass = "Een pas voor de groep kopen" +groupstats = "Downloads per lid" + +[profile] +name = "Noderunners Download Bot" +about = "Stuur me een link naar een video of een nummer en ik stuur je het bestand.\n\nWerkt met duizenden sites, in privéchats en in groepen. Gratis te proberen. Passen en tegoed betaal je in sats via Lightning." +short = "Stuur een link, krijg de video of de audio. Gratis te proberen, meer met sats via Lightning." + +[format] +months = "jan,feb,mrt,apr,mei,jun,jul,aug,sep,okt,nov,dec" +date = "{{.Day}} {{.Month}} {{.Year}}" +datetime = "{{.Day}} {{.Month}} {{.Year}}, {{.Hour}}:{{.Minute}} UTC" + +[hint] +send_link = "Stuur me een link naar een video of een nummer en ik haal het op. In /help staan de details." + +[dl] +usage = "Zet een link achter het commando, of antwoord op een bericht met een link.\nVoorbeeld: /dl https://example.com/video" + +[info] +usage = "Zet een link achter het commando.\nVoorbeeld: /info https://example.com/video" +line = "{{.Label}}: {{.Size}}" +size_unknown = "grootte onbekend" + +[queue] +empty = "Je hebt geen lopende downloads." + +[queue.header] +one = "Je hebt {{.Count}} lopende download" +other = "Je hebt {{.Count}} lopende downloads" + +[cancel] +nothing = "Er is niets om te annuleren." + +[cancel.done] +one = "{{.Count}} download geannuleerd." +other = "{{.Count}} downloads geannuleerd." + +[card] +looking = "Link opzoeken…" +pick = "Kies een formaat:" +cancelled = "Geannuleerd." + +[btn] +full_settings = "Alle instellingen openen" +add_group_credits = "Groepstegoed toevoegen" +buy_group_pass = "Groepspas kopen" +open_app = "App openen" +best = "Beste" +res = "{{.Height}}p" +mp3 = "MP3" +m4a = "M4A" +thumb = "Miniatuur" +subs = "Ondertitels ({{.Lang}})" +with_size = "{{.Label}} · {{.Size}}" +cancel = "Annuleren" +skip_queue = "Voordringen" +open_private = "Privéchat openen" +open_wallet = "Openen in wallet" +check_payment = "Betaling controleren" +this_file = "Alleen dit bestand" +buy_for_me = "Voor mij kopen" +subs_auto = "{{.Lang}} (automatisch)" +resend = "{{.N}}. {{.Title}}" + +[status] +queued = "In de wachtrij. Plek {{.Position}}, ongeveer {{.Wait}}." +downloading = "Downloaden…" +downloading_bytes = "Downloaden… {{.Done}}" +downloading_progress = "Downloaden…\n{{.Bar}} {{.Percent}}\n{{.Done}} van {{.Total}}" +processing = "Bestand verwerken…" +uploading = "Naar Telegram sturen…" +preparing = "Even klaarzetten…" +done = "Klaar. Veel plezier." +cancelled = "Geannuleerd." +failed = "Dat lukte niet. {{.Reason}}" +refunded = "{{.Amount}} is teruggezet op je saldo." + +[notice] +group_only = "Dit commando werkt in groepen." +admins_only = "Alleen beheerders van deze groep kunnen dat." +saved = "Opgeslagen." +cancelled = "Geannuleerd." +not_yours = "Deze knoppen zijn van degene die het vroeg." +too_late = "Te laat om dat te annuleren." +expired = "Deze kaart is verlopen. Stuur de link opnieuw." +already_chosen = "Er loopt al een download vanaf deze kaart." +private_only = "Dit werkt in een privéchat met mij." +rate_limited = "Dat zijn veel links. Wacht een minuut en probeer het opnieuw." +paid = "Betaling ontvangen." +not_paid_yet = "Nog niet betaald. Het kan na het betalen een paar seconden duren." +invoice_closed = "Deze factuur is gesloten." +skipped = "Klaar. Je download staat nu vooraan." +skip_too_late = "Deze download wacht niet meer in de wachtrij." +skip_private = "Open een privéchat met mij om hiervoor te betalen." + +[limit] +group_disabled = "De bot staat uit in deze groep." +group_admins_only = "In deze groep kunnen alleen beheerders de bot gebruiken." +group_pass_only = "In deze groep heb je een pas nodig om de bot te gebruiken. Gebruik /buy in een privéchat met mij." +group_site = "De beheerders van deze groep staan downloads van die site niet toe." +maintenance = "Ik ben in onderhoud. Probeer het straks opnieuw." +too_large = "Dit bestand is groter dan je limiet van {{.MaxSize}}. Probeer een lagere kwaliteit." +too_long = "Dit is langer dan je limiet van {{.MaxDuration}}." +live = "Livestreams kunnen niet worden gedownload." +queue_full = "De wachtrij is nu vol. Probeer het over een paar minuten opnieuw." +blocked = "Deze inhoud is niet beschikbaar via deze bot." +daily_volume = "Je hebt je dagvolume van {{.MaxVolume}} bereikt. Het begint opnieuw om middernacht UTC." + +[limit.daily_downloads] +one = "Je hebt je {{.Count}} download voor vandaag gebruikt. Het begint opnieuw om middernacht UTC." +other = "Je hebt je {{.Count}} downloads voor vandaag gebruikt. Het begint opnieuw om middernacht UTC." + +[limit.active_jobs] +one = "Je hebt al {{.Count}} lopende download. Wacht tot die klaar is of gebruik /cancel." +other = "Je hebt al {{.Count}} lopende downloads. Wacht tot er een klaar is of gebruik /cancel." + +[unit.sats] +one = "{{.N}} sat" +other = "{{.N}} sats" + +[unit.seconds] +one = "{{.Count}} seconde" +other = "{{.Count}} seconden" + +[unit.minutes] +one = "{{.Count}} minuut" +other = "{{.Count}} minuten" + +[unit.hours] +one = "{{.Count}} uur" +other = "{{.Count}} uur" + +[error] +unsupported_url = "Van die link kan ik niet downloaden." +not_found = "Op die link is niets gevonden. Misschien is het verwijderd." +private = "Deze inhoud is privé of alleen voor leden." +login_required = "Voor deze inhoud moet je inloggen op de site, dus ik kan het niet ophalen." +geo_blocked = "Deze inhoud is niet beschikbaar in de regio waar ik vandaan download." +site_blocked = "De site weigerde de download nu. Probeer het later opnieuw." +rate_limited = "De site beperkt op dit moment het aantal verzoeken. Probeer het over een paar minuten opnieuw." +live_stream = "Livestreams kunnen niet worden gedownload." +drm = "Deze inhoud is tegen kopiëren beveiligd en kan niet worden gedownload." +too_large = "Het bestand is groter dan je limiet. Probeer een lagere kwaliteit." +too_long = "Dit is langer dan je limiet." +no_media = "Er is geen video of audio gevonden in het formaat dat je koos." +no_subtitles = "Er zijn geen ondertitels in die taal gevonden." +network = "Een netwerkprobleem onderbrak de download. Probeer het opnieuw." +timeout = "De download duurde te lang en is gestopt." +processing_failed = "Het bestand is gedownload maar kon niet worden verwerkt." +cancelled = "De download is geannuleerd." +worker_lost = "De download is onderbroken. Probeer het opnieuw." +internal = "Er ging aan mijn kant iets mis. Probeer het opnieuw." +unknown = "De download is mislukt. Probeer het later opnieuw." +playlist = "Die link is een afspeellijst. Stuur hem als gewoon bericht om één formaat voor de hele lijst te kiezen." +playlist_nested = "Dit onderdeel is zelf een lijst, dus heb ik het overgeslagen." +send_failed = "Ik kon het bestand niet naar Telegram sturen. Probeer het opnieuw." + +[product] +pass_day = "Dagpas" +pass_week = "Weekpas" +pass_month = "Maandpas" +credits = "Tegoed" +one_off = "Losse download" +skip_queue = "Voordringen" +donation = "Donatie" + +[source] +one_off = "Losse download" +own_pass = "Je pas" +group_pass = "Groepspas" +group_credits = "Groepstegoed" +own_credits = "Je tegoed" +free = "Gratis" + +[buy] +intro = """ +Passen en tegoed + +Een pas verhoogt je limieten naar {{.MaxSize}} en {{.MaxDuration}} per download en zet je in de voorrangswachtrij zolang hij loopt. + +Tegoed betaalt per download, {{.PerDownload}} per stuk, met dezelfde limieten en voorrang. Het verloopt nooit. + +Je betaalt in sats via Lightning.""" +unavailable = "Betalingen zijn op deze bot nog niet ingesteld." +backend_down = "Ik kan de betaaldienst nu niet bereiken. Probeer het zo opnieuw." +backend_down_short = "De betaaldienst is nu niet bereikbaar. Probeer het zo opnieuw." +bad_amount = "Dat bedrag kan niet." + +[credits] +text = """ +Je saldo: {{.Balance}} + +Eén download kost {{.PerDownload}}. Opwaarderen:""" + +[donate] +intro = "Bedankt dat je de bot steunt. Kies een bedrag:" + +[account] +title = "Je account" +pass_active = "Pas: actief tot {{.Until}}" +pass_none = "Pas: geen" +balance = "Saldo: {{.Balance}}" +today = "Vandaag" +usage_downloads = "Downloads: {{.Used}} van {{.Max}}" +usage_volume = "Volume: {{.Used}} van {{.Max}}" +unlimited = "onbeperkt" + +[limits] +text = """ +Je limieten ({{.Tier}}) + +Grootte per download: {{.MaxSize}} +Lengte per download: {{.MaxDuration}} +Downloads tegelijk: {{.ActiveJobs}} +Downloads per dag: {{.DailyDownloads}} +Volume per dag: {{.DailyVolume}}""" + +[referral.text] +one = """ +Nodig vrienden uit + +Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}. + +{{.Link}} + +Je hebt tot nu toe {{.Count}} persoon uitgenodigd.""" +other = """ +Nodig vrienden uit + +Deel je link. Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}. + +{{.Link}} + +Je hebt tot nu toe {{.Count}} mensen uitgenodigd.""" + +[redeem] +usage = "Stuur de code achter het commando.\nVoorbeeld: /redeem NR-ABCD-EFGH-JKMN" +invalid = "Die code is niet geldig." +used = "Die code is al gebruikt of verlopen." +credits = "Klaar. Er is {{.Amount}} aan je saldo toegevoegd." +pass = "Klaar. Je pas is actief tot {{.Until}}." +cashu_off = "Deze bot accepteert geen Cashu-tokens." +cashu_mint = "Tokens van die mint accepteer ik niet." + +[invoice] +for_group = "Voor de groep {{.Group}}" +group_balance = "Het saldo van de groep is nu {{.Balance}}." +group_pass_until = "De groepspas is actief tot {{.Until}}." +memo = "The Noderunners Download Bot: {{.Title}}" +caption = """ +{{.Title}} · {{.Amount}} + +{{.Invoice}} + +Scan de code of tik op de factuur om hem te kopiëren. Geldig voor {{.Valid}}.""" +paid = "Betaald. {{.Title}} · {{.Amount}}" +balance = "Je saldo is nu {{.Balance}}." +pass_until = "Je pas is actief tot {{.Until}}." +thanks = "Bedankt voor de steun." +expired = "Deze factuur voor {{.Title}} is verlopen. Er is niets afgeschreven." +cancelled = "Factuur geannuleerd." + +[pay] +title = "Betalen met Lightning" +hint = "Je Lightning-wallet zou nu moeten openen." +open = "Openen in wallet" +gone = "Deze factuur staat niet meer open." +too_late_skip = "Je betaling is binnen, maar de download had de wachtrij al verlaten. In plaats daarvan is {{.Amount}} aan je saldo toegevoegd." +too_late_file = "Je betaling is binnen, maar de download kon niet starten. In plaats daarvan is {{.Amount}} aan je saldo toegevoegd." +not_started = "De download kon niet starten. {{.Reason}}" +skip_not_needed = "Die download wacht niet meer in de wachtrij, dus er valt niets te betalen." + +[over] +options = "Je kunt de limiet opheffen:" +started = "Je limieten laten het nu toe. De download is gestart." + +[playlist] +empty = "Ik vond geen onderdelen in die afspeellijst." +item_failed = "{{.Title}}\nOvergeslagen. {{.Reason}}" + +[playlist.card] +one = """ +{{.Title}} +Afspeellijst met {{.Count}} onderdeel. Ik haal er {{.Take}} op, een voor een. + +Kies een formaat voor allemaal:""" +other = """ +{{.Title}} +Afspeellijst met {{.Count}} onderdelen. Ik haal er {{.Take}} op, een voor een. + +Kies een formaat voor allemaal:""" + +[playlist.queued] +one = "{{.Title}}\n{{.Count}} onderdeel staat klaar. Het start zodra je een plek vrij hebt. /cancel stopt het." +other = "{{.Title}}\n{{.Count}} onderdelen staan klaar. Ze starten een voor een als je plekken vrij hebt. /cancel stopt ze." + +[subs] +pick = "Kies een taal voor de ondertitels:" +none = "Deze video heeft geen ondertitels." + +[history] +empty = "Je hebt nog geen eerdere downloads." +header = "Je eerdere downloads\nTik op een download om hem opnieuw te krijgen." +line = "{{.N}}. {{.Title}} · {{.Label}}" + +[owner] +books_ok = "grootboek en saldi kloppen" +ln_ok = "bereikbaar" +ln_down = "NIET bereikbaar" +queue_empty = "Er staan geen taken in de wachtrij of in uitvoering." +queue_line = "{{.ID}} {{.Status}} · {{.Lane}} · {{.Profile}} · werker {{.Worker}} · labels {{.Tags}}\n{{.Title}}" +user_usage = "Voorbeeld: /user 123456789" +group_usage = "Voorbeeld: /group -1001234567890" +not_found = "Niet gevonden." +user = """ +Gebruiker {{.ID}} +Naam: {{.Name}} (@{{.Username}}) +Taal: {{.Lang}} +Geblokkeerd: {{.Banned}} +Pas tot: {{.Pass}} +Saldo: {{.Balance}} +Vandaag: {{.Downloads}} downloads, {{.Volume}} +Doorverwijzingen: {{.Referrals}} +Eerst gezien: {{.Since}}""" +group = """ +Groep {{.ID}} +Titel: {{.Title}} +Status van de bot: {{.Status}} +Bot aan: {{.Enabled}} +Wie hem mag gebruiken: {{.Who}} +Tegoed uitgeven: {{.Spend}} +Pas tot: {{.Pass}} +Saldo: {{.Balance}}""" +ban_usage = "Voorbeeld: /ban 123456789 en /unban 123456789" +ban_owner = "Een eigenaar kan niet worden geblokkeerd." +banned = "Gebruiker {{.ID}} is geblokkeerd." +unbanned = "Gebruiker {{.ID}} is niet meer geblokkeerd." +grant_usage = """ +Een pas geven aan een gebruiker of een groep (groepen hebben negatieve ID's): +/grant 123456789 week +Een cadeaucode maken: +/grant code credits 1000 5 +/grant code month""" +gift_code = "Cadeaucode: {{.Code}}\nKeer te gebruiken: {{.Uses}}" +granted = "Klaar. De pas van {{.ID}} loopt tot {{.Until}}." +credit_usage = "Voorbeeld: /credit 123456789 500" +refund_usage = "Voorbeelden:\n/refund 123456789 500\n/refund 123456789 pass 24h" +no_pass = "Die wallet heeft geen actieve pas om te verlengen." +credited = "Klaar. {{.Amount}} toegevoegd aan {{.ID}}. Saldo: {{.Balance}}." +blocklist_empty = "De blokkeerlijst is leeg." +blocklist_header = "Blokkeerlijst" +blocklist_line = "{{.Kind}}: {{.Value}} {{.Reason}}" +blocklist_usage = """ +/blocklist +/blocklist add site example.com spam +/blocklist add key youtube:VIDEOID +/blocklist remove site example.com""" +blocked = "Geblokkeerd: {{.Value}}" +unblocked = "Gedeblokkeerd: {{.Value}}" +maint_usage = "Gebruik /maint on of /maint off." +maint_on = "Onderhoudsmodus staat aan. Nieuwe downloads worden geweigerd voor iedereen behalve eigenaren." +maint_off = "Onderhoudsmodus staat uit." +reload_usage = "Gebruik /reload i18n." +reload_builtin = "De vertalingen zitten in het programma zelf. Stel LOCALES_DIR in om ze uit een map te laden." +reload_failed = "Opnieuw laden mislukt, de oude vertalingen blijven in gebruik.\n{{.Error}}" +reloaded = "Vertalingen opnieuw geladen: {{.Langs}}" +broadcast_usage = "Voorbeeld: /broadcast De bot is vanavond vanaf 22:00 UTC offline." +broadcast_preview = "Voorbeeld\n\n{{.Text}}" +broadcast_done = "Rondzending klaar. Verstuurd: {{.Sent}}. Mislukt: {{.Failed}}." +stats = """ +Statistieken +Gebruikers: {{.Users}} +Laatste 24 uur: {{.Done}} klaar, {{.Failed}} mislukt +Wachtrij: {{.Paid}} betaald, {{.Free}} gratis, oudste wacht {{.Oldest}} +Werkers: {{.Running}} van {{.Slots}} plekken bezet +Cache-treffers: {{.Rate}}, bespaard {{.Saved}} +Ontvangen: {{.Sats}} +Facturen sinds de start: {{.Created}} gemaakt, {{.Settled}} betaald +Lightning: {{.Lightning}} +Boekhouding: {{.Books}} +Onderhoud: {{.Maint}}""" +never = "nooit" +state_active = "actief" +state_offline = "offline" +state_draining = "aflopend" +state_revoked = "ingetrokken" +worker_embedded = "ingebouwd · {{.Running}} van {{.Capacity}} plekken bezet" +worker_line = "{{.Name}} · {{.State}} · {{.Running}} van {{.Capacity}} plekken bezet · {{.Seen}} geleden gezien\nlabels: {{.Tags}} · yt-dlp {{.Version}}" +worker_unknown = "Er is geen werker met de naam {{.Name}}." +drain_usage = "Noem de werker.\nVoorbeeld: /drain eu-1, en /drain eu-1 off om hem terug te halen." +drain_on = "Werker {{.Name}} loopt af. Hij maakt zijn taken af en krijgt geen nieuwe." +drain_off = "Werker {{.Name}} neemt weer taken aan." +ytdlp_usage = "Gebruik /ytdlp update om yt-dlp op elke werker bij te werken." +purge_usage = "Stuur een link, of een sleutel als extractor:video_id.\nVoorbeeld: /purge https://example.com/video melding van auteursrecht" +cache = """ +Cache +Items: {{.Entries}} ({{.Stored}} met een bewaarde kopie) +Bewaard: {{.Size}} van {{.Budget}} +Treffers in totaal: {{.Hits}} +Verwijderd na melding: {{.Blocked}} + +Sinds de laatste start +Trefferpercentage: {{.Rate}} van {{.Since}} verzoeken +Bespaard downloadvolume: {{.Saved}}""" + +[owner.workers_header] +one = "Werkers\n{{.Slots}} downloadplekken online, {{.Count}} externe werker geregistreerd." +other = "Werkers\n{{.Slots}} downloadplekken online, {{.Count}} externe werkers geregistreerd." + +[owner.ytdlp_update] +one = "{{.Count}} werker gevraagd om yt-dlp bij te werken. Dat gebeurt zodra hij weer naar werk zoekt." +other = "{{.Count}} werkers gevraagd om yt-dlp bij te werken. Dat gebeurt zodra ze weer naar werk zoeken." + +[owner.purged] +one = "Verwijderd: {{.Key}}\n{{.Count}} bestand uit de cache gewist. De sleutel is geblokkeerd." +other = "Verwijderd: {{.Key}}\n{{.Count}} bestanden uit de cache gewist. De sleutel is geblokkeerd." + +[owner.books_bad] +one = "{{.Count}} wallet KLOPT NIET met zijn grootboek" +other = "{{.Count}} wallets KLOPPEN NIET met hun grootboeken" + +[owner.queue_header] +one = "{{.Count}} actieve taak" +other = "{{.Count}} actieve taken" + +[owner.broadcast_send] +one = "Naar {{.Count}} gebruiker sturen" +other = "Naar {{.Count}} gebruikers sturen" + +[word] +on = "aan" +off = "uit" +none = "geen" + +[settings] +text = """ +Groepsinstellingen +Saldo: {{.Balance}} · Pas tot: {{.Pass}} +Taal: {{.Lang}} +Toegestane sites: {{.Allowed}} +Geblokkeerde sites: {{.Blocked}} +Per persoon per dag: {{.SpendCap}} · Groep per dag: {{.DailyCap}} + +Tik om te wijzigen. Meer met /grouplang, /allow, /block en /spending.""" +button = "{{.Label}}: {{.Value}}" +enabled = "Bot" +auto_detect = "Geplakte links herkennen" +delete_commands = "Commandoberichten wissen" +who = "Wie hem mag gebruiken" +who_everyone = "iedereen" +who_pass_holders = "pashouders" +who_admins = "beheerders" +spend = "Groepstegoed" +spend_anyone = "iedereen" +spend_admins = "alleen beheerders" +spend_capped = "iedereen, met plafond" +quality = "Standaardkwaliteit" +lang_auto = "die van elk lid" +commands = """ +Instellingen van {{.Group}} + +Stuur deze in de groep, als beheerder: +/settings - snelle schakelaars +/grouplang code - taal van de bot in de groep +/autodetect on - links ophalen zonder commando +/allow site - alleen bepaalde sites toestaan +/block site - een site blokkeren +/spending regel - wie groepstegoed mag uitgeven""" + +[quality] +ask = "Elke keer vragen" +pick = "Kies je standaardformaat. Dan begin ik meteen in plaats van te vragen." +set = "Standaardformaat: {{.Quality}}" + +[language] +name = "Nederlands" +auto = "Mijn Telegram-taal volgen" +pick = "Kies een taal:" +set = "Taal: {{.Lang}}" + +[grouplang] +usage = "Zet er een taalcode achter, of auto om elk lid te volgen.\nBeschikbaar: {{.Langs}}" +auto = "De bot antwoordt nu elk lid in zijn eigen taal." +set = "De bot spreekt nu {{.Lang}} in deze groep." + +[autodetect] +usage = "Gebruik /autodetect on of /autodetect off." +on = "Ik haal nu links op die in deze groep worden geplakt, zonder commando. Daarvoor moet ik berichten kunnen zien: maak me beheerder, of zet groepsprivacy voor mij uit in @BotFather." +off = "In deze groep reageer ik alleen op commando's." + +[allow] +list = "Toegestane sites: {{.Sites}}\nToevoegen met /allow example.com, verwijderen met /allow remove example.com, leegmaken met /allow clear. Met een lege lijst is elke site toegestaan." + +[block] +list = "Geblokkeerde sites: {{.Sites}}\nToevoegen met /block example.com, verwijderen met /block remove example.com, leegmaken met /block clear." + +[sites] +bad_host = "Dat lijkt geen site. Voorbeeld: example.com" + +[spending] +usage = """ +Wie groepstegoed mag uitgeven: +/spending admins +/spending anyone +/spending capped 200 (sats per persoon per dag) +/spending daily 5000 (sats per dag voor de hele groep, 0 voor geen plafond)""" +set = "Groepstegoed: {{.Rule}}.\nPer persoon per dag: {{.SpendCap}}. Groep per dag: {{.DailyCap}}." + +[groupwallet] +text = "Wallet van de groep\nSaldo: {{.Balance}}\n{{.Pass}}\nWie tegoed mag uitgeven: {{.Rule}}" +pass_none = "Pas: geen" +pass_until = "Pas: actief tot {{.Until}}" + +[grouppass] +text = "Groepspas\n{{.Pass}}\nMet een groepspas downloadt iedereen hier met de hogere limieten en in de voorrangswachtrij." + +[groupstats] +empty = "Niemand heeft de bot hier de afgelopen 7 dagen gebruikt." +header = "Afgelopen 7 dagen" + +[groupstats.line] +one = "{{.Name}}: {{.Count}} download, {{.Size}}, {{.Sats}}" +other = "{{.Name}}: {{.Count}} downloads, {{.Size}}, {{.Sats}}" + +[groupbuy] +unknown = "Die groep ken ik niet, of ik zit er niet meer in." +intro = "{{.Group}}\nSaldo van de groep: {{.Balance}}\n\nWat je hier koopt is van de groep: een pas geldt voor elk lid, tegoed wordt uitgegeven volgens de regels van de groep." + +[app] +unavailable = "De app is op deze bot niet ingesteld." +open = "Open de app om downloads, passen en groepen te beheren." +title = "Downloads" +retry = "Opnieuw proberen" +save = "Opslaan" +saved = "Opgeslagen." +add = "Toevoegen" +close = "Sluiten" +done = "Klaar" +copied = "Gekopieerd." +on = "Aan" +off = "Uit" +untitled = "Zonder titel" +see_plans = "Passen en tegoed bekijken" +sent_to_chat = "Gestart. Het bestand komt in onze chat." +pass_until = "Pas tot {{.Until}}" +balance_is = "Saldo: {{.Balance}}" + +[app.error] +unauthorized = "Open deze pagina vanuit Telegram, met de knop App openen van de bot." +banned = "Dit account kan de bot niet gebruiken." +bad_link = "Dat lijkt geen link die ik kan gebruiken." +bad_settings = "Sommige van deze instellingen zijn niet geldig." +network = "Geen verbinding. Controleer je netwerk en probeer het opnieuw." +generic = "Er ging iets mis. Probeer het opnieuw." +not_found = "Dat is er niet meer." + +[app.tab] +home = "Start" +queue = "Wachtrij" +buy = "Kopen" +groups = "Groepen" +me = "Ik" + +[app.home] +hello = "Hoi {{.Name}}" +pass_active = "Pas actief" +plan_free = "Gratis plan" +plan_free_hint = "Een pas heft de limieten op en laat je voordringen." +balance = "Saldo" +today = "Vandaag" +downloads = "Downloads" +volume = "Volume" +used_of = "{{.Used}} van {{.Max}}" +used_unlimited = "{{.Used}}, geen limiet" +paste_title = "Nieuwe download" +paste_placeholder = "Plak een link" +look_up = "Opzoeken" +recent = "Recente downloads" +all_history = "Alles" + +[app.queue] +title = "Je downloads" +note = "Bestanden komen in je chat met de bot." +empty = "Niets in de wachtrij." +waiting = "Plek {{.Position}}, ongeveer {{.Wait}}" +downloading = "Downloaden" +downloading_pct = "Downloaden, {{.Percent}}" +processing = "Verwerken" +sending = "Naar Telegram sturen" +prioritize = "Voorrang · {{.Price}}" +prioritized = "Naar voren gezet." +cancel_confirm = "\"{{.Title}}\" annuleren?" +cancelled = "Geannuleerd." + +[app.buy] +unavailable = "Betalingen zijn op deze bot niet ingesteld." +step = "Stap {{.Step}} van {{.Total}}" +target_title = "Voor wie is het?" +target_note = "Een groepspas en groepstegoed gelden voor de leden van die groep." +for_me = "Ik" +for_group = "Groep" +pass_title = "Pas voor {{.Target}}" +pass_note = "Een pas geeft de hogere limieten en voorrang tot hij afloopt. Opnieuw kopen telt tijd erbij op." +credits_title = "Tegoed" +credits_note = "Zonder pas kost een download boven de gratis limieten {{.Price}}." +paid_title = "Met een pas of tegoed" + +[app.buy.credits_downloads] +one = "ongeveer {{.Count}} download" +other = "ongeveer {{.Count}} downloads" + +[app.limit] +size = "Grootte per download" +duration = "Lengte per download" +per_day = "Downloads per dag" +at_once = "Tegelijk" +none = "Geen limiet" + +[app.invoice] +qr_alt = "Lightning-factuur als QR-code" +copy = "Factuur kopiëren" +waiting = "Wachten op betaling · {{.Time}}" +checking = "Betaling controleren…" +cancel = "Deze factuur annuleren" +paid = "Betaald" +paid_text = "{{.Product}} voor {{.Amount}}. Bedankt." +expired = "Factuur verlopen" +cancelled = "Factuur geannuleerd" +closed_text = "Er is niets afgeschreven. Een betaling die toch nog binnenkomt gaat naar het saldo." + +[app.history] +title = "Geschiedenis" +note = "Opnieuw sturen telt als een nieuwe download. Meestal gaat het meteen." +empty = "Nog geen downloads." +resend = "Opnieuw sturen" + +[app.groups] +title = "Je groepen" +note = "Groepen waar je beheerder bent en de bot lid is." +empty = "Nog geen groepen. Voeg de bot toe aan een groep waar je beheerder bent en stuur daar één keer een commando." +no_pass = "Geen pas" + +[app.group] +balance = "Saldo van de groep" +pass = "Groepspas" +pass_on = "Actief" +pass_off = "Geen" +language = "Taal" +auto_detect_hint = "Links ophalen die leden plakken, zonder commando." +caps_title = "Plafonds voor deze groep" +caps_note = "Laat leeg voor de normale limiet ({{.Size}} per bestand). Een plafond kan die alleen verlagen." +max_size = "Grootste bestand, in MB" +max_minutes = "Langste video, in minuten" +allowed_title = "Toegestane sites" +allowed_note = "Staan er sites in deze lijst, dan werken alleen die in de groep." +blocked_title = "Geblokkeerde sites" +blocked_note = "Links naar deze sites worden in de groep geweigerd." +site_placeholder = "example.com" +remove_site = "{{.Site}} verwijderen" +top_up = "Opwaarderen of een pas kopen" +rules_title = "Regels voor uitgeven" +rules_note = "Groepstegoed betaalt voor leden die over hun eigen limieten gaan. Een leeg plafond betekent geen plafond." +spend_cap = "Sats per persoon per dag" +daily_cap = "Sats per dag voor de hele groep" +usage_empty = "Geen downloads in deze periode." +col_member = "Lid" +col_downloads = "Downloads" +col_volume = "Volume" +col_spent = "Uitgegeven" + +[app.group.tab] +overview = "Overzicht" +settings = "Instellingen" +wallet = "Wallet" +usage = "Gebruik" + +[app.group.usage_title] +one = "Gebruik, afgelopen dag" +other = "Gebruik, afgelopen {{.Count}} dagen" + +[app.me] +downloads_title = "Downloads" +quality_note = "Met een standaardformaat start een link meteen in plaats van te vragen." +audio_only = "Alleen audio" +audio_only_hint = "Altijd het geluid als MP3 ophalen." +language_title = "Taal" +language = "Taal" +referral_title = "Nodig vrienden uit" +referral_note = "Als iemand die je uitnodigde voor het eerst iets koopt, krijg jij {{.Reward}}." +copy_link = "Link kopiëren" +share = "Delen" +invited = "Tot nu toe uitgenodigd" +support = "Hulp" + +[app.me.invited_count] +one = "{{.Count}} persoon" +other = "{{.Count}} mensen" + +[static] +privacy = """ +Privacy + +Ik bewaar wat ik nodig heb om te werken: je Telegram-ID en naam, je taal, de links die je stuurt en de bestanden die daarvan zijn gemaakt, je saldo en aankopen, en tellingen van je gebruik. + +Gedownloade bestanden worden een beperkte tijd bewaard zodat herhalen snel gaat, en daarna gewist. Bestanden van links waarvoor je moet inloggen worden nooit bewaard of gedeeld. + +Ik verkoop geen gegevens en ik vraag niet wie je bent. Betalingen gaan in sats via Lightning. + +Wil je dat je gegevens worden verwijderd, neem dan contact op met {{.Contact}}.""" +terms = """ +Voorwaarden + +Gebruik de bot alleen voor inhoud die je mag downloaden. Je bent zelf verantwoordelijk voor wat je ophaalt en deelt. + +Passen en tegoed worden na gebruik niet terugbetaald. Een download die mislukt wordt automatisch terugbetaald. + +De dienst wordt geleverd zoals hij is, zonder garantie dat een bepaalde site werkt. Misbruik leidt tot een blokkade. + +Vragen: {{.Contact}}""" +support = "Hulp nodig? Schrijf naar {{.Contact}}.\n\n/help laat zien wat ik kan." diff --git a/web/miniapp/e2e/smoke.mjs b/web/miniapp/e2e/smoke.mjs index 182887b..6acad3d 100644 --- a/web/miniapp/e2e/smoke.mjs +++ b/web/miniapp/e2e/smoke.mjs @@ -226,6 +226,17 @@ try { if (!shared.startsWith("https://t.me/share/url?url=")) throw new Error("share link = " + shared); await shot(page, "me"); }); + await run("switching the language changes the app", async () => { + await page.getByLabel("Language", { exact: true }).selectOption("es"); + await tab(page, "Inicio").waitFor(); + await page.getByText("Invita a tus amigos").waitFor(); + if ((await page.evaluate(() => document.documentElement.lang)) !== "es") throw new Error("html lang was not updated"); + await shot(page, "me-spanish"); + await page.getByLabel("Idioma", { exact: true }).selectOption("nl"); + await tab(page, "Start").waitFor(); + await page.getByLabel("Taal", { exact: true }).selectOption(""); + await tab(page, "Home").waitFor(); + }); await page.context().close(); await run("a member who is not an admin sees no groups", async () => {