Link in, card, download, send, in private chats and groups. - cmd/core with an embedded download worker - Telegram front end on telego v1.13.0 (Bot API 10.4): link card with thumbnail and format buttons, one live status message, /dl /audio /thumb /info /queue /cancel, group support with requester-only buttons - Database backed queue: paid and free lanes, leases with heartbeats, one automatic retry, cancel, queue position and wait estimate - yt-dlp and ffprobe behind a Runner interface with classified, redacted errors mapped to friendly messages - SQLite via modernc with goose migrations, portable schema - Local file storage behind a Storage interface - go-i18n with an English catalog, no literal text in handlers - Free tier limits enforced before queueing and again on the real file - Bot token and webhook secret are stripped from all log output - Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end flows against a fake Bot API server; opt-in test with the real yt-dlp Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
812 lines
27 KiB
Go
812 lines
27 KiB
Go
package app_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/noderunners/dlbot/internal/app"
|
|
"github.com/noderunners/dlbot/internal/bot"
|
|
"github.com/noderunners/dlbot/internal/config"
|
|
"github.com/noderunners/dlbot/internal/db"
|
|
"github.com/noderunners/dlbot/internal/storage"
|
|
"github.com/noderunners/dlbot/internal/tg/fakeserver"
|
|
"github.com/noderunners/dlbot/internal/ytdlp"
|
|
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
|
|
)
|
|
|
|
// harness runs the real core against a fake Bot API and a scripted yt-dlp.
|
|
type harness struct {
|
|
t *testing.T
|
|
srv *fakeserver.Server
|
|
fake *ytdlptest.Fake
|
|
runner ytdlp.Runner
|
|
app *app.App
|
|
cfg config.Config
|
|
cancel context.CancelFunc
|
|
done chan error
|
|
}
|
|
|
|
const (
|
|
alice = int64(42)
|
|
bob = int64(43)
|
|
group = int64(-1001234567890)
|
|
link = "https://example.com/watch?v=1"
|
|
)
|
|
|
|
func start(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *harness {
|
|
t.Helper()
|
|
if fake == nil {
|
|
fake = &ytdlptest.Fake{}
|
|
}
|
|
h := startWithRunner(t, fake, mut)
|
|
h.fake = fake
|
|
return h
|
|
}
|
|
|
|
func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)) *harness {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
srv := fakeserver.New()
|
|
cfg := config.Default()
|
|
cfg.Telegram.Token = fakeserver.Token
|
|
cfg.Telegram.APIURL = srv.URL()
|
|
cfg.HTTP.Listen = "127.0.0.1:0"
|
|
cfg.Database.DSN = filepath.Join(dir, "bot.db")
|
|
cfg.Storage.LocalDir = filepath.Join(dir, "files")
|
|
cfg.Worker.TempDir = filepath.Join(dir, "tmp")
|
|
cfg.Queue.Lease = config.Duration(2 * time.Second)
|
|
cfg.Queue.Heartbeat = config.Duration(40 * time.Millisecond)
|
|
if mut != nil {
|
|
mut(&cfg)
|
|
}
|
|
h := &harness{t: t, srv: srv, runner: runner, cfg: cfg}
|
|
h.boot()
|
|
t.Cleanup(func() {
|
|
h.stop()
|
|
srv.Close()
|
|
})
|
|
return h
|
|
}
|
|
|
|
// boot starts (or restarts) the core on the same database and storage.
|
|
func (h *harness) boot() {
|
|
h.t.Helper()
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
a, err := app.New(ctx, app.Options{
|
|
Config: h.cfg,
|
|
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
|
Runner: h.runner,
|
|
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
|
|
})
|
|
if err != nil {
|
|
cancel()
|
|
h.t.Fatalf("app.New: %v", err)
|
|
}
|
|
h.app, h.cancel, h.done = a, cancel, make(chan error, 1)
|
|
go func() { h.done <- a.Run(ctx) }()
|
|
select {
|
|
case <-a.Ready():
|
|
case err := <-h.done:
|
|
h.t.Fatalf("app.Run stopped during startup: %v", err)
|
|
case <-time.After(10 * time.Second):
|
|
h.t.Fatal("the core did not become ready")
|
|
}
|
|
}
|
|
|
|
func (h *harness) stop() {
|
|
if h.cancel == nil {
|
|
return
|
|
}
|
|
h.cancel()
|
|
h.cancel = nil
|
|
select {
|
|
case err := <-h.done:
|
|
if err != nil {
|
|
h.t.Errorf("app.Run: %v", err)
|
|
}
|
|
case <-time.After(15 * time.Second):
|
|
h.t.Error("the core did not shut down")
|
|
}
|
|
}
|
|
|
|
// wait blocks until the bot makes a matching call after sequence "after".
|
|
func (h *harness) wait(after int, method string, match func(fakeserver.Call) bool) fakeserver.Call {
|
|
h.t.Helper()
|
|
c, ok := h.srv.WaitFor(after, 10*time.Second, method, match)
|
|
if !ok {
|
|
var sb strings.Builder
|
|
for _, c := range h.srv.Calls("") {
|
|
if c.Seq > after {
|
|
fmt.Fprintf(&sb, "\n #%d %s chat=%s text=%q", c.Seq, c.Method, c.Params["chat_id"], c.Text())
|
|
}
|
|
}
|
|
h.t.Fatalf("no %s call matched. Calls since #%d:%s", method, after, sb.String())
|
|
}
|
|
return c
|
|
}
|
|
|
|
// never asserts that no matching call shows up for a short while.
|
|
func (h *harness) never(after int, method string, match func(fakeserver.Call) bool) {
|
|
h.t.Helper()
|
|
if c, ok := h.srv.WaitFor(after, 400*time.Millisecond, method, match); ok {
|
|
h.t.Fatalf("unexpected %s call: %+v", method, c.Params)
|
|
}
|
|
}
|
|
|
|
func textHas(sub string) func(fakeserver.Call) bool {
|
|
return func(c fakeserver.Call) bool { return strings.Contains(c.Text(), sub) }
|
|
}
|
|
|
|
func textIs(want string) func(fakeserver.Call) bool {
|
|
return func(c fakeserver.Call) bool { return c.Text() == want }
|
|
}
|
|
|
|
const edits = "editMessageText|editMessageCaption"
|
|
|
|
// card sends a link and returns the card call.
|
|
func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) fakeserver.Call {
|
|
h.t.Helper()
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(chat, user, text, opts...)
|
|
return h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool {
|
|
_, ok := c.Button("dl:")
|
|
return ok
|
|
})
|
|
}
|
|
|
|
func (h *harness) press(chat, user int64, card fakeserver.Call, prefix string) (seq int) {
|
|
h.t.Helper()
|
|
btn, ok := card.Button(prefix)
|
|
if !ok {
|
|
h.t.Fatalf("no button starting with %q in %+v", prefix, card.Buttons())
|
|
}
|
|
seq = h.srv.Seq()
|
|
h.srv.PushCallback(chat, user, card.MessageID, btn.Data)
|
|
return seq
|
|
}
|
|
|
|
func replyTarget(c fakeserver.Call) int {
|
|
var rp struct {
|
|
MessageID int `json:"message_id"`
|
|
}
|
|
_ = json.Unmarshal([]byte(c.Params["reply_parameters"]), &rp)
|
|
return rp.MessageID
|
|
}
|
|
|
|
func (h *harness) jobs(status string) []*db.Job {
|
|
h.t.Helper()
|
|
js, err := h.app.Store.JobsByStatus(context.Background(), status, 100)
|
|
if err != nil {
|
|
h.t.Fatal(err)
|
|
}
|
|
return js
|
|
}
|
|
|
|
func (h *harness) waitJobs(status string, n int) []*db.Job {
|
|
h.t.Helper()
|
|
deadline := time.Now().Add(10 * time.Second)
|
|
for {
|
|
js := h.jobs(status)
|
|
if len(js) == n {
|
|
return js
|
|
}
|
|
if time.Now().After(deadline) {
|
|
h.t.Fatalf("%d jobs in %s, want %d", len(js), status, n)
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
func (h *harness) storedFiles() int {
|
|
n := 0
|
|
_ = h.app.Storage.List(context.Background(), "", func(storage.Object) error { n++; return nil })
|
|
return n
|
|
}
|
|
|
|
// --- acceptance: pasting a link returns the file ---------------------------
|
|
|
|
func TestPrivateLinkReturnsFile(t *testing.T) {
|
|
h := start(t, &ytdlptest.Fake{FileSize: 4096}, nil)
|
|
seq := h.srv.Seq()
|
|
msgID := h.srv.PushMessage(alice, alice, "look at this "+link)
|
|
|
|
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())
|
|
}
|
|
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")
|
|
}
|
|
var labels []string
|
|
for _, b := range card.Buttons() {
|
|
labels = append(labels, b.Text)
|
|
// Callback data carries identifiers only, never translated text.
|
|
if strings.ContainsAny(b.Data, " ") || len(b.Data) > 64 {
|
|
t.Errorf("bad callback data %q", b.Data)
|
|
}
|
|
}
|
|
want := []string{"Best · 10.0 MB", "480p · 5.0 MB", "MP3 · 1.0 MB", "Thumbnail", "Cancel"}
|
|
if strings.Join(labels, "|") != strings.Join(want, "|") {
|
|
t.Fatalf("buttons = %v, want %v", labels, want)
|
|
}
|
|
// The placeholder is replaced by the photo card.
|
|
h.wait(seq, "deleteMessage", nil)
|
|
|
|
seq = h.press(alice, alice, card, "dl:")
|
|
h.wait(seq, "answerCallbackQuery", nil)
|
|
video := h.wait(seq, "sendVideo", nil)
|
|
if video.ChatID() != alice || video.Files["video"].Size != 4096 {
|
|
t.Fatalf("sendVideo = %+v files=%+v", video.Params, video.Files)
|
|
}
|
|
if video.Files["video"].Name != "Test Video.mp4" {
|
|
t.Fatalf("file name = %q", video.Files["video"].Name)
|
|
}
|
|
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")
|
|
}
|
|
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)
|
|
}
|
|
|
|
h.waitJobs(db.JobDone, 1)
|
|
if n := h.storedFiles(); n != 0 {
|
|
t.Fatalf("%d files left in storage after delivery", n)
|
|
}
|
|
if n := len(h.fake.Probes()); n != 1 {
|
|
t.Fatalf("probes = %d, want 1", n)
|
|
}
|
|
}
|
|
|
|
func TestStatusGoesThroughDownloadingAndUploading(t *testing.T) {
|
|
block := make(chan struct{})
|
|
h := start(t, &ytdlptest.Fake{Block: block, FileSize: 2000}, nil)
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
|
|
// The fake reports half of the file before it blocks.
|
|
down := h.wait(seq, edits, textHas("50%"))
|
|
if !strings.Contains(down.Text(), "Downloading") || !strings.Contains(down.Text(), "▰▰▰▰▰▱▱▱▱▱") ||
|
|
!strings.Contains(down.Text(), "1,000 B of 2 KB") {
|
|
t.Fatalf("progress text = %q", down.Text())
|
|
}
|
|
if _, ok := down.Button("jc:"); !ok {
|
|
t.Fatal("a running job must offer Cancel")
|
|
}
|
|
close(block)
|
|
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"))
|
|
}
|
|
|
|
// --- acceptance: groups work with /dl --------------------------------------
|
|
|
|
func TestGroupDlCommand(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
cmdID := h.srv.PushMessage(group, alice, "/dl@"+fakeserver.BotUsername+" "+link)
|
|
card := h.wait(seq, "sendPhoto", nil)
|
|
if card.ChatID() != group || replyTarget(card) != cmdID {
|
|
t.Fatalf("the card must reply to the command in the group: %+v", card.Params)
|
|
}
|
|
|
|
// Somebody else presses a button: a short notice, no job.
|
|
seq = h.press(group, bob, card, "dl:")
|
|
notice := h.wait(seq, "answerCallbackQuery", nil)
|
|
if !strings.Contains(notice.Params["text"], "belong to the person who asked") {
|
|
t.Fatalf("notice = %q", notice.Params["text"])
|
|
}
|
|
h.never(seq, "sendVideo", nil)
|
|
if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)); n != 0 {
|
|
t.Fatalf("a stranger's press created %d jobs", n)
|
|
}
|
|
// The stranger cannot dismiss the card either.
|
|
seq = h.press(group, bob, card, "cx:")
|
|
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
|
|
return strings.Contains(c.Params["text"], "belong to the person who asked")
|
|
})
|
|
h.never(seq, "deleteMessage", nil)
|
|
|
|
seq = h.press(group, alice, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480")
|
|
video := h.wait(seq, "sendVideo", nil)
|
|
if video.ChatID() != group || replyTarget(video) != cmdID {
|
|
t.Fatalf("the file must reply to the original message: %+v", video.Params)
|
|
}
|
|
if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "480" {
|
|
t.Fatalf("downloads = %+v", dl)
|
|
}
|
|
}
|
|
|
|
func TestGroupReplyDlUsesTheRepliedMessage(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(group, alice, "/dl", fakeserver.ReplyTo(555, "watch "+link+" tonight"))
|
|
card := h.wait(seq, "sendPhoto", nil)
|
|
if replyTarget(card) != 555 {
|
|
t.Fatalf("card replies to %d, want the message with the link (555)", replyTarget(card))
|
|
}
|
|
if got := h.fake.Probes(); len(got) != 1 || got[0] != link {
|
|
t.Fatalf("probed %v", got)
|
|
}
|
|
}
|
|
|
|
func TestGroupIgnoresPlainLinksAndForeignCommands(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(group, alice, "check "+link)
|
|
h.srv.PushMessage(group, alice, "/dl@some_other_bot "+link)
|
|
h.srv.PushMessage(group, alice, "/unknowncommand")
|
|
h.never(seq, "", nil)
|
|
if n := len(h.fake.Probes()); n != 0 {
|
|
t.Fatalf("probes = %d, want 0", n)
|
|
}
|
|
// /dl without a link explains itself.
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(group, alice, "/dl")
|
|
h.wait(seq, "sendMessage", textHas("Add a link after the command"))
|
|
}
|
|
|
|
// --- acceptance: cancel works ----------------------------------------------
|
|
|
|
func TestCancelCardBeforeChoosing(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "cx:")
|
|
h.wait(seq, "answerCallbackQuery", textIs("Cancelled."))
|
|
h.wait(0, "deleteMessage", func(c fakeserver.Call) bool {
|
|
return c.Params["message_id"] == fmt.Sprint(card.MessageID)
|
|
})
|
|
// The card is dead: its format buttons no longer start anything.
|
|
seq = h.press(alice, alice, card, "dl:")
|
|
h.wait(seq, "answerCallbackQuery", nil)
|
|
h.never(seq, "sendVideo", nil)
|
|
}
|
|
|
|
func TestCancelRunningJob(t *testing.T) {
|
|
block := make(chan struct{})
|
|
defer close(block)
|
|
h := start(t, &ytdlptest.Fake{Block: block}, nil)
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
status := h.wait(seq, edits, textHas("Downloading"))
|
|
|
|
// Bob cannot cancel Alice's download.
|
|
seq = h.press(alice, bob, status, "jc:")
|
|
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
|
|
return strings.Contains(c.Params["text"], "belong to the person who asked")
|
|
})
|
|
if len(h.jobs(db.JobRunning)) != 1 {
|
|
t.Fatal("the job must keep running")
|
|
}
|
|
|
|
seq = h.press(alice, alice, status, "jc:")
|
|
cancelled := h.wait(seq, edits, textHas("Cancelled"))
|
|
if len(cancelled.Buttons()) != 0 {
|
|
t.Fatal("a cancelled status must have no buttons")
|
|
}
|
|
h.waitJobs(db.JobCancelled, 1)
|
|
h.never(seq, "sendVideo", nil)
|
|
if n := h.storedFiles(); n != 0 {
|
|
t.Fatalf("%d files left in storage after cancel", n)
|
|
}
|
|
}
|
|
|
|
func TestCancelCommandCancelsQueuedAndRunning(t *testing.T) {
|
|
block := make(chan struct{})
|
|
defer close(block)
|
|
h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) {
|
|
c.Worker.Concurrency = 1
|
|
c.Limits.Free.ActiveJobs = 3
|
|
})
|
|
for i := 0; i < 2; i++ {
|
|
card := h.card(alice, alice, fmt.Sprintf("https://example.com/v%d", i))
|
|
h.press(alice, alice, card, "dl:")
|
|
}
|
|
h.waitJobs(db.JobRunning, 1)
|
|
h.waitJobs(db.JobQueued, 1)
|
|
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/queue")
|
|
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool {
|
|
return strings.Contains(c.Text(), "2 downloads in progress") && strings.Contains(c.Text(), "In the queue. Position 1")
|
|
})
|
|
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/cancel")
|
|
h.wait(seq, "sendMessage", textHas("Cancelled 2 downloads."))
|
|
h.waitJobs(db.JobCancelled, 2)
|
|
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/cancel")
|
|
h.wait(seq, "sendMessage", textHas("nothing to cancel"))
|
|
}
|
|
|
|
// --- failures --------------------------------------------------------------
|
|
|
|
func TestDownloadFailureShowsFriendlyError(t *testing.T) {
|
|
raw := "ERROR: [youtube] abc: Private video. token=SECRET"
|
|
h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
|
|
link: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: raw}},
|
|
}}, nil)
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
failed := h.wait(seq, edits, textHas("That did not work"))
|
|
if !strings.Contains(failed.Text(), "private or for members only") {
|
|
t.Fatalf("failure text = %q", failed.Text())
|
|
}
|
|
for _, c := range h.srv.Calls("") {
|
|
if strings.Contains(c.Text(), "SECRET") || strings.Contains(c.Text(), "ERROR:") {
|
|
t.Fatalf("raw yt-dlp output reached the user: %q", c.Text())
|
|
}
|
|
}
|
|
h.waitJobs(db.JobFailed, 1)
|
|
h.never(seq, "sendVideo", nil)
|
|
}
|
|
|
|
func TestRetryableFailureIsRetriedOnce(t *testing.T) {
|
|
h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
|
|
link: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "reset"}},
|
|
}}, nil)
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
h.wait(seq, "sendVideo", nil)
|
|
if n := len(h.fake.Downloads()); n != 2 {
|
|
t.Fatalf("downloads = %d, want 2 (one retry)", n)
|
|
}
|
|
}
|
|
|
|
func TestProbeFailureShowsFriendlyError(t *testing.T) {
|
|
h := start(t, &ytdlptest.Fake{ProbeErrs: map[string]error{
|
|
link: &ytdlp.Error{Code: ytdlp.CodeUnsupported, Raw: "ERROR: Unsupported URL"},
|
|
}}, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, link)
|
|
h.wait(seq, "editMessageText", textHas("I cannot download from that link"))
|
|
}
|
|
|
|
func TestPlaylistLinkIsExplained(t *testing.T) {
|
|
h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{
|
|
link: {Type: "playlist", ID: "PL", Title: "List"},
|
|
}}, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, link)
|
|
h.wait(seq, "editMessageText", textHas("playlist"))
|
|
}
|
|
|
|
func TestThumbnailFetchFailureFallsBackToTextCard(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
h.srv.FailNext("sendPhoto", 400, "Bad Request: wrong file identifier/HTTP URL specified")
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, link)
|
|
card := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok })
|
|
|
|
// 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")
|
|
}
|
|
}
|
|
|
|
func TestRejectedVideoIsSentAsDocument(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
card := h.card(alice, alice, link)
|
|
h.srv.FailNext("sendVideo", 400, "Bad Request: wrong file type")
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
doc := h.wait(seq, "sendDocument", nil)
|
|
if doc.Files["document"].Size != 1024 {
|
|
t.Fatalf("document upload = %+v", doc.Files)
|
|
}
|
|
h.wait(seq, edits, textHas("Done"))
|
|
}
|
|
|
|
func TestTransientSendFailureIsRetried(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
card := h.card(alice, alice, link)
|
|
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.waitJobs(db.JobDone, 1)
|
|
}
|
|
|
|
func TestSendGivesUpAfterRepeatedFailures(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
card := h.card(alice, alice, link)
|
|
for i := 0; i < 3; i++ {
|
|
h.srv.FailNext("sendVideo", 500, "Internal Server Error")
|
|
}
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
h.wait(seq, edits, textHas("could not send the file to Telegram"))
|
|
h.waitJobs(db.JobDone, 1) // the job itself is closed and cleaned up
|
|
if n := h.storedFiles(); n != 0 {
|
|
t.Fatalf("%d files left in storage", n)
|
|
}
|
|
}
|
|
|
|
// --- limits ----------------------------------------------------------------
|
|
|
|
func TestOverSizeAndOverDurationAreRefused(t *testing.T) {
|
|
big := "https://example.com/big"
|
|
long := "https://example.com/long"
|
|
h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{
|
|
big: {Type: "video", ID: "b", Title: "Big", Extractor: "fake", Duration: 60,
|
|
Formats: []ytdlp.Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 1080, Filesize: 80 << 20}}},
|
|
long: {Type: "video", ID: "l", Title: "Long", Extractor: "fake", Duration: 3600},
|
|
}}, nil)
|
|
|
|
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" {
|
|
t.Fatalf("alert = %+v", alert.Params)
|
|
}
|
|
// The card stays usable: the thumbnail-free card still lets the user
|
|
// pick something else, here MP3 is absent so we only check no job ran.
|
|
h.never(seq, "sendVideo|sendDocument", nil)
|
|
|
|
card = h.card(alice, alice, long)
|
|
seq = h.press(alice, alice, card, "dl:")
|
|
alert = h.wait(seq, "answerCallbackQuery", nil)
|
|
if !strings.Contains(alert.Params["text"], "longer than your limit of 10 minutes") {
|
|
t.Fatalf("alert = %+v", alert.Params)
|
|
}
|
|
if n := len(h.fake.Downloads()); n != 0 {
|
|
t.Fatalf("downloads = %d, want 0", n)
|
|
}
|
|
}
|
|
|
|
func TestWorkerEnforcesCapWhenMetadataHasNoSize(t *testing.T) {
|
|
// The card cannot know the size, the worker finds out and stops.
|
|
h := start(t, &ytdlptest.Fake{FileSize: 3 << 20, Infos: map[string]*ytdlp.Info{
|
|
link: {Type: "video", ID: "x", Title: "No Sizes", Extractor: "fake"},
|
|
}}, func(c *config.Config) { c.Limits.Free.MaxSizeMB = 2 })
|
|
card := h.card(alice, alice, link)
|
|
seq := h.press(alice, alice, card, "dl:")
|
|
h.wait(seq, edits, textHas("larger than your limit"))
|
|
h.never(seq, "sendVideo", nil)
|
|
}
|
|
|
|
func TestOneActiveJobPerFreeUser(t *testing.T) {
|
|
block := make(chan struct{})
|
|
defer close(block)
|
|
h := start(t, &ytdlptest.Fake{Block: block}, nil)
|
|
first := h.card(alice, alice, "https://example.com/a")
|
|
second := h.card(alice, alice, "https://example.com/b")
|
|
h.press(alice, alice, first, "dl:")
|
|
h.waitJobs(db.JobRunning, 1)
|
|
|
|
seq := h.press(alice, alice, second, "dl:")
|
|
alert := h.wait(seq, "answerCallbackQuery", nil)
|
|
if !strings.Contains(alert.Params["text"], "already have 1 download running") {
|
|
t.Fatalf("alert = %q", alert.Params["text"])
|
|
}
|
|
// Another user is not affected.
|
|
other := h.card(bob, bob, "https://example.com/c")
|
|
h.press(bob, bob, other, "dl:")
|
|
h.waitJobs(db.JobRunning, 2)
|
|
}
|
|
|
|
func TestDoubleTapStartsOneJob(t *testing.T) {
|
|
block := make(chan struct{})
|
|
defer close(block)
|
|
h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Limits.Free.ActiveJobs = 5 })
|
|
card := h.card(alice, alice, link)
|
|
btn, _ := card.Button("dl:")
|
|
for i := 0; i < 4; i++ {
|
|
h.srv.PushCallback(alice, alice, card.MessageID, btn.Data)
|
|
}
|
|
h.waitJobs(db.JobRunning, 1)
|
|
time.Sleep(300 * time.Millisecond)
|
|
if n := len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobQueued)); n != 1 {
|
|
t.Fatalf("%d jobs after a quadruple tap, want 1", n)
|
|
}
|
|
}
|
|
|
|
// --- other commands --------------------------------------------------------
|
|
|
|
func TestAudioCommandSkipsTheCard(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/audio "+link)
|
|
audio := h.wait(seq, "sendAudio", nil)
|
|
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"))
|
|
if len(h.srv.Calls("sendPhoto")) != 0 {
|
|
t.Fatal("/audio must not show a card")
|
|
}
|
|
}
|
|
|
|
func TestThumbCommandSendsPhoto(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/thumb "+link)
|
|
photo := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, up := c.Files["photo"]; return up })
|
|
if photo.Files["photo"].Name != "Test Video.jpg" {
|
|
t.Fatalf("photo upload = %+v", photo.Files)
|
|
}
|
|
}
|
|
|
|
func TestInfoCommandListsFormatsWithoutDownloading(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
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"} {
|
|
if !strings.Contains(info.Text(), want) {
|
|
t.Errorf("info text lacks %q: %q", want, info.Text())
|
|
}
|
|
}
|
|
if strings.Contains(info.Text(), "1080p") {
|
|
t.Errorf("1080p is above the source height and must not be listed: %q", info.Text())
|
|
}
|
|
if n := len(h.fake.Downloads()); n != 0 {
|
|
t.Fatalf("/info downloaded %d files", n)
|
|
}
|
|
}
|
|
|
|
func TestStartHelpAndHints(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/start", fakeserver.From("Ana <b>", "ana"))
|
|
welcome := h.wait(seq, "sendMessage", textHas("welcome"))
|
|
if !strings.Contains(welcome.Text(), "Ana <b>") {
|
|
t.Fatalf("the name must be escaped: %q", welcome.Text())
|
|
}
|
|
if welcome.Params["parse_mode"] != "HTML" {
|
|
t.Fatalf("parse_mode = %q", welcome.Params["parse_mode"])
|
|
}
|
|
u, err := h.app.Store.GetUser(context.Background(), alice)
|
|
if err != nil || u.Username != "ana" || u.FirstName != "Ana <b>" || u.Lang != "en" {
|
|
t.Fatalf("user row = %+v, %v", u, err)
|
|
}
|
|
|
|
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"))
|
|
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "hello bot")
|
|
h.wait(seq, "sendMessage", textHas("Send me a link"))
|
|
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "/nope")
|
|
h.wait(seq, "sendMessage", textHas("do not know that command"))
|
|
|
|
seq = h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, "http://127.0.0.1:8080/admin")
|
|
h.wait(seq, "sendMessage", textHas("Send me a link"))
|
|
if n := len(h.fake.Probes()); n != 0 {
|
|
t.Fatalf("a private address was probed %d times", n)
|
|
}
|
|
}
|
|
|
|
// --- durability ------------------------------------------------------------
|
|
|
|
func TestRestartResumesQueuedJob(t *testing.T) {
|
|
block := make(chan struct{})
|
|
fake := &ytdlptest.Fake{Block: block}
|
|
h := start(t, fake, nil)
|
|
card := h.card(alice, alice, link)
|
|
h.press(alice, alice, card, "dl:")
|
|
h.waitJobs(db.JobRunning, 1)
|
|
|
|
// Stop the core in the middle of the download. The worker hands the
|
|
// job back, and the next start picks it up and delivers it.
|
|
h.stop()
|
|
close(block)
|
|
seq := h.srv.Seq()
|
|
h.boot()
|
|
video := h.wait(seq, "sendVideo", nil)
|
|
if video.ChatID() != alice {
|
|
t.Fatalf("sendVideo after restart = %+v", video.Params)
|
|
}
|
|
h.wait(seq, edits, textHas("Done"))
|
|
h.waitJobs(db.JobDone, 1)
|
|
}
|
|
|
|
func TestCommandMenuIsRegistered(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
calls := h.srv.Calls("setMyCommands")
|
|
if len(calls) == 0 {
|
|
t.Fatal("setMyCommands was not called")
|
|
}
|
|
var cmds []struct {
|
|
Command string `json:"command"`
|
|
Description string `json:"description"`
|
|
}
|
|
if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(cmds) != 7 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
|
|
t.Fatalf("commands = %+v", cmds)
|
|
}
|
|
for _, c := range cmds {
|
|
if c.Command != strings.ToLower(c.Command) || strings.HasPrefix(c.Description, "menu.") {
|
|
t.Errorf("bad menu entry %+v", c)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestHealthEndpoint(t *testing.T) {
|
|
h := start(t, nil, nil)
|
|
resp, err := http.Get("http://" + h.app.HTTP.Addr() + "/healthz")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
body, _ := io.ReadAll(resp.Body)
|
|
if resp.StatusCode != 200 || !strings.Contains(string(body), `"ok"`) {
|
|
t.Fatalf("healthz = %d %s", resp.StatusCode, body)
|
|
}
|
|
}
|
|
|
|
// TestRealYtDlp runs the whole path with the real yt-dlp and ffmpeg against
|
|
// a small public test file. It needs network access, so it only runs when
|
|
// DLBOT_E2E_YTDLP points at a yt-dlp binary:
|
|
//
|
|
// DLBOT_E2E_YTDLP=$(command -v yt-dlp) go test ./internal/app -run TestRealYtDlp -v
|
|
func TestRealYtDlp(t *testing.T) {
|
|
bin := os.Getenv("DLBOT_E2E_YTDLP")
|
|
if bin == "" {
|
|
t.Skip("set DLBOT_E2E_YTDLP to a yt-dlp binary to run this test")
|
|
}
|
|
url := os.Getenv("DLBOT_E2E_URL")
|
|
if url == "" {
|
|
url = "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4"
|
|
}
|
|
real := &ytdlp.Exec{Path: bin, ProbeTimeout: 60 * time.Second, DownloadTimeout: 3 * time.Minute}
|
|
h := startWithRunner(t, real, nil)
|
|
|
|
seq := h.srv.Seq()
|
|
h.srv.PushMessage(alice, alice, url)
|
|
card, ok := h.srv.WaitFor(seq, 90*time.Second, "sendPhoto|editMessageText", func(c fakeserver.Call) bool {
|
|
_, ok := c.Button("dl:")
|
|
return ok
|
|
})
|
|
if !ok {
|
|
t.Fatalf("no card for the real link. Calls: %+v", h.srv.Calls(""))
|
|
}
|
|
t.Logf("card: %q buttons=%v", card.Text(), card.Buttons())
|
|
|
|
seq = h.press(alice, alice, card, "dl:")
|
|
video, ok := h.srv.WaitFor(seq, 3*time.Minute, "sendVideo|sendDocument", nil)
|
|
if !ok {
|
|
var last string
|
|
for _, c := range h.srv.Calls("") {
|
|
if c.Text() != "" {
|
|
last = c.Text()
|
|
}
|
|
}
|
|
t.Fatalf("the real download was not delivered. Last status: %q", last)
|
|
}
|
|
f := video.Files["video"]
|
|
t.Logf("delivered via %s: %s (%d bytes), duration=%s %sx%s", video.Method, f.Name, f.Size,
|
|
video.Params["duration"], video.Params["width"], video.Params["height"])
|
|
if video.Method != "sendVideo" || f.Size < 100_000 || video.Params["duration"] != "10" ||
|
|
video.Params["width"] != "640" || video.Params["height"] != "360" {
|
|
t.Fatalf("unexpected delivery: %+v %+v", video.Params, video.Files)
|
|
}
|
|
}
|