1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-10 09:02:49 +00:00

added youtube downloader

This commit is contained in:
2017-07-21 00:06:59 -05:00
parent 4baad6b025
commit 43fadf9c6a
14 changed files with 240 additions and 20 deletions

View File

@@ -0,0 +1,71 @@
package handlers
import (
"bytes"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"github.com/mgerb/chi_auth_server/response"
)
// Downloader -
func Downloader(w http.ResponseWriter, r *http.Request) {
url := r.FormValue("url")
fileType := r.FormValue("fileType")
// create youtube folder if it does not exist
if _, err := os.Stat("youtube"); os.IsNotExist(err) {
os.Mkdir("youtube", os.ModePerm)
}
// get the video title
titleCmd := exec.Command("youtube-dl", "--get-title", url)
var titleOut bytes.Buffer
titleCmd.Stdout = &titleOut
err := titleCmd.Run()
if err != nil {
log.Println(err)
response.ERR(w, http.StatusInternalServerError, response.DefaultInternalError)
return
}
// TODO add video id to tile to not get collisions
// ------------------------------------------------
// remove all special characters from title
cleanTitle := cleanseTitle(titleOut.String())
log.Println(cleanTitle)
cmd := exec.Command("youtube-dl", "-x", "--audio-format", "mp3", "-o", "./youtube/"+cleanTitle+".%(ext)s", url)
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
log.Println(out.String())
log.Println(err)
response.ERR(w, http.StatusInternalServerError, response.DefaultInternalError)
return
}
response.JSON(w, map[string]interface{}{"fileName": cleanTitle + "." + fileType})
}
func cleanseTitle(title string) string {
// Make a Regex to say we only want
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Fatal(err)
}
return reg.ReplaceAllString(title, "")
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/mgerb/go-discord-bot/server/config"
)
// FileUpload
func FileUpload(w http.ResponseWriter, r *http.Request) {
password := r.FormValue("password")

View File

@@ -26,18 +26,21 @@ func getRouter() *chi.Mux {
r.Use(middleware.Logger)
}
r.Get("/soundlist", handlers.SoundList)
r.Put("/upload", handlers.FileUpload)
workDir, _ := os.Getwd()
FileServer(r, "/static", http.Dir(filepath.Join(workDir, "./dist/static")))
FileServer(r, "/sounds", http.Dir(filepath.Join(workDir, "./sounds")))
FileServer(r, "/public/sounds", http.Dir(filepath.Join(workDir, "./sounds")))
FileServer(r, "/public/youtube", http.Dir(filepath.Join(workDir, "./youtube")))
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./dist/index.html")
})
// configure end points
r.Get("/soundlist", handlers.SoundList)
r.Put("/upload", handlers.FileUpload)
r.Get("/ytdownloader", handlers.Downloader)
return r
}