From 6e027de4063bb2b65006b746c1eb8bffcf76f440 Mon Sep 17 00:00:00 2001 From: Logan G Date: Tue, 31 Dec 2024 15:53:17 -0700 Subject: [PATCH] Moved youtube.go to download.go --- download.go | 113 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 download.go diff --git a/download.go b/download.go new file mode 100644 index 0000000..c296826 --- /dev/null +++ b/download.go @@ -0,0 +1,113 @@ +package main + +import ( + "context" + "fmt" + "os" + "io" + "errors" + "net/http" + "strconv" + + + "github.com/charmbracelet/log" + "github.com/wader/goutubedl" +) + +func checkURL(input string) (error) { + request, err := http.NewRequest("GET", input, nil) + if err != nil { + return err + } + + client := &http.Client{} + resp, err := client.Do(request) + if err != nil { + return err + } + + if resp.StatusCode == http.StatusNotFound { + return errors.New(fmt.Sprintf("Video does not exist!")) + } + + return nil +} + +func downloadVideo(url string, videoFormat string, audioFormat string, outDir string, sizeLimit float64) (err error) { + goutubedl.Path = "yt-dlp" + + if err := checkURL(url); err != nil { + return err + } + + log.Debugf("URL \"%s\" exists.", url) + + video, err := goutubedl.New(context.Background(), url, goutubedl.Options{}) + if err != nil { + return err + } + + path := outDir+strconv.Itoa(int(video.Info.Timestamp))+" - "+video.Info.Title + + if ! video.Info.IsLive { + /* VIDEO */ + { + log.Debugf("Downloading video \"%s\" with format \"%s\"", video.Info.ID, videoFormat) + + videoDLResult, err := video.Download(context.Background(), videoFormat) + if err != nil { + return err + } + + defer videoDLResult.Close() + + file, err := os.OpenFile(path+"-vid", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) + defer file.Close() + + io.Copy(file, videoDLResult) + + videoDLResult.Close() + file.Close() + } + + /* AUDIO */ + { + log.Debugf("Downloading audio \"%s\" with format \"%s\"", video.Info.ID, audioFormat) + + audioDLResult, err := video.Download(context.Background(), audioFormat) + if err != nil { + return err + } + + defer audioDLResult.Close() + + file, err := os.OpenFile(path+"-audio", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644) + defer file.Close() + + io.Copy(file, audioDLResult) + + audioDLResult.Close() + file.Close() + } + + mergeStreams(path+"-vid",path+"-audio",path+".mkv") + + if err := os.Remove(path+"-vid"); err != nil { + log.Warnf("Could not remove file \"%s\"", path+"-vid") + } + if err := os.Remove(path+"-audio"); err != nil { + log.Warnf("Could not remove file \"%s\"", path+"-audio") + } + + /* + extension, err := getExtension(path) + if err != nil { + return err + } + + os.Rename(path, path+"."+extension) + */ + } + + return nil +}