dndmusicbot/youtube.go

99 lines
1.8 KiB
Go
Raw Normal View History

2022-11-18 21:18:12 +00:00
package main
import (
2023-11-02 20:30:29 +00:00
"bytes"
"dndmusicbot/youtube"
2023-11-02 20:30:29 +00:00
"io"
2022-11-18 21:18:12 +00:00
"log"
2023-11-02 20:30:29 +00:00
"net/http"
"os"
"github.com/grafov/m3u8"
"github.com/julienschmidt/httprouter"
2022-11-18 21:18:12 +00:00
)
func init() {
log.Println("youtube.go loading..")
app.youtube = youtube.New()
2022-11-18 21:18:12 +00:00
log.Println("youtube.go done.")
}
2023-11-02 20:30:29 +00:00
func ProxyTube(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
os.MkdirAll(config.GetString("cache.path"), 0755)
buf := new(bytes.Buffer)
_, data, err := app.cache.Get("youtube." + p.ByName("id"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// cache hit
if data != nil {
io.Copy(w, data)
return
//w.WriteHeader(200)
}
vinfo, err := app.youtube.GetVideoFromID(p.ByName("id"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uri := vinfo.GetHLSPlaylist("234")
resp, err := http.Get(uri)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
pl, _, err := m3u8.DecodeFrom(resp.Body, true)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var segresp *http.Response
mediapl := pl.(*m3u8.MediaPlaylist)
writer := io.MultiWriter(w, buf)
if err != nil {
log.Println(err)
return
}
for _, segment := range mediapl.GetAllSegments() {
segresp, err = http.Get(segment.URI)
2023-11-02 20:30:29 +00:00
if err != nil {
segresp.Body.Close()
2023-11-02 20:30:29 +00:00
log.Println(err)
return
}
_, err = io.Copy(writer, segresp.Body)
2023-11-02 20:30:29 +00:00
if err != nil {
segresp.Body.Close()
2023-11-02 20:30:29 +00:00
log.Println(err)
return
}
}
2023-11-02 20:30:29 +00:00
go func() {
_, cw, err := app.cache.WriteCloser("youtube." + p.ByName("id"))
2023-11-02 20:30:29 +00:00
if err != nil {
log.Println(err)
return
}
cw.Write(buf.Bytes())
cw.Close()
}()
//w.WriteHeader(200)
2023-11-02 20:30:29 +00:00
}