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:
co-authored by
Claude Opus 5.5
parent
3c153af97f
commit
6843053582
+134
-29
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ func (h *harness) fetch(user int64, url string) fakeserver.Call {
|
||||
card := h.card(user, user, url)
|
||||
seq := h.press(user, user, card, "dl:")
|
||||
video := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == user && !c.Failed })
|
||||
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == user && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seq, user)
|
||||
return video
|
||||
}
|
||||
|
||||
@@ -170,7 +170,7 @@ func TestCacheHitEnforcesSizeLimit(t *testing.T) {
|
||||
// the cache, and he still must not get it.
|
||||
card := h.card(bob, bob, link)
|
||||
seq := h.press(bob, bob, card, "dl:")
|
||||
offer := h.wait(seq, "sendMessage", textHas("larger than your limit of 2.0 MB"))
|
||||
offer := h.wait(seq, "sendMessage", textHas("larger than your limit of 2 MB"))
|
||||
if !strings.Contains(offer.Text(), "You can lift the limit") {
|
||||
t.Fatalf("offer = %q", offer.Text())
|
||||
}
|
||||
@@ -224,7 +224,9 @@ func TestCacheHitCountsAgainstAndIsStoppedByTheDailyQuota(t *testing.T) {
|
||||
t.Fatalf("usage after a cache hit = %+v, want 1 download and its bytes", u)
|
||||
}
|
||||
// Bob's quota is used up. The cached file is refused like a fresh one.
|
||||
card := h.card(bob, bob, link)
|
||||
// (/dl, because a plain link he just got is answered with "already
|
||||
// sent", whose button runs into the same limit.)
|
||||
card := h.card(bob, bob, "/dl "+link)
|
||||
seq := h.press(bob, bob, card, "dl:")
|
||||
alert := h.wait(seq, "answerCallbackQuery", nil)
|
||||
if !strings.Contains(alert.Params["text"], "You used your 1 download for today") {
|
||||
@@ -307,8 +309,8 @@ func TestTwoRequestersShareOneDownload(t *testing.T) {
|
||||
// Everyone is notified on completion: both get the file.
|
||||
toAlice := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice })
|
||||
toGroup := h.wait(seqA, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group })
|
||||
h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") })
|
||||
h.wait(seqA, edits, func(c fakeserver.Call) bool { return c.ChatID() == group && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seqA, alice)
|
||||
h.finished(seqA, group)
|
||||
|
||||
// The file went over the wire once; the second requester got the
|
||||
// file_id of the first upload.
|
||||
@@ -433,7 +435,7 @@ func TestInvalidFileIDFallsBackToTheStoredCopy(t *testing.T) {
|
||||
if !uploaded(healed, "video") || healed.Files["video"].Size != 4096 {
|
||||
t.Fatalf("the fallback must upload the stored copy: %+v %+v", healed.Params, healed.Files)
|
||||
}
|
||||
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seq, bob)
|
||||
if n := len(h.fake.Downloads()); n != 1 {
|
||||
t.Fatalf("yt-dlp ran %d times; the stored copy should have been enough", n)
|
||||
}
|
||||
@@ -472,7 +474,7 @@ func TestInvalidFileIDWithoutStoredCopyDownloadsAgain(t *testing.T) {
|
||||
if !uploaded(fresh, "video") {
|
||||
t.Fatal("the fresh download must be uploaded")
|
||||
}
|
||||
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seq, bob)
|
||||
if n := len(h.fake.Downloads()); n != 2 {
|
||||
t.Fatalf("yt-dlp ran %d times, want 2 (the original and the re-download)", n)
|
||||
}
|
||||
@@ -512,7 +514,7 @@ func TestLowerProfileIsDerivedFromTheStoredCopy(t *testing.T) {
|
||||
if video.Files["video"].Size != 500 || video.Params["height"] != "480" {
|
||||
t.Fatalf("derived video = %+v %+v", video.Params, video.Files)
|
||||
}
|
||||
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == bob && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seq, bob)
|
||||
if trans.calls.Load() != 1 {
|
||||
t.Fatalf("transcoder ran %d times, want 1", trans.calls.Load())
|
||||
}
|
||||
@@ -572,7 +574,7 @@ func TestFreshCommandSkipsTheCacheUnderNormalLimits(t *testing.T) {
|
||||
if !uploaded(video, "video") {
|
||||
t.Fatal("/fresh must download and upload again")
|
||||
}
|
||||
h.wait(seq, edits, textHas("Done"))
|
||||
h.finished(seq, 0)
|
||||
if n := len(h.fake.Downloads()); n != 2 {
|
||||
t.Fatalf("downloads = %d, want 2", n)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
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"])
|
||||
}
|
||||
}
|
||||
@@ -322,10 +322,22 @@ func TestGroupSettingsAreAdminOnly(t *testing.T) {
|
||||
h.srv.PushMessage(group, alice, cmd)
|
||||
h.wait(seq, "sendMessage", textHas("Pass: none"))
|
||||
}
|
||||
// Group commands make no sense in a private chat.
|
||||
// In a private chat /settings is about the person, not a group.
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(alice, alice, "/settings")
|
||||
h.wait(seq, "sendMessage", textHas("works in groups"))
|
||||
own := h.wait(seq, "sendMessage", textHas("Your settings"))
|
||||
if strings.Contains(own.Text(), "Allowed sites") {
|
||||
t.Fatalf("private /settings shows group settings: %q", own.Text())
|
||||
}
|
||||
add, ok := own.Button("")
|
||||
for _, b := range own.Buttons() {
|
||||
if strings.Contains(b.URL, "?startgroup=") {
|
||||
add, ok = b, true
|
||||
}
|
||||
}
|
||||
if !ok || add.URL != "https://t.me/"+fakeserver.BotUsername+"?startgroup=settings" {
|
||||
t.Fatalf("no add-to-group button in %+v", own.Buttons())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminStatusIsVerifiedWithTelegramAndCached(t *testing.T) {
|
||||
@@ -446,7 +458,8 @@ func TestUserDefaultQualityAndLanguageAndStaticPages(t *testing.T) {
|
||||
seq := h.srv.Seq()
|
||||
h.srv.PushMessage(alice, alice, "/quality")
|
||||
menu := h.wait(seq, "sendMessage", textHas("Pick your default format"))
|
||||
if labels(menu) != "✓ Ask every time | Best | 1080p | 720p | 480p | MP3" {
|
||||
// Somebody who never chose gets "best that fits my limit".
|
||||
if labels(menu) != "Ask every time | ✓ Best that fits my limit | Best | 1080p | 720p | 480p | Audio only (MP3)" {
|
||||
t.Fatalf("quality buttons = %q", labels(menu))
|
||||
}
|
||||
seq = h.press(alice, alice, menu, "ql:720")
|
||||
|
||||
@@ -153,7 +153,7 @@ func TestTelegramLanguageIsFollowed(t *testing.T) {
|
||||
h.wait(seq, "sendMessage", textHas("te damos la bienvenida"))
|
||||
|
||||
card := h.card(bob, bob, link, fakeserver.Lang("nl"))
|
||||
if labels := card.Buttons(); labels[0].Text != "Beste · 10,0 MB" || labels[len(labels)-1].Text != "Annuleren" {
|
||||
if labels := card.Buttons(); labels[0].Text != "Beste · 10 MB" || labels[len(labels)-1].Text != "Annuleren" {
|
||||
t.Fatalf("Dutch card buttons = %+v", labels)
|
||||
}
|
||||
// A language without a catalog gets English.
|
||||
@@ -181,7 +181,8 @@ func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) {
|
||||
for _, b := range pick.Buttons() {
|
||||
names = append(names, b.Text)
|
||||
}
|
||||
if strings.Join(names, "|") != "English|Español|Nederlands|Follow my Telegram language" {
|
||||
// The active choice is checked.
|
||||
if strings.Join(names, "|") != "English|Español|Nederlands|✓ Follow my Telegram language" {
|
||||
t.Fatalf("language buttons = %v", names)
|
||||
}
|
||||
seq = h.press(alice, alice, pick, "lg:es")
|
||||
@@ -198,12 +199,19 @@ func TestSwitchingLanguageChangesMessagesButtonsMenusAndApp(t *testing.T) {
|
||||
// Messages and buttons.
|
||||
card := h.card(alice, alice, link)
|
||||
labels := card.Buttons()
|
||||
if labels[0].Text != "Mejor · 10,0 MB" || labels[len(labels)-1].Text != "Cancelar" {
|
||||
if labels[0].Text != "Mejor · 10 MB" || labels[len(labels)-1].Text != "Cancelar" {
|
||||
t.Fatalf("Spanish card buttons = %+v", labels)
|
||||
}
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, "sendVideo", nil)
|
||||
h.wait(seq, edits, textHas("Listo. Que lo disfrutes."))
|
||||
video := h.finished(seq, alice)
|
||||
if !strings.Contains(video.Text(), "vía @") {
|
||||
t.Fatalf("Spanish caption = %q", video.Text())
|
||||
}
|
||||
for _, b := range video.Buttons() {
|
||||
if b.Text == "Delete" || b.Text == "Other quality" {
|
||||
t.Fatalf("English button under a Spanish file: %+v", video.Buttons())
|
||||
}
|
||||
}
|
||||
|
||||
seq = h.srv.Seq()
|
||||
h.srv.PushMessage(alice, alice, "/account")
|
||||
|
||||
@@ -391,7 +391,7 @@ func TestMiniAppHistoryResend(t *testing.T) {
|
||||
if again.Params["video"] == "" || len(again.Files) != 0 {
|
||||
t.Fatalf("the resend should reuse Telegram's copy: params %v, %d uploads", again.Params, len(again.Files))
|
||||
}
|
||||
h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") })
|
||||
h.finished(seq, alice)
|
||||
// One real download happened, and both deliveries count as usage.
|
||||
if n := len(h.fake.Downloads()); n != 1 {
|
||||
t.Fatalf("%d downloads ran, want 1", n)
|
||||
@@ -670,13 +670,24 @@ func TestMiniAppPreferences(t *testing.T) {
|
||||
// A default format has to be a video or audio format.
|
||||
h.refused(h.call(alice, "PUT", "me", map[string]any{"quality": "thumb"}), http.StatusBadRequest, "bad_request")
|
||||
h.refused(h.call(alice, "PUT", "me", map[string]any{"lang": "tlh"}), http.StatusBadRequest, "bad_request")
|
||||
// "" is "ask every time" in the app, as for groups; "fit" is the best
|
||||
// quality that fits the limit, which is also what a new user gets.
|
||||
h.must(alice, "PUT", "me", map[string]any{"quality": ""})
|
||||
|
||||
if me := h.must(alice, "GET", "me", nil); me.str("quality") != "" {
|
||||
t.Fatalf("me after ask = %s", me.Raw)
|
||||
}
|
||||
h.must(alice, "PUT", "me", map[string]any{"lang": "en"})
|
||||
u, err := h.app.Store.GetUser(ctx, alice)
|
||||
if err != nil || u.LangOverride != "en" || u.Quality != "" {
|
||||
if err != nil || u.LangOverride != "en" || u.Quality != "ask" {
|
||||
t.Fatalf("user = %+v, %v", u, err)
|
||||
}
|
||||
h.must(alice, "PUT", "me", map[string]any{"quality": "fit"})
|
||||
if me := h.must(alice, "GET", "me", nil); me.str("quality") != "fit" {
|
||||
t.Fatalf("me after fit = %s", me.Raw)
|
||||
}
|
||||
if me := h.must(bob, "GET", "me", nil); me.str("quality") != "fit" {
|
||||
t.Fatalf("a new user's quality = %s", me.Raw)
|
||||
}
|
||||
h.must(alice, "PUT", "me", map[string]any{"lang": "auto"})
|
||||
if u, _ = h.app.Store.GetUser(ctx, alice); u.LangOverride != "" {
|
||||
t.Fatalf("language override = %q, want none", u.LangOverride)
|
||||
|
||||
+11
-10
@@ -281,7 +281,7 @@ func TestCreditsTopUpAndPayPerDownload(t *testing.T) {
|
||||
card := h.card(alice, alice, bigLink)
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, "sendVideo", nil)
|
||||
h.wait(seq, edits, textHas("Done"))
|
||||
h.finished(seq, 0)
|
||||
if got := h.balance(alice); got != 950 {
|
||||
t.Fatalf("balance = %d, want 950 after one 50 sat download", got)
|
||||
}
|
||||
@@ -383,7 +383,7 @@ func TestOverLimitPayForThisFileOnly(t *testing.T) {
|
||||
card := h.card(alice, alice, bigLink)
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
|
||||
if !strings.Contains(offer.Text(), "larger than your limit of 50.0 MB") {
|
||||
if !strings.Contains(offer.Text(), "larger than your limit of 50 MB") {
|
||||
t.Fatalf("offer text = %q", offer.Text())
|
||||
}
|
||||
// 80 MB is one started 100 MB step: 100 base + 50.
|
||||
@@ -410,10 +410,11 @@ func TestOverLimitPayForThisFileOnly(t *testing.T) {
|
||||
if video.Files["video"].Size != 4096 {
|
||||
t.Fatalf("video = %+v", video.Files)
|
||||
}
|
||||
// The original card became the status message.
|
||||
done := h.wait(seq, edits, textHas("Done"))
|
||||
if done.MessageID != card.MessageID {
|
||||
t.Fatalf("status went to message %d, want the card %d", done.MessageID, card.MessageID)
|
||||
// The original card became the status message, and made way for the
|
||||
// file.
|
||||
file := h.finished(seq, 0)
|
||||
if gone := h.wait(file.Seq, "deleteMessage", nil); gone.MessageID != card.MessageID {
|
||||
t.Fatalf("deleted message %d, want the card %d", gone.MessageID, card.MessageID)
|
||||
}
|
||||
sent := h.waitSent(alice, 1)
|
||||
if sent[0].Source != "one_off" || sent[0].ChargeSats != 150 {
|
||||
@@ -689,7 +690,7 @@ func TestDailyQuota(t *testing.T) {
|
||||
for i := 0; i < 2; i++ {
|
||||
card := h.card(alice, alice, fmt.Sprintf("https://example.com/ok%d", i))
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, edits, textHas("Done"))
|
||||
h.finished(seq, 0)
|
||||
}
|
||||
card = h.card(alice, alice, "https://example.com/third")
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
@@ -704,7 +705,7 @@ func TestDailyQuota(t *testing.T) {
|
||||
// Another user has their own quota.
|
||||
card = h.card(bob, bob, "https://example.com/bob")
|
||||
seq = h.press(bob, bob, card, "dl:")
|
||||
h.wait(seq, edits, textHas("Done"))
|
||||
h.finished(seq, 0)
|
||||
}
|
||||
|
||||
func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) {
|
||||
@@ -714,12 +715,12 @@ func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) {
|
||||
}
|
||||
card := h.card(alice, alice, link)
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, edits, textHas("Done")) // 3 MB delivered, cap is 2 MB
|
||||
h.finished(seq, 0) // 3 MB delivered, cap is 2 MB
|
||||
|
||||
card = h.card(alice, alice, "https://example.com/more")
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
alert := h.wait(seq, "answerCallbackQuery", nil)
|
||||
if !strings.Contains(alert.Params["text"], "daily volume of 2.0 MB") {
|
||||
if !strings.Contains(alert.Params["text"], "daily volume of 2 MB") {
|
||||
t.Fatalf("alert = %q", alert.Params["text"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,11 +103,9 @@ func TestJobWidgetEndsWithTheFile(t *testing.T) {
|
||||
card := h.card(alice, alice, link)
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
sent := h.wait(seq, "sendWidget", nil)
|
||||
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice && !c.Failed })
|
||||
h.wait(seq, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool {
|
||||
return s.Kind == "end" && s.Message == "Done. Enjoy."
|
||||
}))
|
||||
// The file replies to the link, like without widgets.
|
||||
file := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice && !c.Failed })
|
||||
// Once the file is there, the widget goes like any status message.
|
||||
h.wait(file.Seq, "deleteMessage", func(c fakeserver.Call) bool { return c.MessageID == sent.MessageID })
|
||||
h.waitJobs(db.JobDone, 1)
|
||||
if n := len(h.srv.Calls("sendWidget")); n != 1 {
|
||||
t.Fatalf("%d widgets for one download", n)
|
||||
@@ -129,15 +127,18 @@ func TestJobCardFallsBackWhenSendWidgetFails(t *testing.T) {
|
||||
t.Fatal("the scripted failure did not happen")
|
||||
}
|
||||
// The ordinary card carries on as if widgets did not exist.
|
||||
h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice })
|
||||
done := h.wait(seq, "editMessageCaption", textHas("Done"))
|
||||
if done.MessageID != card.MessageID {
|
||||
t.Fatalf("the status went to message %d, the card is %d", done.MessageID, card.MessageID)
|
||||
h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool { return c.MessageID == card.MessageID })
|
||||
file := h.finished(seq, alice)
|
||||
if gone := h.wait(file.Seq, "deleteMessage", nil); gone.MessageID != card.MessageID {
|
||||
t.Fatalf("deleted message %d, the card is %d", gone.MessageID, card.MessageID)
|
||||
}
|
||||
if n := len(h.srv.Calls("sendWidget")); n != 1 {
|
||||
t.Fatalf("sendWidget was tried %d times for one download", n)
|
||||
}
|
||||
h.never(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == itoaInt(card.MessageID) })
|
||||
// The card is the status until the file is there.
|
||||
h.never(seq, "deleteMessage", func(c fakeserver.Call) bool {
|
||||
return c.Params["message_id"] == itoaInt(card.MessageID) && c.Seq < file.Seq
|
||||
})
|
||||
if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="fallback",widget="status"} 1`) {
|
||||
t.Fatal("the fallback was not counted")
|
||||
}
|
||||
@@ -156,10 +157,10 @@ func TestWidgetsPauseWhenTheServerHasNone(t *testing.T) {
|
||||
h.srv.FailNext("sendWidget", 404, "Not Found: method not found")
|
||||
card := h.card(alice, alice, link)
|
||||
seq := h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, "editMessageCaption", textHas("Done"))
|
||||
h.finished(seq, alice)
|
||||
card = h.card(alice, alice, "https://example.com/second")
|
||||
seq = h.press(alice, alice, card, "dl:")
|
||||
h.wait(seq, "editMessageCaption", textHas("Done"))
|
||||
h.finished(seq, alice)
|
||||
if n := len(h.srv.Calls("sendWidget")); n != 1 {
|
||||
t.Fatalf("sendWidget tried %d times after the server said it has no such method", n)
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ func TestRemoteWorkerDoesEverythingOverHTTP(t *testing.T) {
|
||||
if video.Files["video"].Size != 5000 {
|
||||
t.Fatalf("the file that went through the worker upload is wrong: %+v", video.Files)
|
||||
}
|
||||
f.wait(seq, edits, textHas("Done"))
|
||||
f.finished(seq, 0)
|
||||
job := f.jobOf(db.JobDone)
|
||||
if job.WorkerID != "w1" || job.Attempts != 1 {
|
||||
t.Fatalf("job worker=%q attempts=%d", job.WorkerID, job.Attempts)
|
||||
@@ -236,7 +236,7 @@ func TestKilledWorkerJobIsRequeuedAndFinishedByTheOther(t *testing.T) {
|
||||
if video.Files["video"].Size != 7777 {
|
||||
t.Fatalf("the delivered file did not come from the second worker: %+v", video.Files)
|
||||
}
|
||||
f.wait(seq, edits, textHas("Done"))
|
||||
f.finished(seq, 0)
|
||||
done := f.jobOf(db.JobDone)
|
||||
if done.ID != running.ID || done.WorkerID != "w2" || done.Attempts != 2 {
|
||||
t.Fatalf("job id=%s worker=%q attempts=%d, want the same job finished by w2 on attempt 2",
|
||||
@@ -325,7 +325,7 @@ func TestDrainAndWorkersCommands(t *testing.T) {
|
||||
for i := 0; i < 3; i++ {
|
||||
card := f.card(bob, bob, fmt.Sprintf("https://example.com/d%d", i))
|
||||
seq := f.press(bob, bob, card, "dl:")
|
||||
f.wait(seq, edits, textHas("Done"))
|
||||
f.finished(seq, 0)
|
||||
}
|
||||
if n := len(w1.fake.Downloads()); n != 0 {
|
||||
t.Fatalf("a draining worker took %d jobs", n)
|
||||
|
||||
Reference in New Issue
Block a user