// 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 } // Langs returns the loaded language tags, English first. func (b *Bundle) Langs() []string { 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 } _, 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 } _, gotTag, err := goi18n.NewLocalizer(b.bundle, lang).LocalizeWithTag(&goi18n.LocalizeConfig{ MessageID: id, PluralCount: 2, TemplateData: map[string]any{}, }) return err == nil && gotTag == tag }