package api import ( "fmt" "log" "net/http" "github.com/gin-gonic/gin" "git.nemunai.re/nemunaire/reveil/config" "git.nemunai.re/nemunaire/reveil/model" ) func declareActionsRoutes(cfg *config.Config, router *gin.RouterGroup) { router.GET("/actions", func(c *gin.Context) { actions, err := reveil.LoadActions(cfg) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()}) return } c.JSON(http.StatusOK, actions) }) router.POST("/actions", func(c *gin.Context) { c.AbortWithStatusJSON(http.StatusNotImplemented, gin.H{"errmsg": "TODO"}) }) actionsRoutes := router.Group("/actions/:tid") actionsRoutes.Use(func(c *gin.Context) { actions, err := reveil.LoadActions(cfg) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()}) return } for _, t := range actions { if t.Id.ToString() == c.Param("tid") { c.Set("action", t) c.Next() return } } c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Action not found"}) }) actionsRoutes.GET("", func(c *gin.Context) { c.JSON(http.StatusOK, c.MustGet("action")) }) actionsRoutes.PUT("", func(c *gin.Context) { oldaction := c.MustGet("action").(*reveil.Action) var action reveil.Action if err := c.ShouldBindJSON(&action); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()}) return } if action.Name != oldaction.Name { err := oldaction.Rename(action.Name) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to rename the action: %s", err.Error())}) return } } if action.Enabled != oldaction.Enabled { var err error if action.Enabled { err = oldaction.Enable() } else { err = oldaction.Disable() } if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to enable/disable the action: %s", err.Error())}) return } } c.JSON(http.StatusOK, oldaction) }) actionsRoutes.DELETE("", func(c *gin.Context) { action := c.MustGet("action").(*reveil.Action) err := action.Remove() if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to remove the action: %s", err.Error())}) return } c.JSON(http.StatusOK, nil) }) actionsRoutes.POST("/run", func(c *gin.Context) { action := c.MustGet("action").(*reveil.Action) settings, err := reveil.ReadSettings(cfg.SettingsFile) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to run the action: unable to read settings: %s", err.Error())}) return } cmd, err := action.Launch(settings) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to run the action: %s", err.Error())}) return } go func() { err := cmd.Wait() if err != nil { log.Printf("%q: %s", action.Name, err.Error()) } }() c.JSON(http.StatusOK, true) }) }