clean up proxy code
Marco Andronaco andronacomarco@gmail.com
Sat, 13 Jan 2024 14:34:34 +0100
2 files changed,
31 insertions(+),
24 deletions(-)
M
fixyoutube.go
→
fixyoutube.go
@@ -124,30 +124,14 @@ return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) videoId := vars["videoId"] - video, err := invidious.GetVideoDB(videoId) - if err != nil { - logger.Warn("Cannot proxy a video that is not cached: https://youtu.be/", videoId) - http.Error(w, "Something went wrong.", http.StatusBadRequest) + b, l, s := invidiousClient.ProxyVideoId(videoId) + if l > 0 { + h := w.Header() + h.Set("Status", "200") + h.Set("Content-Type", "video/mp4") + h.Set("Content-Length", strconv.FormatInt(l, 10)) + io.Copy(w, b) return - } - - fmtAmount := len(video.Formats) - - s := http.StatusNotFound - for i := fmtAmount - 1; i >= 0; i-- { - url := video.Formats[i].Url - logger.Debug(url) - b, l, httpStatus := invidiousClient.ProxyVideo(url) - if httpStatus == http.StatusOK { - h := w.Header() - h.Set("Status", "200") - h.Set("Content-Type", "video/mp4") - h.Set("Content-Length", strconv.FormatInt(l, 10)) - io.Copy(w, b) - return - } - s = httpStatus - logger.Debug("Format ", i, "failed with status code ", s) } logger.Error("proxyHandler() failed. Final code: ", s)
M
invidious/proxy.go
→
invidious/proxy.go
@@ -6,7 +6,7 @@ "io"
"net/http" ) -func (c *Client) ProxyVideo(url string) (*bytes.Buffer, int64, int) { +func (c *Client) proxyUrl(url string) (*bytes.Buffer, int64, int) { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { logger.Error(err) // bad request@@ -42,3 +42,26 @@ }
return b, l, http.StatusOK } + +func (c *Client) proxyVideo(video *Video) (*bytes.Buffer, int64, int) { + for i := len(video.Formats) - 1; i >= 0; i-- { + url := video.Formats[i].Url + logger.Debug(url) + b, l, httpStatus := c.proxyUrl(url) + if httpStatus == http.StatusOK { + return b, l, i + } + logger.Debug("Format ", i, "failed with status code ", httpStatus) + } + return nil, 0, -1 +} + +func (c *Client) ProxyVideoId(videoId string) (*bytes.Buffer, int64, int) { + video, err := GetVideoDB(videoId) + if err != nil { + logger.Info("Cannot proxy a video that is not cached: https://youtu.be/", videoId) + return nil, 0, http.StatusBadRequest + } + + return c.proxyVideo(video) +}