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>
This commit is contained in:
Michilis
2026-11-18 20:08:58 +00:00
co-authored by Claude Opus 5.5
parent 3c153af97f
commit 6843053582
52 changed files with 3369 additions and 271 deletions
+134 -29
View File
@@ -107,7 +107,10 @@ func (h *harness) boot() {
Config: h.cfg,
Log: slog.New(&guardHandler{Handler: base, t: h.t}),
Runner: h.runner, Transcoder: h.trans,
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
Tune: func(b *bot.Bot) {
b.SetTimings(60*time.Millisecond, 0)
b.SetThumbnails(testThumbs{})
},
})
if err != nil {
cancel()
@@ -124,6 +127,20 @@ func (h *harness) boot() {
}
}
// testThumbs stands in for fetching thumbnails from the web: the fake
// yt-dlp's thumbnail URL gives a fixed small JPEG, anything else none.
type testThumbs struct{}
// testThumbJPEG is what testThumbs returns.
var testThumbJPEG = []byte("\xff\xd8\xff\xe0test-thumbnail\xff\xd9")
func (testThumbs) Fetch(_ context.Context, url string) []byte {
if url == "https://img.example.com/t.jpg" {
return testThumbJPEG
}
return nil
}
// guardHandler fails the test when the core logs something that is always
// a bug: a message ID that is missing from the catalog, or a panic.
type guardHandler struct {
@@ -193,6 +210,29 @@ func (h *harness) never(after int, method string, match func(fakeserver.Call) bo
}
}
// fileMethods are the calls that send a downloaded file.
const fileMethods = "sendVideo|sendAudio|sendDocument|sendPhoto"
// isResult matches a delivered file: it carries the buttons for the next
// step, among them Delete. A card, which is also a photo, has format
// buttons instead.
func isResult(chat int64) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool {
_, ok := c.Button("fx:")
return ok && (chat == 0 || c.ChatID() == chat)
}
}
// finished waits for a download to end the way it should: the file in the
// chat, then the status message deleted so the file is the only message
// left. chat 0 matches any chat. It returns the file call.
func (h *harness) finished(after int, chat int64) fakeserver.Call {
h.t.Helper()
file := h.wait(after, fileMethods, isResult(chat))
h.wait(file.Seq, "deleteMessage", func(c fakeserver.Call) bool { return c.ChatID() == file.ChatID() })
return file
}
func textHas(sub string) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool { return strings.Contains(c.Text(), sub) }
}
@@ -203,9 +243,11 @@ func textIs(want string) func(fakeserver.Call) bool {
const edits = "editMessageText|editMessageCaption"
// card sends a link and returns the card call.
// card sends a link and returns the card call. The user is set to "ask
// every time" first, the setting under which every link shows a card.
func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) fakeserver.Call {
h.t.Helper()
h.askEveryTime(user)
seq := h.srv.Seq()
h.srv.PushMessage(chat, user, text, opts...)
return h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool {
@@ -214,6 +256,26 @@ func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt)
})
}
// askEveryTime makes sure a user sees the card for every link. A user who
// never chose a default gets the card once and "best that fits" after it.
func (h *harness) askEveryTime(user int64) {
h.t.Helper()
ctx := context.Background()
u, err := h.app.Store.GetUser(ctx, user)
if err == db.ErrNotFound {
if u, err = h.app.Store.UpsertUser(ctx, user, "", "User", "en"); err != nil {
h.t.Fatal(err)
}
} else if err != nil {
h.t.Fatal(err)
}
if u.Quality == "" {
if err := h.app.Store.SetUserQuality(ctx, user, "ask"); err != nil {
h.t.Fatal(err)
}
}
}
func (h *harness) press(chat, user int64, card fakeserver.Call, prefix string) (seq int) {
h.t.Helper()
btn, ok := card.Button(prefix)
@@ -270,17 +332,23 @@ func TestPrivateLinkReturnsFile(t *testing.T) {
seq := h.srv.Seq()
msgID := h.srv.PushMessage(alice, alice, "look at this "+link)
h.wait(seq, "sendMessage", textHas("Looking up"))
looking := h.wait(seq, "sendMessage", textHas("Looking up"))
card := h.wait(seq, "sendPhoto", nil)
if !strings.Contains(card.Text(), "<b>Test Video</b>") || !strings.Contains(card.Text(), "1:00") ||
!strings.Contains(card.Text(), "example.com") {
t.Fatalf("card text = %q", card.Text())
}
// The first link of a new user shows the card once and says what
// happens from now on.
if !strings.Contains(card.Text(), "best quality that fits your limit") {
t.Fatalf("the first card does not explain the new default: %q", card.Text())
}
if card.Params["photo"] != "https://img.example.com/t.jpg" {
t.Fatalf("card photo = %q", card.Params["photo"])
}
if replyTarget(card) != msgID {
t.Fatalf("the card must reply to the link message")
// A private chat has one conversation: nothing is quoted.
if replyTarget(card) != 0 || replyTarget(looking) != 0 {
t.Fatalf("a private answer quotes the link message")
}
var labels []string
for _, b := range card.Buttons() {
@@ -290,7 +358,7 @@ func TestPrivateLinkReturnsFile(t *testing.T) {
t.Errorf("bad callback data %q", b.Data)
}
}
want := []string{"Best · 10.0 MB", "480p · 5.0 MB", "MP3 · 1.0 MB", "Thumbnail", "Cancel"}
want := []string{"Best · 10 MB", "480p · 5 MB", "MP3 · 1 MB", "Thumbnail", "Cancel"}
if strings.Join(labels, "|") != strings.Join(want, "|") {
t.Fatalf("buttons = %v, want %v", labels, want)
}
@@ -309,21 +377,56 @@ func TestPrivateLinkReturnsFile(t *testing.T) {
if video.Params["supports_streaming"] != "true" || video.Params["width"] != "1280" || video.Params["duration"] != "60" {
t.Fatalf("video params = %+v", video.Params)
}
if replyTarget(video) != msgID {
t.Fatalf("the file must reply to the link message")
if replyTarget(video) != 0 {
t.Fatalf("the file quotes the link message in a private chat")
}
done := h.wait(seq, "editMessageCaption", textHas("Done"))
if done.MessageID != card.MessageID || len(done.Buttons()) != 0 {
t.Fatalf("the card must end as a status without buttons: %+v", done.Params)
// Forwarding works: the content is not protected.
if video.Params["protect_content"] == "true" {
t.Fatal("the video is protected")
}
// The caption: title, uploader and length, a clean link, the bot.
wantCaption := "<b>Test Video</b>\nTester · 1:00\n" +
`<a href="https://example.com/watch?v=1">example.com/watch?v=1</a>` + "\nvia @" + fakeserver.BotUsername
if video.Text() != wantCaption {
t.Fatalf("caption = %q, want %q", video.Text(), wantCaption)
}
// The thumbnail is uploaded with the video.
if f, ok := video.Files["thumbnail"]; !ok || f.Size != int64(len(testThumbJPEG)) {
t.Fatalf("thumbnail = %+v, %v", f, ok)
}
var next []string
for _, b := range video.Buttons() {
next = append(next, b.Text)
}
if strings.Join(next, "|") != "Audio (MP3)|Other quality|Thumbnail|Delete" {
t.Fatalf("buttons under the file = %v", next)
}
// One message per job: the card that showed the status is gone, and
// nothing says "Done" under the file.
gone := h.wait(video.Seq, "deleteMessage", nil)
if gone.MessageID != card.MessageID {
t.Fatalf("deleted message %d, want the card %d", gone.MessageID, card.MessageID)
}
h.never(video.Seq, edits, textHas("Done"))
_ = msgID
h.waitJobs(db.JobDone, 1)
// The delivered file stays as the cache's stored copy.
if n := h.storedFiles(); n != 1 {
t.Fatalf("%d files in storage after delivery, want the one cached copy", n)
// The user's default is now "best that fits": the next link starts
// right away, with one status message that becomes the file.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "https://example.com/watch?v=2")
status := h.wait(seq, "sendMessage", textHas("Looking up"))
h.never(seq, "sendPhoto", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
second := h.finished(seq, alice)
if gone := h.wait(second.Seq, "deleteMessage", nil); gone.MessageID != status.MessageID {
t.Fatalf("deleted %d, want the status %d", gone.MessageID, status.MessageID)
}
if n := len(h.fake.Probes()); n != 1 {
t.Fatalf("probes = %d, want 1", n)
h.waitJobs(db.JobDone, 2)
// The delivered files stay as the cache's stored copies.
if n := h.storedFiles(); n != 2 {
t.Fatalf("%d files in storage after delivery, want the two cached copies", n)
}
if n := len(h.fake.Probes()); n != 2 {
t.Fatalf("probes = %d, want 2", n)
}
}
@@ -346,7 +449,7 @@ func TestStatusGoesThroughDownloadingAndUploading(t *testing.T) {
h.wait(seq, edits, textHas("Sending it to Telegram"))
h.wait(seq, "sendChatAction", func(c fakeserver.Call) bool { return c.Params["action"] == "upload_video" })
h.wait(seq, "sendVideo", nil)
h.wait(seq, edits, textHas("Done"))
h.finished(seq, 0)
}
// --- acceptance: groups work with /dl --------------------------------------
@@ -552,10 +655,12 @@ func TestThumbnailFetchFailureFallsBackToTextCard(t *testing.T) {
// The text card works exactly like the photo card.
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", nil)
done := h.wait(seq, "editMessageText", textHas("Done"))
if done.MessageID != card.MessageID {
t.Fatal("the text card must become the status message")
h.wait(seq, edits, func(c fakeserver.Call) bool {
return c.MessageID == card.MessageID && !strings.Contains(c.Text(), "Pick a format")
})
h.finished(seq, alice)
if gone := h.wait(seq, "deleteMessage", nil); gone.MessageID != card.MessageID {
t.Fatal("the text card must be the status message, and go once the file is there")
}
}
@@ -568,7 +673,7 @@ func TestRejectedVideoIsSentAsDocument(t *testing.T) {
if doc.Files["document"].Size != 1024 {
t.Fatalf("document upload = %+v", doc.Files)
}
h.wait(seq, edits, textHas("Done"))
h.finished(seq, 0)
}
func TestTransientSendFailureIsRetried(t *testing.T) {
@@ -577,7 +682,7 @@ func TestTransientSendFailureIsRetried(t *testing.T) {
h.srv.FailNext("sendVideo", 500, "Internal Server Error")
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed })
h.wait(seq, edits, textHas("Done"))
h.finished(seq, 0)
h.waitJobs(db.JobDone, 1)
}
@@ -611,7 +716,7 @@ func TestOverSizeAndOverDurationAreRefused(t *testing.T) {
card := h.card(alice, alice, big)
seq := h.press(alice, alice, card, "dl:")
alert := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "larger than your limit of 50.0 MB") || alert.Params["show_alert"] != "true" {
if !strings.Contains(alert.Params["text"], "larger than your limit of 50 MB") || alert.Params["show_alert"] != "true" {
t.Fatalf("alert = %+v", alert.Params)
}
// The card stays usable: the thumbnail-free card still lets the user
@@ -686,7 +791,7 @@ func TestAudioCommandSkipsTheCard(t *testing.T) {
if audio.Files["audio"].Name != "Test Video.mp3" || audio.Params["title"] != "Test Video" || audio.Params["performer"] != "Tester" {
t.Fatalf("sendAudio = %+v files=%+v", audio.Params, audio.Files)
}
h.wait(seq, "editMessageText", textHas("Done"))
h.finished(seq, alice)
if len(h.srv.Calls("sendPhoto")) != 0 {
t.Fatal("/audio must not show a card")
}
@@ -707,7 +812,7 @@ func TestInfoCommandListsFormatsWithoutDownloading(t *testing.T) {
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/info "+link)
info := h.wait(seq, "sendMessage", textHas("Test Video"))
for _, want := range []string{"Best: 10.0 MB", "720p: 10.0 MB", "480p: 5.0 MB", "MP3: 1.0 MB", "Tester"} {
for _, want := range []string{"Best: 10 MB", "720p: 10 MB", "480p: 5 MB", "MP3: 1 MB", "Tester"} {
if !strings.Contains(info.Text(), want) {
t.Errorf("info text lacks %q: %q", want, info.Text())
}
@@ -738,7 +843,7 @@ func TestStartHelpAndHints(t *testing.T) {
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/help")
h.wait(seq, "sendMessage", textHas("Up to 50.0 MB and 10 minutes per download"))
h.wait(seq, "sendMessage", textHas("Up to 50 MB and 10 minutes per download"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "hello bot")
@@ -776,7 +881,7 @@ func TestRestartResumesQueuedJob(t *testing.T) {
if video.ChatID() != alice {
t.Fatalf("sendVideo after restart = %+v", video.Params)
}
h.wait(seq, edits, textHas("Done"))
h.finished(seq, 0)
h.waitJobs(db.JobDone, 1)
}