Phase 1: core bot
Link in, card, download, send, in private chats and groups. - cmd/core with an embedded download worker - Telegram front end on telego v1.13.0 (Bot API 10.4): link card with thumbnail and format buttons, one live status message, /dl /audio /thumb /info /queue /cancel, group support with requester-only buttons - Database backed queue: paid and free lanes, leases with heartbeats, one automatic retry, cancel, queue position and wait estimate - yt-dlp and ffprobe behind a Runner interface with classified, redacted errors mapped to friendly messages - SQLite via modernc with goose migrations, portable schema - Local file storage behind a Storage interface - go-i18n with an English catalog, no literal text in handlers - Free tier limits enforced before queueing and again on the real file - Bot token and webhook secret are stripped from all log output - Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end flows against a fake Bot API server; opt-in test with the real yt-dlp Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Size formats a byte count for humans in the user's locale, for example
|
||||
// "61.9 MB" in English and "61,9 MB" in Spanish and Dutch.
|
||||
func (b *Bundle) Size(lang string, bytes int64) string {
|
||||
const unit = 1024
|
||||
p := b.printer(lang)
|
||||
switch {
|
||||
case bytes < unit:
|
||||
return p.Sprintf("%d B", bytes)
|
||||
case bytes < unit*unit:
|
||||
return p.Sprintf("%.0f KB", float64(bytes)/unit)
|
||||
case bytes < unit*unit*unit:
|
||||
v := float64(bytes) / (unit * unit)
|
||||
if v >= 100 {
|
||||
return p.Sprintf("%.0f MB", v)
|
||||
}
|
||||
return p.Sprintf("%.1f MB", v)
|
||||
default:
|
||||
return p.Sprintf("%.2f GB", float64(bytes)/(unit*unit*unit))
|
||||
}
|
||||
}
|
||||
|
||||
// Clock formats a media duration as 1:02:03 or 2:03.
|
||||
func Clock(seconds int64) string {
|
||||
if seconds < 0 {
|
||||
seconds = 0
|
||||
}
|
||||
h, m, s := seconds/3600, seconds/60%60, seconds%60
|
||||
if h > 0 {
|
||||
return fmt.Sprintf("%d:%02d:%02d", h, m, s)
|
||||
}
|
||||
return fmt.Sprintf("%d:%02d", m, s)
|
||||
}
|
||||
|
||||
// Span formats a length of time in words, such as "30 seconds", "5 minutes"
|
||||
// or "2 hours", using the plural rules of the language.
|
||||
func (b *Bundle) Span(lang string, d time.Duration) string {
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
n := int(d.Round(time.Second) / time.Second)
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
return b.T(lang, "unit.seconds", Args{"Count": n})
|
||||
case d < time.Hour:
|
||||
return b.T(lang, "unit.minutes", Args{"Count": int(d.Round(time.Minute) / time.Minute)})
|
||||
default:
|
||||
return b.T(lang, "unit.hours", Args{"Count": int(d.Round(time.Hour) / time.Hour)})
|
||||
}
|
||||
}
|
||||
|
||||
// Percent formats a ratio in the 0 to 1 range as a whole percentage.
|
||||
func (b *Bundle) Percent(lang string, ratio float64) string {
|
||||
if ratio < 0 {
|
||||
ratio = 0
|
||||
}
|
||||
if ratio > 1 {
|
||||
ratio = 1
|
||||
}
|
||||
return b.printer(lang).Sprintf("%d%%", int(ratio*100+0.5))
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package i18n_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"github.com/noderunners/dlbot/internal/i18n"
|
||||
"github.com/noderunners/dlbot/internal/ytdlp"
|
||||
"github.com/noderunners/dlbot/locales"
|
||||
)
|
||||
|
||||
func load(t *testing.T) *i18n.Bundle {
|
||||
t.Helper()
|
||||
b, err := i18n.Load(locales.FS, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestEveryErrorCodeHasAMessage(t *testing.T) {
|
||||
b := load(t)
|
||||
for _, code := range ytdlp.KnownCodes {
|
||||
if !b.Has("en", "error."+string(code)) {
|
||||
t.Errorf("the en catalog has no message for error.%s", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPluralsAndArgs(t *testing.T) {
|
||||
b := load(t)
|
||||
if got := b.T("en", "unit.minutes", i18n.Args{"Count": 1}); got != "1 minute" {
|
||||
t.Errorf("one = %q", got)
|
||||
}
|
||||
if got := b.T("en", "unit.minutes", i18n.Args{"Count": 5}); got != "5 minutes" {
|
||||
t.Errorf("other = %q", got)
|
||||
}
|
||||
if got := b.T("en", "btn.res", i18n.Args{"Height": 720}); got != "720p" {
|
||||
t.Errorf("btn.res = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLEscapesArguments(t *testing.T) {
|
||||
b := load(t)
|
||||
got := b.HTML("en", "start.private", i18n.Args{"Name": "<script>alert(1)</script>"})
|
||||
if strings.Contains(got, "<script>") {
|
||||
t.Fatalf("user text was not escaped: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "<b>") {
|
||||
t.Fatalf("catalog markup must survive: %q", got)
|
||||
}
|
||||
raw := b.HTML("en", "info.line", i18n.Args{"Label": i18n.Raw("<i>x</i>"), "Size": "1 & 2"})
|
||||
if raw != "<i>x</i>: 1 & 2" {
|
||||
t.Fatalf("Raw handling = %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingKeyReturnsID(t *testing.T) {
|
||||
b := load(t)
|
||||
if got := b.T("en", "no.such.key", nil); got != "no.such.key" {
|
||||
t.Fatalf("missing key = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAndFallbackChain(t *testing.T) {
|
||||
fsys := fstest.MapFS{
|
||||
"en.toml": {Data: []byte("hello = \"Hello\"\nbye = \"Bye\"\nonly_en = \"Only English\"\n")},
|
||||
"es.toml": {Data: []byte("hello = \"Hola\"\nbye = \"Chau\"\n")},
|
||||
"nl.toml": {Data: []byte("hello = \"Hallo\"\n")},
|
||||
}
|
||||
b, err := i18n.Load(fsys, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolve := map[string]string{
|
||||
"": "en", "en": "en", "en-GB": "en", "es": "es", "es-PY": "es", "es-419": "es",
|
||||
"nl": "nl", "nl-BE": "nl", "de": "en", "zz": "en", "not a tag!": "en",
|
||||
}
|
||||
for in, want := range resolve {
|
||||
if got := b.Resolve(in); got != want {
|
||||
t.Errorf("Resolve(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
// es-PY falls back to es, then to en for keys es does not have.
|
||||
if got := b.T("es-PY", "bye", nil); got != "Chau" {
|
||||
t.Errorf("es-PY bye = %q, want the es text", got)
|
||||
}
|
||||
if got := b.T("es-PY", "only_en", nil); got != "Only English" {
|
||||
t.Errorf("es-PY only_en = %q, want the en text", got)
|
||||
}
|
||||
if got := b.T("nl", "bye", nil); got != "Bye" {
|
||||
t.Errorf("nl bye = %q, want the en fallback", got)
|
||||
}
|
||||
if b.Has("nl", "bye") || !b.Has("nl", "hello") {
|
||||
t.Error("Has must not count fallbacks")
|
||||
}
|
||||
if langs := b.Langs(); len(langs) != 3 || langs[0] != "en" {
|
||||
t.Errorf("Langs = %v", langs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadNeedsEnglish(t *testing.T) {
|
||||
if _, err := i18n.Load(fstest.MapFS{"es.toml": {Data: []byte("a = \"b\"\n")}}, nil); err == nil {
|
||||
t.Fatal("loading without en.toml must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatting(t *testing.T) {
|
||||
b := load(t)
|
||||
sizes := map[int64]string{
|
||||
512: "512 B",
|
||||
2048: "2 KB",
|
||||
5 << 20: "5.0 MB",
|
||||
64_900_000: "61.9 MB",
|
||||
150 << 20: "150 MB",
|
||||
3 << 29: "1.50 GB",
|
||||
}
|
||||
for in, want := range sizes {
|
||||
if got := b.Size("en", in); got != want {
|
||||
t.Errorf("Size(%d) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
if got := b.Size("es", 64_900_000); got != "61,9 MB" {
|
||||
t.Errorf("Spanish decimal separator: %q", got)
|
||||
}
|
||||
clocks := map[int64]string{0: "0:00", 59: "0:59", 61: "1:01", 3600: "1:00:00", 3723: "1:02:03"}
|
||||
for in, want := range clocks {
|
||||
if got := i18n.Clock(in); got != want {
|
||||
t.Errorf("Clock(%d) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
spans := map[time.Duration]string{
|
||||
0: "1 second", 30 * time.Second: "30 seconds", 60 * time.Second: "1 minute",
|
||||
10 * time.Minute: "10 minutes", 3 * time.Hour: "3 hours",
|
||||
}
|
||||
for in, want := range spans {
|
||||
if got := b.Span("en", in); got != want {
|
||||
t.Errorf("Span(%s) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
if got := b.Percent("en", 0.426); got != "43%" {
|
||||
t.Errorf("Percent = %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user