101 lines
1.8 KiB
Go
101 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/kkdai/youtube/v2"
|
|
)
|
|
|
|
const (
|
|
StatusDownloading = iota
|
|
StatusCompleted
|
|
StatusError
|
|
)
|
|
|
|
type Task struct {
|
|
Video *youtube.Video
|
|
Status int
|
|
}
|
|
|
|
var taskCh chan *Task
|
|
|
|
func init() {
|
|
log.SetPrefix("[youtube-dl-service] ")
|
|
taskCh = make(chan *Task)
|
|
}
|
|
|
|
func main() {
|
|
go func() {
|
|
log.Println("Start task scheduler...")
|
|
for {
|
|
select {
|
|
case task := <-taskCh:
|
|
log.Println(task.Status)
|
|
|
|
}
|
|
}
|
|
|
|
log.Println("Stop task scheduler...")
|
|
}()
|
|
|
|
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("/get_video", func(c *gin.Context) {
|
|
id, err := youtube.ExtractVideoID(c.Query("url"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
log.Printf("Extracted video ID: %s", id)
|
|
|
|
client := youtube.Client{}
|
|
video, err := client.GetVideo(id)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
c.JSON(200, gin.H{
|
|
"title": video.Title,
|
|
"duration": float64(video.Duration) / float64(time.Minute),
|
|
"thumbnails": video.Thumbnails[0],
|
|
})
|
|
|
|
go func() {
|
|
log.Println("Download started.")
|
|
taskCh <- &Task{
|
|
video,
|
|
StatusDownloading,
|
|
}
|
|
|
|
// simulate a long task with time.Sleep(). 5 seconds
|
|
time.Sleep(5 * time.Second)
|
|
|
|
// note that you are using the copied context "cCp", IMPORTANT
|
|
log.Printf("Video with id %s downloaded.", video.ID)
|
|
taskCh <- &Task{
|
|
video,
|
|
StatusCompleted,
|
|
}
|
|
|
|
}()
|
|
|
|
})
|
|
|
|
r.Run()
|
|
}
|