Files
Media-download-telegram-bot/internal/i18n/i18n.go
T
MichilisandClaude Opus 5.5 f1f9c6156c Phase 7: languages
- Complete Spanish (neutral Latin American, Paraguay friendly, no
  inverted marks) and Dutch catalogs, including the Mini App and owner texts
- Command menus per language in three scopes (private, group members,
  group admins); per-chat menus follow a user's /language and a group's
  /grouplang, from chat and from the Mini App
- Bot name, description and short description per language, sent only
  when the catalog text changes (TELEGRAM_SET_PROFILE)
- Dates from the catalog, numbers, sizes and durations per locale
- Pseudo-locale en-XA generated from English (I18N_PSEUDO), owners only
- Catalog checks: completeness, placeholders, tags, commands, plurals,
  Telegram length limits, untranslated text, unused and missing IDs
- CI workflow; make i18n-check; docs/TRANSLATING.md
- Test fix: the queued-download helper could match another chat's status

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:42:31 +00:00

351 lines
9.3 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 (
"bytes"
"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
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
mu sync.Mutex
localizers map[string]*goi18n.Localizer
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, 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{},
printers: map[string]*message.Printer{},
raw: map[string]map[string]any{},
}
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
}
var doc map[string]any
if err := toml.Unmarshal(data, &doc); err == nil {
b.raw[mf.Tag.String()] = doc
}
}
if !hasDefault {
return nil, fmt.Errorf("i18n: the %s catalog is missing", Default)
}
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() {
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, b.opts...)
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.raw = fresh.raw
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
}
// rtlLangs are the languages written right to left.
var rtlLangs = map[string]bool{"ar": true, "he": true, "fa": true, "ur": true, "ps": true, "sd": true, "yi": true, "dv": true, "ckb": true, "ug": true}
// Dir returns the text direction of a language: "rtl" or "ltr".
func Dir(lang string) string {
base, _, _ := strings.Cut(strings.ToLower(lang), "-")
if rtlLangs[base] {
return "rtl"
}
return "ltr"
}
var pluralForms = map[string]bool{"zero": true, "one": true, "two": true, "few": true, "many": true, "other": true}
// Section exports one top-level table of the catalogs for a client that
// renders text itself, such as the Mini App. Keys are flattened with dots.
// A value is a string, or an object of plural forms. Placeholders are
// rewritten from {{.Name}} to {Name}. Languages fall back the same way as
// everywhere else: the exact one, its base language, then English.
func (b *Bundle) Section(lang, table string) map[string]any {
b.mu.Lock()
defer b.mu.Unlock()
out := map[string]any{}
chain := []string{Default}
if base, _, ok := strings.Cut(lang, "-"); ok && base != Default {
chain = append(chain, base)
}
if lang != Default {
chain = append(chain, lang)
}
for _, l := range chain {
doc, ok := b.raw[l]
if !ok {
continue
}
if t, ok := doc[table].(map[string]any); ok {
flatten("", t, out)
}
}
return out
}
func flatten(prefix string, in map[string]any, out map[string]any) {
for k, v := range in {
key := k
if prefix != "" {
key = prefix + "." + k
}
switch x := v.(type) {
case string:
out[key] = clientTemplate(x)
case map[string]any:
if isPlural(x) {
forms := map[string]string{}
for form, text := range x {
if s, ok := text.(string); ok {
forms[form] = clientTemplate(s)
}
}
out[key] = forms
} else {
flatten(key, x, out)
}
}
}
}
func isPlural(m map[string]any) bool {
if len(m) == 0 {
return false
}
for k, v := range m {
if _, ok := v.(string); !ok || !pluralForms[k] {
return false
}
}
return true
}
// clientTemplate turns {{.Name}} into {Name}.
func clientTemplate(s string) string {
s = strings.ReplaceAll(s, "{{.", "{")
return strings.ReplaceAll(s, "}}", "}")
}