Files
Media-download-telegram-bot/internal/app/flow_test.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

511 lines
18 KiB
Go

package app_test
import (
"context"
"fmt"
"io/fs"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/BurntSushi/toml"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
"github.com/noderunners/dlbot/locales"
)
// --- acceptance: no English in Spanish or Dutch ------------------------------
// catalogWords returns the words of every message of a catalog.
func catalogWords(t *testing.T, lang string) map[string]bool {
t.Helper()
data, err := fs.ReadFile(locales.FS, lang+".toml")
if err != nil {
t.Fatal(err)
}
var doc map[string]any
if err := toml.Unmarshal(data, &doc); err != nil {
t.Fatal(err)
}
out := map[string]bool{}
var walk func(v any)
walk = func(v any) {
switch x := v.(type) {
case string:
for _, w := range words(x) {
out[w] = true
}
case map[string]any:
for _, e := range x {
walk(e)
}
}
}
walk(doc)
return out
}
var (
wordRe = regexp.MustCompile(`[\p{L}]{4,}`)
placeholderRe = regexp.MustCompile(`\{\{[^}]*\}\}`)
linkRe = regexp.MustCompile(`<a [^>]*>.*?</a>|https?://\S+|@\w+|/\w+`)
tagRe = regexp.MustCompile(`<[^>]+>`)
)
// words splits text into lowercase words, leaving out links, commands,
// usernames, placeholders and markup, which are the same in every language.
func words(s string) []string {
s = placeholderRe.ReplaceAllString(s, " ")
s = linkRe.ReplaceAllString(s, " ")
s = tagRe.ReplaceAllString(s, " ")
var out []string
for _, w := range wordRe.FindAllString(s, -1) {
out = append(out, strings.ToLower(w))
}
return out
}
// englishOnly are the words of the English catalog that neither the
// Spanish nor the Dutch one uses. One of them in a Spanish or Dutch
// message means English leaked in: a fallback, or a hardcoded string.
func englishOnly(t *testing.T) map[string]bool {
t.Helper()
en, es, nl := catalogWords(t, "en"), catalogWords(t, "es"), catalogWords(t, "nl")
out := map[string]bool{}
for w := range en {
if !es[w] && !nl[w] {
out[w] = true
}
}
// Words of the test fixtures, not of the bot, and "English": language
// pickers list each language under its own name.
for _, w := range []string{"test", "tester", "video", "user", "english"} {
delete(out, w)
}
return out
}
// shownTo collects every text and button label the bot showed in a chat,
// with the call each came from.
func shownTo(h *harness, chat int64) map[string]string {
out := map[string]string{}
for _, c := range h.srv.Calls("") {
if c.Failed {
continue
}
mine := c.ChatID() == chat || (c.Method == "answerCallbackQuery" && c.ChatID() == 0)
if !mine || strings.HasPrefix(c.Method, "get") || strings.HasPrefix(c.Method, "setMy") {
continue
}
if t := c.Text(); t != "" {
out[t] = c.Method
}
if t := c.Params["text"]; t != "" {
out[t] = c.Method
}
for _, b := range c.Buttons() {
out[b.Text] = c.Method + " button"
}
}
return out
}
// tour walks a new user through every screen of the bot: first start,
// help, settings with each of their pages, quality and language pickers,
// a first link and the buttons under its file, a repeated link, errors
// with their buttons, and the account and money commands.
func tour(t *testing.T, h *moneyHarness, user int64, lang string) {
t.Helper()
opt := fakeserver.Lang(lang)
send := func(text string) int {
seq := h.srv.Seq()
h.srv.PushMessage(user, user, text, opt)
return seq
}
inChat := func(c fakeserver.Call) bool { return c.ChatID() == user }
pressOn := func(c fakeserver.Call, prefix string) int {
t.Helper()
btn, ok := c.Button(prefix)
if !ok {
t.Fatalf("no %q button in %+v", prefix, c.Buttons())
}
seq := h.srv.Seq()
h.srv.PushCallback(user, user, c.MessageID, btn.Data)
return seq
}
answered := func(seq int) { h.wait(seq, "answerCallbackQuery", nil) }
// First start: a welcome with the language picker.
seq := send("/start")
welcome := h.wait(seq, "sendMessage", inChat)
if _, ok := welcome.Button("lw:"); !ok {
t.Fatalf("the first /start has no language picker: %+v", welcome.Buttons())
}
// A first link: the card once, then the file with its buttons.
seq = send(link)
card := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
seq = pressOn(card, "dl:")
video := h.finished(seq, user)
for _, prefix := range []string{"ft:", "fa:"} {
seq = pressOn(video, prefix)
file := h.finished(seq, user)
seq = pressOn(file, "fx:")
h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.MessageID == file.MessageID })
}
seq = pressOn(video, "fq:")
other := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
seq = pressOn(other, "cx:")
answered(seq)
// The same link again: already sent, with a button to get it again.
seq = send(link)
dup := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("rs:"); return ok })
seq = pressOn(dup, "rs:")
h.finished(seq, user)
// Errors, each with its next step.
seq = send(busyLink)
failed := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("fl:"); return ok })
seq = pressOn(failed, "fl:")
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == failed.MessageID && c.Text() != failed.Text() })
seq = send(privateLink)
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button(""); return ok && c.ChatID() == user })
seq = send(hugeLink)
h.wait(seq, edits, func(c fakeserver.Call) bool { _, ok := c.Button("fq:"); return ok })
// Settings and every page of them.
seq = send("/settings")
settings := h.wait(seq, "sendMessage", inChat)
for _, key := range []string{"ps:q", "ps:home", "ps:l", "ps:home", "ps:r", "ps:home", "ps:a", "ps:a", "ps:k", "ps:k"} {
seq = h.srv.Seq()
h.srv.PushCallback(user, user, settings.MessageID, key)
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == settings.MessageID })
}
// Every command a user has.
for _, cmd := range []string{
"/help", "/quality", "/language", "/queue", "/cancel", "/account", "/limits", "/referral", "/buy",
"/credits", "/donate", "/redeem", "/redeem NOPE", "/info " + link, "/info", "/history", "/dl", "/privacy",
"/terms", "/support", "/app", "/nonsense", "hello",
} {
seq = send(cmd)
h.wait(seq, "sendMessage", inChat)
}
// An invoice.
seq = send("/buy")
buy := h.wait(seq, "sendMessage", inChat)
seq = pressOn(buy, "by:pass_day")
h.wait(seq, "sendPhoto", inChat)
}
// Links of the tour with scripted outcomes.
const (
busyLink = "https://example.com/busy"
privateLink = "https://example.com/private"
hugeLink = "https://example.com/huge"
)
func tourFake() *ytdlptest.Fake {
return &ytdlptest.Fake{
ProbeErrs: map[string]error{
busyLink: &ytdlp.Error{Code: ytdlp.CodeRateLimited, Retryable: true, Raw: "HTTP Error 429"},
privateLink: &ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private video"},
},
DownloadErrs: map[string][]error{
hugeLink: {&ytdlp.Error{Code: ytdlp.CodeTooLarge, Raw: "larger than max-filesize"}},
},
}
}
func TestEveryScreenInSpanishAndDutch(t *testing.T) {
foreign := englishOnly(t)
for _, lang := range []string{"es", "nl"} {
t.Run(lang, func(t *testing.T) {
// A missing message or a fallback to English is logged as a bug,
// which fails the test (see guardHandler).
h := startApp(t, tourFake(), nil)
const user = int64(501)
tour(t, h, user, lang)
var leaks []string
for text, where := range shownTo(h.harness, user) {
for _, w := range words(text) {
if foreign[w] {
leaks = append(leaks, fmt.Sprintf("%s %q in %q", where, w, text))
break
}
}
}
sort.Strings(leaks)
if len(leaks) > 0 {
t.Fatalf("English in %s:\n%s", lang, strings.Join(leaks, "\n"))
}
})
}
}
// --- language resolution -----------------------------------------------------
func TestLanguageIsResolvedFromChoiceThenTelegramThenEnglish(t *testing.T) {
h := start(t, nil, nil)
ask := func(user int64, opts ...fakeserver.MsgOpt) string {
seq := h.srv.Seq()
h.srv.PushMessage(user, user, "hello", opts...)
return h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == user }).Text()
}
// Telegram's language_code.
if got := ask(61, fakeserver.Lang("nl")); !strings.Contains(got, "Stuur me een link") {
t.Fatalf("nl: %q", got)
}
// No catalog for it: English.
if got := ask(62, fakeserver.Lang("ja")); !strings.Contains(got, "Send me a link") {
t.Fatalf("ja: %q", got)
}
// A stored choice wins over Telegram's language.
if err := h.app.Store.SetUserLang(context.Background(), 61, "es"); err != nil {
t.Fatal(err)
}
if got := ask(61, fakeserver.Lang("nl")); !strings.Contains(got, "Envíame el enlace") {
t.Fatalf("stored es over nl: %q", got)
}
// Buttons pressed later use the same resolution.
seq := h.srv.Seq()
h.srv.PushCallback(61, 61, 1, "nonsense:1")
if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "venció") {
t.Fatalf("callback answer = %q", c.Params["text"])
}
}
func TestFirstStartShowsTheLanguagePickerOnce(t *testing.T) {
h := start(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("en"))
welcome := h.wait(seq, "sendMessage", textHas("welcome"))
if _, ok := welcome.Button("lw:nl"); !ok {
t.Fatalf("no language picker under the first welcome: %+v", welcome.Buttons())
}
// Picking Dutch writes the welcome again in Dutch.
seq = h.press(alice, alice, welcome, "lw:nl")
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool {
return c.MessageID == welcome.MessageID && strings.Contains(c.Text(), "welkom")
})
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/start", fakeserver.Lang("en"))
again := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice })
if len(again.Buttons()) != 0 || !strings.Contains(again.Text(), "welkom") {
t.Fatalf("the second /start = %q %+v", again.Text(), again.Buttons())
}
}
// --- errors with next steps --------------------------------------------------
func TestLookupErrorsAreRetriedOnceAndOfferANextStep(t *testing.T) {
h := startApp(t, tourFake(), nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, busyLink)
failed := h.wait(seq, "editMessageText", textHas("limiting requests"))
if n := countProbes(h.fake, busyLink); n != 2 {
t.Fatalf("a passing failure was looked up %d times, want 2 (one automatic retry)", n)
}
retry, ok := failed.Button("fl:")
if !ok || retry.Text != "Try again" {
t.Fatalf("buttons = %+v", failed.Buttons())
}
// Try again: the same message runs the lookup again.
seq = h.press(alice, alice, failed, "fl:")
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool {
return c.MessageID == failed.MessageID && strings.Contains(c.Text(), "Looking up")
})
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool {
return c.MessageID == failed.MessageID && strings.Contains(c.Text(), "limiting requests")
})
// A lasting failure is not retried and points to the app.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, privateLink)
priv := h.wait(seq, "editMessageText", textHas("private"))
if n := countProbes(h.fake, privateLink); n != 1 {
t.Fatalf("a lasting failure was looked up %d times", n)
}
if b, ok := priv.Button(""); !ok || b.WebApp == nil {
t.Fatalf("buttons = %+v", priv.Buttons())
}
// Someone else cannot press the buttons of a group member.
seq = h.srv.Seq()
h.srv.PushCallback(alice, bob, failed.MessageID, retry.Data)
if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "belong to the person") {
t.Fatalf("answer = %q", c.Params["text"])
}
}
func countProbes(f *ytdlptest.Fake, url string) int {
n := 0
for _, p := range f.Probes() {
if p == url {
n++
}
}
return n
}
func TestFailedDownloadOffersASmallerQualityAndAnUpgrade(t *testing.T) {
h := startApp(t, tourFake(), nil)
card := h.card(alice, alice, hugeLink)
seq := h.press(alice, alice, card, "dl:")
failed := h.wait(seq, edits, textHas("larger than your limit"))
var labels []string
for _, b := range failed.Buttons() {
labels = append(labels, b.Text)
}
if strings.Join(labels, "|") != "Smaller quality|Upgrade" {
t.Fatalf("buttons = %v", labels)
}
// Smaller quality shows the formats again.
seq = h.press(alice, alice, failed, "fq:")
h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
// Upgrade opens the buy screen.
seq = h.press(alice, alice, failed, "up")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("by:"); return ok })
}
// --- buttons under the result ------------------------------------------------
func TestResultButtonsBelongToTheRequester(t *testing.T) {
h := startGroup(t, nil, nil)
h.settings(func(s *db.GroupSettings) { s.Quality = "" })
card := h.card(group, alice, "/dl "+link)
seq := h.press(group, alice, card, "dl:")
video := h.finished(seq, group)
// In a group the file quotes the message with the link.
if replyTarget(video) == 0 {
t.Fatal("in a group the file must quote the link message")
}
// Bob may look, not press.
del, _ := video.Button("fx:")
seq = h.srv.Seq()
h.srv.PushCallback(group, bob, video.MessageID, del.Data)
if c := h.wait(seq, "answerCallbackQuery", nil); !strings.Contains(c.Params["text"], "belong to the person") {
t.Fatalf("answer to bob = %q", c.Params["text"])
}
h.never(seq, "deleteMessage", nil)
// Alice asks for the MP3: a new download, quoted under her file.
seq = h.press(group, alice, video, "fa:")
audio := h.finished(seq, group)
if audio.Method != "sendAudio" || replyTarget(audio) != video.MessageID {
t.Fatalf("follow-up = %s replying to %d", audio.Method, replyTarget(audio))
}
// And deletes the video.
seq = h.press(group, alice, video, "fx:")
if c := h.wait(seq, "deleteMessage", nil); c.MessageID != video.MessageID {
t.Fatalf("deleted %d, want %d", c.MessageID, video.MessageID)
}
}
// --- several links, repeated links -------------------------------------------
func TestSeveralLinksInOneMessage(t *testing.T) {
h := start(t, nil, func(c *config.Config) {
c.MultiLinkMax = 3
c.Limits.Free.ActiveJobs = 5
})
h.askEveryTime(alice)
seq := h.srv.Seq()
var text []string
for i := 1; i <= 4; i++ {
text = append(text, fmt.Sprintf("https://example.com/v%d", i))
}
h.srv.PushMessage(alice, alice, strings.Join(text, " "))
for i := 0; i < 3; i++ {
h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok && c.Seq > seq })
seq = h.srv.Seq() - 1
}
time.Sleep(300 * time.Millisecond)
if n := len(h.fake.Probes()); n != 3 {
t.Fatalf("%d links looked up, the limit is 3", n)
}
}
func TestAlreadySentLinkOffersToSendAgain(t *testing.T) {
h := start(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 2 })
h.fetch(alice, link+"&utm_source=a")
// The same link, shared with other tracking tags.
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, link+"&si=XYZ")
dup := h.wait(seq, "sendMessage", textHas("a moment ago"))
if n := len(h.fake.Probes()); n != 1 {
t.Fatalf("a repeated link was looked up again (%d lookups)", n)
}
// Sending again is a new download under the same limits.
seq = h.press(alice, alice, dup, "rs:")
h.finished(seq, alice)
if u := h.usage(alice); u.Downloads != 2 {
t.Fatalf("usage = %+v, want 2 downloads", u)
}
seq = h.press(alice, alice, dup, "rs:")
h.wait(seq, edits, textHas("You used your 2 downloads for today"))
}
// --- queue noise ---------------------------------------------------------------
func TestQueuePositionIsShownOnlyWhenItMatters(t *testing.T) {
block := make(chan struct{})
h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) {
c.Worker.Concurrency = 1
c.QueueNoticeThresholdSeconds = 0
})
// Alice gets the free slot at once: no queue talk.
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Downloading") })
h.never(seq, edits, textHas("In the queue"))
// Bob and Carol wait behind her: that is worth knowing.
card = h.card(bob, bob, "https://example.com/other")
seqBob := h.press(bob, bob, card, "dl:")
h.wait(seqBob, edits, func(c fakeserver.Call) bool {
return c.ChatID() == bob && strings.Contains(c.Text(), "In the queue. Position 1")
})
card = h.card(carol, carol, "https://example.com/third")
seq = h.press(carol, carol, card, "dl:")
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == carol && strings.Contains(c.Text(), "Position 2") })
close(block)
h.finished(seqBob, bob)
}
// --- menu button ----------------------------------------------------------------
func TestMenuButtonOpensTheAppInTheUsersLanguage(t *testing.T) {
h := startApp(t, nil, nil)
if c := h.srv.Calls("setChatMenuButton"); len(c) == 0 || c[0].Params["chat_id"] != "" ||
!strings.Contains(c[0].Params["menu_button"], `"web_app"`) {
t.Fatalf("default menu button = %+v", c)
}
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "hello", fakeserver.Lang("es"))
btn := h.wait(seq, "setChatMenuButton", func(c fakeserver.Call) bool { return c.Params["chat_id"] == "42" })
if !strings.Contains(btn.Params["menu_button"], "Abrir la app") {
t.Fatalf("menu button = %s", btn.Params["menu_button"])
}
// Once is enough.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "hello again", fakeserver.Lang("es"))
h.wait(seq, "sendMessage", nil)
h.never(seq, "setChatMenuButton", nil)
// A new language relabels it.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/language")
pick := h.wait(seq, "sendMessage", nil)
seq = h.press(alice, alice, pick, "lg:nl")
btn = h.wait(seq, "setChatMenuButton", func(c fakeserver.Call) bool { return c.Params["chat_id"] == "42" })
if !strings.Contains(btn.Params["menu_button"], "App openen") {
t.Fatalf("menu button after switching = %s", btn.Params["menu_button"])
}
}