Files
Media-download-telegram-bot/internal/i18n/i18n.go
T
MichilisandClaude Fable 5.2 51371da0e0 Phase 5: groups
Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:46:32 +00:00

230 lines
6.0 KiB
Go

// Package i18n wraps go-i18n. Every user-facing string of the bot is looked
// up here by message ID; handlers never contain literal text.
package i18n
import (
"fmt"
"html"
"io/fs"
"log/slog"
"sort"
"strings"
"sync"
"github.com/BurntSushi/toml"
goi18n "github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
// Default is the source language and the last fallback.
const Default = "en"
// Args is the template data of a message.
type Args map[string]any
// Raw marks a template value as already safe HTML, so HTML does not escape
// it. Use it only for text produced by this package.
type Raw string
// Bundle holds the loaded catalogs.
type Bundle struct {
bundle *goi18n.Bundle
tags []language.Tag
names []string
matcher language.Matcher
log *slog.Logger
mu sync.Mutex
localizers map[string]*goi18n.Localizer
printers map[string]*message.Printer
}
// 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) {
if log == nil {
log = slog.Default()
}
b := &Bundle{
bundle: goi18n.NewBundle(language.English),
log: log,
localizers: map[string]*goi18n.Localizer{},
printers: map[string]*message.Printer{},
}
b.bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
files, err := fs.Glob(fsys, "*.toml")
if err != nil {
return nil, err
}
sort.Strings(files)
hasDefault := false
for _, name := range files {
data, err := fs.ReadFile(fsys, name)
if err != nil {
return nil, err
}
mf, err := b.bundle.ParseMessageFileBytes(data, name)
if err != nil {
return nil, fmt.Errorf("i18n: %s: %w", name, err)
}
if mf.Tag == language.English {
hasDefault = true
}
}
if !hasDefault {
return nil, fmt.Errorf("i18n: the %s catalog is missing", Default)
}
// English first, so it is the matcher's default.
b.tags = []language.Tag{language.English}
for _, t := range b.bundle.LanguageTags() {
if t != language.English {
b.tags = append(b.tags, t)
}
}
for _, t := range b.tags {
b.names = append(b.names, t.String())
}
b.matcher = language.NewMatcher(b.tags)
return b, nil
}
// Pseudo is the pseudo-locale: English with every letter accented and
// each string wrapped in brackets. Text that shows up plain while it is
// selected did not come from the catalog.
const Pseudo = "en-XA"
// Hidden reports whether a language is for testing and should not be
// offered to users.
func (b *Bundle) Hidden(lang string) bool { return strings.EqualFold(lang, Pseudo) }
// 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)
if err != nil {
return err
}
b.mu.Lock()
defer b.mu.Unlock()
b.bundle, b.tags, b.names, b.matcher = fresh.bundle, fresh.tags, fresh.names, fresh.matcher
b.localizers = map[string]*goi18n.Localizer{}
b.printers = map[string]*message.Printer{}
return nil
}
// Langs returns the loaded language tags, English first.
func (b *Bundle) Langs() []string {
b.mu.Lock()
defer b.mu.Unlock()
return append([]string(nil), b.names...)
}
// Resolve maps any language code, such as the language_code Telegram sends,
// to the closest loaded language. Regional variants fall back to their base
// language (es-PY to es) and unknown languages to English.
func (b *Bundle) Resolve(code string) string {
if code == "" {
return Default
}
tag, err := language.Parse(code)
if err != nil {
return Default
}
b.mu.Lock()
defer b.mu.Unlock()
_, idx, conf := b.matcher.Match(tag)
if conf == language.No {
return Default
}
return b.names[idx]
}
func (b *Bundle) localizer(lang string) *goi18n.Localizer {
b.mu.Lock()
defer b.mu.Unlock()
if l, ok := b.localizers[lang]; ok {
return l
}
// The chain is the exact tag, its base language, then English.
chain := []string{lang}
if base, _, ok := strings.Cut(lang, "-"); ok {
chain = append(chain, base)
}
chain = append(chain, Default)
l := goi18n.NewLocalizer(b.bundle, chain...)
b.localizers[lang] = l
return l
}
func (b *Bundle) printer(lang string) *message.Printer {
b.mu.Lock()
defer b.mu.Unlock()
if p, ok := b.printers[lang]; ok {
return p
}
tag, err := language.Parse(lang)
if err != nil {
tag = language.English
}
p := message.NewPrinter(tag)
b.printers[lang] = p
return p
}
// T returns the plain text of a message. Use it for button labels, callback
// answers and anything else Telegram does not parse as HTML. A "Count"
// argument selects the plural form.
func (b *Bundle) T(lang, id string, args Args) string {
cfg := &goi18n.LocalizeConfig{MessageID: id, TemplateData: map[string]any(args)}
if args != nil {
if c, ok := args["Count"]; ok {
cfg.PluralCount = c
}
}
out, err := b.localizer(lang).Localize(cfg)
if err != nil && out == "" {
// A missing key is a bug caught by the catalog test. At runtime we
// show the ID so the gap is visible and searchable.
b.log.Error("i18n: missing message", "id", id, "lang", lang, "err", err)
return id
}
return out
}
// HTML returns a message for parse_mode HTML. String arguments are escaped,
// so titles and names coming from the web cannot inject markup.
func (b *Bundle) HTML(lang, id string, args Args) string {
if len(args) == 0 {
return b.T(lang, id, args)
}
safe := make(Args, len(args))
for k, v := range args {
switch x := v.(type) {
case Raw:
safe[k] = string(x)
case string:
safe[k] = html.EscapeString(x)
default:
safe[k] = v
}
}
return b.T(lang, id, safe)
}
// Has reports whether the message exists in the given language itself, not
// through fallback.
func (b *Bundle) Has(lang, id string) bool {
tag, err := language.Parse(lang)
if err != nil {
return false
}
b.mu.Lock()
bundle := b.bundle
b.mu.Unlock()
_, gotTag, err := goi18n.NewLocalizer(bundle, lang).LocalizeWithTag(&goi18n.LocalizeConfig{
MessageID: id, PluralCount: 2, TemplateData: map[string]any{},
})
return err == nil && gotTag == tag
}