feat: added yt for yt-dlp logic within the app

This commit is contained in:
HeshamTB 2023-09-12 00:09:24 +03:00
parent d047788835
commit b82b70d911
2 changed files with 48 additions and 33 deletions

34
main.go
View File

@ -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())

47
yt.go Normal file
View File

@ -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
}