diff --git a/backend/main.go b/backend/main.go index 6c07ac0..cda31a8 100644 --- a/backend/main.go +++ b/backend/main.go @@ -33,6 +33,16 @@ func download(c *gin.Context, downloader youtube.Downloader) error { return nil } +func createTask(c *gin.Context) { + err := c.Request.ParseForm() + if err != nil { + panic(err) + } + if err := download(c, youtube_dl.NewYoutubeDlDownloader(c.PostForm("url"), "yt-dlp")); err != nil { + panic(err) + } +} + func status(c *gin.Context, downloader youtube.Downloader) error { id, err := downloader.ExtractVideoID() if err != nil { @@ -85,11 +95,7 @@ func main() { } }) - r.GET("/download", func(c *gin.Context) { - if err := download(c, youtube_dl.NewYoutubeDlDownloader(c.Query("url"), "yt-dlp")); err != nil { - panic(err) - } - }) + r.POST("/task", createTask) r.GET("/status", func(c *gin.Context) { if err := status(c, youtube_dl.NewYoutubeDlDownloader(c.Query("url"), "yt-dlp")); err != nil { diff --git a/backend/main_test.go b/backend/main_test.go new file mode 100644 index 0000000..62c2900 --- /dev/null +++ b/backend/main_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/remogatto/prettytest" +) + +// Start of setup +type testSuite struct { + prettytest.Suite +} + +func TestRunner(t *testing.T) { + prettytest.Run( + t, + new(testSuite), + ) +} + +// Test the creation of a new task. A new task is created with a POST +// request to the endpoint. +func (t *testSuite) TestCreateTask() { + // Set form values + form := url.Values{} + form.Add("url", "https://www.youtube.com/watch?v=AVIBLFl28vo") + + // Create a new request + req, err := http.NewRequest("POST", "/task", strings.NewReader(form.Encode())) + if err != nil { + panic(err) + } + + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + // Create an http recorder + rr := httptest.NewRecorder() + + // Set the context and call the handler + c, _ := gin.CreateTestContext(rr) + c.Request = req + + createTask(c) + + // Read the response and assert it. + var data struct { + Id string + } + + if err := json.Unmarshal(rr.Body.Bytes(), &data); err != nil { + panic(err) + } + + t.Equal("AVIBLFl28vo", data.Id) +} diff --git a/backend/youtube/youtube-dl/youtube-dl.go b/backend/youtube/youtube-dl/youtube-dl.go index 8f0639e..23ecce6 100644 --- a/backend/youtube/youtube-dl/youtube-dl.go +++ b/backend/youtube/youtube-dl/youtube-dl.go @@ -63,9 +63,9 @@ func (d *YoutubeDlDownloader) ExtractVideoID() (string, error) { func (d *YoutubeDlDownloader) getVideoJson(url string) (*youtube.Video, error) { cmd := exec.CommandContext(context.Background(), d.CommandName, "-j", url) - output, err := cmd.Output() + output, err := cmd.CombinedOutput() if err != nil { - return nil, err + return nil, fmt.Errorf("Command terminated with %w: %s", err, output) } result := new(youtube.Video) err = json.Unmarshal(output, &result)