clipper/backend/server/handlers.go

96 lines
2.9 KiB
Go

package server
import (
"encoding/json"
"log"
"net/http"
"strconv"
"git.netflux.io/rob/clipper/media"
"git.netflux.io/rob/clipper/youtube"
youtubev2 "github.com/kkdai/youtube/v2"
"github.com/labstack/echo/v4"
)
// getMediaSet is a handler that responds with a MediaSet.
func getMediaSet(c echo.Context) error {
videoID := c.Param("id")
mediaSet := media.NewMediaSet(videoID)
if mediaSet.Exists() {
if err := mediaSet.Load(); err != nil {
log.Printf("error loading MediaSet: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not fetch media set")
}
return c.JSON(http.StatusOK, mediaSet)
}
var youtubeClient youtubev2.Client
downloader := youtube.NewDownloader(&youtubeClient)
mediaSet, err := downloader.Download(c.Request().Context(), videoID)
if err != nil {
log.Printf("error downloading MediaSet: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not fetch media set")
}
return c.JSON(http.StatusOK, mediaSet)
}
// getThumbnails is a handler that responds with a MediaSet thumbnail grid.
func getThumbnails(c echo.Context) error {
videoID := c.Param("id")
mediaSet := media.NewMediaSet(videoID)
if err := mediaSet.Load(); err != nil {
log.Printf("error loading MediaSet: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not load media set")
}
return c.File(mediaSet.ThumbnailPath())
}
// getVideo is a handler that responds with the video file for a MediaSet
func getVideo(c echo.Context) error {
videoID := c.Param("id")
mediaSet := media.NewMediaSet(videoID)
if err := mediaSet.Load(); err != nil {
log.Printf("error loading MediaSet: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not load media set")
}
return c.File(mediaSet.VideoPath())
}
// getPeaks is a handler that returns a two-dimensional array of peaks, with
// the number of bins matching the provided parameter.
func getPeaks(c echo.Context) error {
videoID := c.Param("id")
start, err := strconv.ParseInt(c.QueryParam("start"), 0, 64)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid start parameter provided")
}
end, err := strconv.ParseInt(c.QueryParam("end"), 0, 64)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid end parameter provided")
}
numBins, err := strconv.Atoi(c.QueryParam("bins"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "invalid bins parameter provided")
}
mediaSet := media.NewMediaSet(videoID)
if err = mediaSet.Load(); err != nil {
log.Printf("error loading MediaSet: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not load media set")
}
peaks, err := mediaSet.Peaks(start, end, numBins)
if err != nil {
log.Printf("error generating peaks: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError, "could not generate peaks")
}
return json.NewEncoder(c.Response()).Encode(peaks)
}