package app_test import ( "encoding/base64" "encoding/json" "io" "net/http" "strconv" "strings" "testing" "time" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/tg/fakeserver" "github.com/noderunners/dlbot/internal/widget" "github.com/noderunners/dlbot/internal/ytdlp" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) func withWidgets(c *config.Config) { c.Telegram.Widgets = true } func jobStateOf(t *testing.T, c fakeserver.Call) widget.Job { t.Helper() var s widget.Job if err := json.Unmarshal([]byte(c.Params["chat_data"]), &s); err != nil { t.Fatalf("chat_data %q: %v", c.Params["chat_data"], err) } return s } func isWidgetEdit(msgID int, pred func(widget.Job) bool) func(fakeserver.Call) bool { return func(c fakeserver.Call) bool { if c.MessageID != msgID { return false } var s widget.Job return json.Unmarshal([]byte(c.Params["chat_data"]), &s) == nil && pred(s) } } // --- acceptance: the live job card ----------------------------------------- func TestJobWidgetShowsProgressAndCancels(t *testing.T) { block := make(chan struct{}) defer close(block) h := start(t, &ytdlptest.Fake{Block: block, FileSize: 4000}, withWidgets) card := h.card(alice, alice, link) seq := h.press(alice, alice, card, "dl:") sent := h.wait(seq, "sendWidget", nil) if sent.ChatID() != alice || sent.Params["html"] != widget.JobHTML() || sent.Params["allow_queries"] != "true" { t.Fatalf("sendWidget = %+v", sent.Params) } if !strings.Contains(sent.Params["caption"], "Test Video") { t.Fatalf("widget caption = %q", sent.Params["caption"]) } first := jobStateOf(t, sent) if first.Cancel != "Cancel" || first.Message == "" { t.Fatalf("first state = %+v", first) } // The card made way for the widget. h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool { return c.Params["message_id"] == itoaInt(card.MessageID) }) // Progress arrives as widget state, not as message edits. h.waitJobs(db.JobRunning, 1) running := h.wait(seq, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool { return s.Kind == "running" && s.Message == "Downloading…" })) if s := jobStateOf(t, running); s.Progress < 0 && s.Detail == "" { // The scripted download reports half of its size. t.Logf("state without numbers yet: %+v", s) } h.never(seq, "editMessageCaption", func(c fakeserver.Call) bool { return strings.Contains(c.Text(), "Downloading") }) // Somebody else's request is refused. q := h.srv.Seq() h.srv.PushWidgetQuery(alice, bob, sent.MessageID, "cx") h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return strings.Contains(c.Params["data"], "belong to the person") }) if len(h.jobs(db.JobRunning)) != 1 { t.Fatal("a stranger's request cancelled the download") } // The widget's Cancel button. q = h.srv.Seq() h.srv.PushWidgetQuery(alice, alice, sent.MessageID, "cx") h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return c.Params["data"] == "Cancelled." }) end := h.wait(q, "editMessageWidgetData", isWidgetEdit(sent.MessageID, func(s widget.Job) bool { return s.Kind == "end" })) if s := jobStateOf(t, end); s.Message != "Cancelled." || s.Cancel != "" { t.Fatalf("final state = %+v", s) } h.waitJobs(db.JobCancelled, 1) h.never(seq, "sendVideo", nil) // Unknown requests get an empty answer, as the widget expects one. q = h.srv.Seq() h.srv.PushWidgetQuery(alice, alice, sent.MessageID, "nonsense") h.wait(q, "answerWidgetQuery", func(c fakeserver.Call) bool { return c.Params["data"] == "" }) } func TestJobWidgetEndsWithTheFile(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 4000, Delay: 300 * time.Millisecond}, withWidgets) 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. h.waitJobs(db.JobDone, 1) if n := len(h.srv.Calls("sendWidget")); n != 1 { t.Fatalf("%d widgets for one download", n) } if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="sent",widget="job"} 1`) { t.Fatal("the widget was not counted") } } // --- acceptance: fallback when sendWidget fails ----------------------------- func TestJobCardFallsBackWhenSendWidgetFails(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 4000, Delay: 200 * time.Millisecond}, withWidgets) h.srv.FailNext("sendWidget", 400, "Bad Request: WIDGET_NOT_ALLOWED") card := h.card(alice, alice, link) seq := h.press(alice, alice, card, "dl:") failed := h.wait(seq, "sendWidget", nil) if !failed.Failed { 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) } 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) }) if body := scrapeMetrics(t, h); !strings.Contains(body, `dlbot_widgets_total{outcome="fallback",widget="status"} 1`) { t.Fatal("the fallback was not counted") } // The next download tries again: one failure is not a pattern. card = h.card(alice, alice, "https://example.com/second") seq = h.press(alice, alice, card, "dl:") if c := h.wait(seq, "sendWidget", nil); c.Failed { t.Fatal("the second widget failed too") } } func TestWidgetsPauseWhenTheServerHasNone(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 4000}, withWidgets) // What an older Bot API server answers for an unknown method. 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")) card = h.card(alice, alice, "https://example.com/second") seq = h.press(alice, alice, card, "dl:") h.wait(seq, "editMessageCaption", textHas("Done")) 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) } } func TestGroupsGetNoWidgets(t *testing.T) { h := start(t, &ytdlptest.Fake{FileSize: 4000}, withWidgets) card := h.card(group, alice, "/dl "+link) seq := h.press(group, alice, card, "dl:") h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == group }) if n := len(h.srv.Calls("sendWidget")); n != 0 { t.Fatalf("%d widgets sent to a group; Telegram allows them in private chats only", n) } } // --- acceptance: the live invoice ------------------------------------------ func TestInvoiceWidgetCountsDownAndShowsPaid(t *testing.T) { h := startMoney(t, nil, withWidgets) seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/buy") menu := h.wait(seq, "sendMessage", textHas("Passes and credits")) seq = h.press(alice, alice, menu, "by:pass_day") inv, ok := h.ln.WaitInvoice(1, 5*time.Second) if !ok { t.Fatal("no invoice") } sent := h.wait(seq, "sendWidget", nil) if sent.Params["html"] != widget.InvoiceHTML() || !strings.Contains(sent.Params["caption"], inv.Bolt11) { t.Fatalf("invoice widget = %+v", sent.Params) } var info widget.InvoiceInfo if err := json.Unmarshal([]byte(sent.Params["public_data"]), &info); err != nil { t.Fatal(err) } if info.Amount != "700 sats" || info.Title != "Day pass" || !strings.Contains(info.Waiting, "{T}") || info.Expires < time.Now().Unix() { t.Fatalf("invoice info = %+v", info) } if bits, err := base64.StdEncoding.DecodeString(info.QR); err != nil || info.N < 21 || len(bits) != (info.N*info.N+7)/8 { t.Fatalf("QR: %d modules, %d bytes, %v", info.N, len(bits), err) } // The usual buttons stay under it, for apps without widgets. if !strings.Contains(labels(sent), "Check payment") { t.Fatalf("buttons = %q", labels(sent)) } h.waitInvoiceSaved(inv) h.pay(inv) paid := h.wait(seq, "editMessageWidgetData", func(c fakeserver.Call) bool { var s widget.InvoiceState return c.MessageID == sent.MessageID && json.Unmarshal([]byte(c.Params["chat_data"]), &s) == nil && s.Status == "paid" }) var st widget.InvoiceState _ = json.Unmarshal([]byte(paid.Params["chat_data"]), &st) if !strings.HasPrefix(st.Message, "Paid.") { t.Fatalf("paid state = %+v", st) } h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool { return c.MessageID == sent.MessageID && strings.Contains(c.Text(), "Paid.") && len(c.Buttons()) == 0 }) h.booksBalance() } func TestInvoiceFallsBackWhenSendWidgetFails(t *testing.T) { h := startMoney(t, nil, withWidgets) h.srv.FailNext("sendWidget", 400, "Bad Request: INPUT_MEDIA_WIDGET_TOO_LARGE") seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/buy") menu := h.wait(seq, "sendMessage", textHas("Passes and credits")) seq = h.press(alice, alice, menu, "by:pass_day") inv, photo := h.invoice(seq, 1) if photo.Method != "sendPhoto" || photo.Files["photo"].Size == 0 { t.Fatalf("fallback invoice = %s %+v", photo.Method, photo.Params) } h.waitInvoiceSaved(inv) h.pay(inv) h.wait(seq, "editMessageCaption", func(c fakeserver.Call) bool { return c.MessageID == photo.MessageID && strings.Contains(c.Text(), "Paid.") }) } // --- metrics ----------------------------------------------------------------- func scrapeMetrics(t *testing.T, h *harness) string { t.Helper() res, err := http.Get("http://" + h.app.HTTP.Addr() + "/metrics") if err != nil { t.Fatal(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) if res.StatusCode != 200 { t.Fatalf("/metrics = %d", res.StatusCode) } return string(body) } func TestMetricsEndpoint(t *testing.T) { h := startMoney(t, &ytdlptest.Fake{FileSize: 3000}, nil) h.fetch(alice, link) h.fetch(bob, link) // the same video: a cache hit // A failure on a site of its own. h.fake.DownloadErrs = map[string][]error{"https://broken.example.org/v": {errPrivate()}} card := h.card(alice, alice, "https://broken.example.org/v") seq := h.press(alice, alice, card, "dl:") h.wait(seq, edits, textHas("That did not work")) seq = h.srv.Seq() h.srv.PushMessage(alice, alice, "/buy") menu := h.wait(seq, "sendMessage", textHas("Passes and credits")) h.press(alice, alice, menu, "by:pass_day") h.ln.WaitInvoice(1, 5*time.Second) // Events are counted by the bot's event loop, which can run a moment // after the user already saw the outcome. var body string for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(50 * time.Millisecond) { body = scrapeMetrics(t, h.harness) if strings.Contains(body, `outcome="failed"} 1`) && strings.Contains(body, "dlbot_queue_wait_seconds_count 2") || time.Now().After(deadline) { break } } if testing.Verbose() { for _, l := range strings.Split(body, "\n") { if strings.HasPrefix(l, "dlbot_") { t.Log(l) } } } for _, want := range []string{ `dlbot_queue_jobs{lane="free"} 0`, `dlbot_queue_jobs{lane="paid"} 0`, "dlbot_queue_oldest_wait_seconds 0", "dlbot_jobs_running 0", "dlbot_worker_slots ", "dlbot_cache_hits_total 1", "dlbot_cache_bytes_saved_total 3000", `dlbot_deliveries_total{via="cache"} 1`, `dlbot_deliveries_total{via="upload"} 1`, // The cache hit is a job of its own, finished without a worker. `dlbot_jobs_finished_total{lane="free",outcome="done"} 2`, `dlbot_jobs_finished_total{lane="free",outcome="failed"} 1`, `dlbot_download_errors_total{code="private",site="broken.example.org"} 1`, "dlbot_invoices_created_total 1", "dlbot_invoices_settled_total 0", "dlbot_lightning_up 1", "dlbot_queue_wait_seconds_count 2", `dlbot_updates_total{type="message"}`, `dlbot_updates_total{type="callback_query"}`, "go_goroutines", } { if !strings.Contains(body, want) { t.Errorf("/metrics lacks %q", want) } } // Nothing about users, links or tokens. for _, bad := range []string{"example.com/watch", fakeserver.Token, "chat_id", "Test Video"} { if strings.Contains(body, bad) { t.Errorf("/metrics shows %q", bad) } } } func TestMetricsCanBeTurnedOff(t *testing.T) { h := start(t, nil, func(c *config.Config) { c.HTTP.Metrics = false }) res, err := http.Get("http://" + h.app.HTTP.Addr() + "/metrics") if err != nil { t.Fatal(err) } res.Body.Close() if res.StatusCode != http.StatusNotFound { t.Fatalf("/metrics with METRICS_ENABLED=false = %d", res.StatusCode) } } func itoaInt(n int) string { return strconv.Itoa(n) } func errPrivate() error { return &ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private"} }