From 15f7c0c6e132bad40e470ab027987636d9c86660 Mon Sep 17 00:00:00 2001 From: Justin Reichardt Date: Wed, 9 Nov 2022 18:10:46 -0600 Subject: [PATCH] Added useful comments --- src/viddown.go | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/viddown.go b/src/viddown.go index 4c3f2fe..1744abe 100644 --- a/src/viddown.go +++ b/src/viddown.go @@ -46,18 +46,25 @@ const template = ` ` +// Used to request an operation (download) type ops struct { URL string Res chan string } +// List of the operations currently being worked on var currentWork map[int]string +// program configurations var config struct { + // Where files should be saved saveLocation string } + +// Global channel to send operation requests to var opsc = make(chan ops) +// handleRequest handles http requests func handleRequest(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet { log.Print("New Get request") @@ -70,6 +77,8 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { }() } else { } + + // Modify template and send it to the requester var insert string for _, url := range currentWork { insert += "
" + url @@ -81,22 +90,28 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { func downloadVid(r *http.Request) { } +// operationHandler waits for operation requests and initiates them func operationHandler() { + // Simple index for sorting video work for i := 0; true; i++ { o := <-opsc log.Print("Start Downloading: " + o.URL) + + // Spin off a go routine to handle a download so the handler can continue to receive requests go func() { + // Create a unique directory to download the video in dir := path.Join(config.saveLocation, ".viddown", strconv.Itoa(i)) os.MkdirAll(dir, 0755) + + // Build the download command cmd := exec.Command("youtube-dl", o.URL) cmd.Dir = dir + "/" - currentWork[i] = o.URL + currentWork[i] = o.URL // Adds the URL to list of current work cmd.Run() - log.Print("Finished: " + o.URL) + delete(currentWork, i) // Remove the URL from list of current work - delete(currentWork, i) - + // Clean up directory files, err := ioutil.ReadDir(dir + "/") if err != nil { log.Print(err) @@ -122,6 +137,7 @@ func operationHandler() { } func main() { + // Set the location to save videos if os.Getenv("VIDDOWNLOC") == "" { config.saveLocation = "./" } else { @@ -129,12 +145,16 @@ func main() { } log.Println("Downloading files to: " + config.saveLocation) + // initialize currentWork with a blank map currentWork = make(map[int]string) + // Create the work directory os.MkdirAll(path.Join(config.saveLocation, ".viddown"), 0755) + // Start the operations handler go operationHandler() + // Start the http server handler := http.HandlerFunc(handleRequest) http.Handle("/", handler) log.Printf("Starting server on 8080")