reveil/api/tracks.go

94 lines
2.3 KiB
Go
Raw Normal View History

2022-10-02 21:24:53 +00:00
package api
import (
2022-10-04 10:29:50 +00:00
"fmt"
2022-10-02 21:24:53 +00:00
"net/http"
"github.com/gin-gonic/gin"
"git.nemunai.re/nemunaire/reveil/config"
2022-10-04 10:29:50 +00:00
"git.nemunai.re/nemunaire/reveil/model"
2022-10-02 21:24:53 +00:00
)
func declareTracksRoutes(cfg *config.Config, router *gin.RouterGroup) {
router.GET("/tracks", func(c *gin.Context) {
2022-10-04 10:29:50 +00:00
tracks, err := reveil.LoadTracks(cfg)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
return
}
2022-10-02 21:24:53 +00:00
2022-10-04 10:29:50 +00:00
c.JSON(http.StatusOK, tracks)
2022-10-02 21:24:53 +00:00
})
router.POST("/tracks", func(c *gin.Context) {
2022-10-04 10:29:50 +00:00
c.AbortWithStatusJSON(http.StatusNotImplemented, gin.H{"errmsg": "TODO"})
2022-10-02 21:24:53 +00:00
})
tracksRoutes := router.Group("/tracks/:tid")
2022-10-04 10:29:50 +00:00
tracksRoutes.Use(func(c *gin.Context) {
tracks, err := reveil.LoadTracks(cfg)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
return
}
for _, t := range tracks {
2022-10-04 13:47:06 +00:00
if t.Id.ToString() == c.Param("tid") {
2022-10-04 10:29:50 +00:00
c.Set("track", t)
c.Next()
return
}
}
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Track not found"})
})
2022-10-02 21:24:53 +00:00
tracksRoutes.GET("", func(c *gin.Context) {
c.JSON(http.StatusOK, c.MustGet("track"))
})
tracksRoutes.PUT("", func(c *gin.Context) {
2022-10-04 10:29:50 +00:00
oldtrack := c.MustGet("track").(*reveil.Track)
var track reveil.Track
if err := c.ShouldBindJSON(&track); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
return
}
if track.Name != oldtrack.Name {
err := oldtrack.Rename(track.Name)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to rename the track: %s", err.Error())})
return
}
}
if track.Enabled != oldtrack.Enabled {
var err error
if track.Enabled {
err = oldtrack.Enable(cfg)
} else {
err = oldtrack.Disable()
}
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to enable/disable the track: %s", err.Error())})
return
}
}
c.JSON(http.StatusOK, oldtrack)
2022-10-02 21:24:53 +00:00
})
tracksRoutes.DELETE("", func(c *gin.Context) {
2022-10-04 10:29:50 +00:00
track := c.MustGet("track").(*reveil.Track)
2022-10-02 21:24:53 +00:00
2022-10-04 10:29:50 +00:00
err := track.Remove()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to remove the track: %s", err.Error())})
return
}
2022-10-02 21:24:53 +00:00
2022-10-04 10:29:50 +00:00
c.JSON(http.StatusOK, nil)
})
2022-10-02 21:24:53 +00:00
}