92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strconv"
|
|
|
|
"git.andreafazzi.eu/andrea/youtube-dl-service/task"
|
|
"git.andreafazzi.eu/andrea/youtube-dl-service/youtube"
|
|
youtube_dl "git.andreafazzi.eu/andrea/youtube-dl-service/youtube/youtube-dl"
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
var tasks task.Tasks
|
|
|
|
func init() {
|
|
log.SetPrefix("[youtube-dl-service] ")
|
|
tasks = make(task.Tasks, 0)
|
|
}
|
|
|
|
func download(c *gin.Context, downloader youtube.Downloader) error {
|
|
video, err := downloader.GetVideo()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.JSON(http.StatusOK, video)
|
|
|
|
go downloader.StartDownload(video, tasks)
|
|
|
|
return nil
|
|
}
|
|
|
|
func status(c *gin.Context, downloader youtube.Downloader) error {
|
|
id, err := downloader.ExtractVideoID()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
task, ok := tasks[id]
|
|
if ok {
|
|
c.JSON(http.StatusOK, task)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func serveFile(c *gin.Context, filename string) error {
|
|
c.Writer.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename))
|
|
c.Writer.Header().Set("Content-Type", "application/octet-stream")
|
|
http.ServeFile(c.Writer, c.Request, filepath.Join("data", filename))
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
r := gin.Default()
|
|
r.Use(cors.New(cors.Config{
|
|
AllowOrigins: []string{"http://localhost:8080", "http://localhost:5000"},
|
|
AllowCredentials: true,
|
|
AllowHeaders: []string{"*"},
|
|
}))
|
|
|
|
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
|
|
if err, ok := recovered.(string); ok {
|
|
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
|
|
}
|
|
c.AbortWithStatus(http.StatusInternalServerError)
|
|
}))
|
|
|
|
r.GET("/data/:filename", func(c *gin.Context) {
|
|
if err := serveFile(c, c.Param("filename")); err != nil {
|
|
panic(err)
|
|
}
|
|
})
|
|
|
|
// r.Static("/data", "./data")
|
|
|
|
r.GET("/download", func(c *gin.Context) {
|
|
if err := download(c, youtube_dl.NewYoutubeDlDownloader(c.Query("url"), "yt-dlp")); err != nil {
|
|
panic(err)
|
|
}
|
|
})
|
|
|
|
r.GET("/status", func(c *gin.Context) {
|
|
if err := status(c, youtube_dl.NewYoutubeDlDownloader(c.Query("url"), "yt-dlp")); err != nil {
|
|
panic(err)
|
|
}
|
|
})
|
|
|
|
r.Run()
|
|
}
|