From b82b70d91138ecc973749e885c61a169348af10d Mon Sep 17 00:00:00 2001 From: HeshamTB Date: Tue, 12 Sep 2023 00:09:24 +0300 Subject: [PATCH] feat: added yt for yt-dlp logic within the app --- main.go | 34 +--------------------------------- yt.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 33 deletions(-) create mode 100644 yt.go diff --git a/main.go b/main.go index 32e86bb..944ca62 100644 --- a/main.go +++ b/main.go @@ -2,13 +2,10 @@ package main import ( "encoding/json" - "fmt" "html/template" - "io" "log" "net/http" "time" - ) const ( @@ -107,16 +104,6 @@ func NewContext(r *http.Request) *Context { } } -var AppURL string = "http://localhost:8080" -type HTMLBaseData struct { - Formats []DownloadFormats - AppURL string -} - -var appData HTMLBaseData = HTMLBaseData{ - AppURL: AppURL, -} - func init() { log.Println("[ init ] Starting...") @@ -146,9 +133,8 @@ func main() { w = writeJSONResponse(w, "Provide URL as query") return } - // Get URL from convx - req, err := http.Get(fmt.Sprintf("http://localhost:80?url=%s", userURL)) + downloadURL, err := getYoutubeDownloadURL(userURL) if err != nil { log.Println(err.Error()) ctx.StatusCode = 500 @@ -156,23 +142,6 @@ func main() { err = templates.ExecuteTemplate(w,"download-result.html", ctx) return } - if req.StatusCode != 200 { - log.Printf("Got %v from convx\n", req) - ctx.StatusCode = 500 - ctx.Err = &err - err = templates.ExecuteTemplate(w,"download-result.html", ctx) - return - } - body, err := io.ReadAll(req.Body) - if err != nil { - log.Printf("Error while reading convx response body. \n%v", err.Error()) - ctx.StatusCode = 500 - ctx.Err = &err - err = templates.ExecuteTemplate(w,"download-result.html", ctx) - return - } - downloadURL := string(body) - log.Println("URL from convx", downloadURL) ctx.DownloadURL = downloadURL err = templates.ExecuteTemplate(w,"download-result.html", ctx) @@ -194,7 +163,6 @@ func main() { audioOnly: false, videoOnly: false, }) - appData.Formats = formats err := templates.ExecuteTemplate(w, "download.html", ctx) if err != nil { log.Println(err.Error()) diff --git a/yt.go b/yt.go new file mode 100644 index 0000000..6bd6321 --- /dev/null +++ b/yt.go @@ -0,0 +1,47 @@ +package main + +import ( + "net/http" + "net/url" + "os/exec" +) + + +func getYoutubeDownloadURL(link string) (string, error) { + + var dlLink string + cmd := exec.Command("yt-dlp", "--get-url", "-f 22", link) + result, err := cmd.Output() + + if err != nil { + return "", err + } + + dlLink = string(result) + + return dlLink, nil +} + +func isValidURL(data string) bool { + + _, err := url.ParseRequestURI(data) + + if err != nil { + return false + } + + + httpClient := &http.Client{} + resp, err := httpClient.Get(data) + + if err != nil { + return false + } + + if resp.StatusCode != 200 { + return false + } + + return true +} +