2023-10-12 17:23:35 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2023-11-13 21:54:07 +00:00
|
|
|
"io"
|
2023-10-12 17:23:35 +00:00
|
|
|
"net/http"
|
2023-11-17 18:24:12 +00:00
|
|
|
"strings"
|
2023-10-12 17:23:35 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
"code.jhot.me/jhot/hats/internal/nats"
|
2023-11-08 23:12:04 +00:00
|
|
|
"code.jhot.me/jhot/hats/internal/ntfy"
|
2023-10-12 17:23:35 +00:00
|
|
|
"code.jhot.me/jhot/hats/pkg/config"
|
|
|
|
"code.jhot.me/jhot/hats/pkg/homeassistant"
|
2023-11-08 23:12:04 +00:00
|
|
|
ntfyPkg "code.jhot.me/jhot/hats/pkg/ntfy"
|
2023-10-12 17:23:35 +00:00
|
|
|
"github.com/go-chi/chi/middleware"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/go-chi/render"
|
2023-11-17 18:43:50 +00:00
|
|
|
"github.com/gomarkdown/markdown"
|
|
|
|
"github.com/gomarkdown/markdown/html"
|
|
|
|
"github.com/gomarkdown/markdown/parser"
|
2023-10-12 17:23:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
cfg *config.HatsConfig
|
|
|
|
logger *slog.Logger
|
|
|
|
server http.Server
|
|
|
|
haClient *homeassistant.RestClient
|
2023-11-17 18:43:50 +00:00
|
|
|
homepage string
|
2023-10-12 17:23:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
HA_STATE_PREFIX = "homeassistant.states"
|
|
|
|
)
|
|
|
|
|
2024-04-24 19:48:46 +00:00
|
|
|
func InitAPI(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) {
|
|
|
|
go func(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) {
|
|
|
|
for {
|
|
|
|
err := Listen(parentLogger, parentConfig, readme)
|
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
parentLogger.Error("An error occurred with the API. Restarting now.", "error", err)
|
|
|
|
Close()
|
|
|
|
}
|
|
|
|
}(parentLogger, parentConfig, readme)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Listen(parentLogger *slog.Logger, parentConfig *config.HatsConfig, readme []byte) error {
|
2023-10-12 17:23:35 +00:00
|
|
|
logger = parentLogger
|
2023-12-20 18:29:23 +00:00
|
|
|
cfg = parentConfig
|
2023-11-17 18:43:50 +00:00
|
|
|
|
|
|
|
// render readme to HTML
|
|
|
|
p := parser.NewWithExtensions(parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock)
|
|
|
|
doc := p.Parse(readme)
|
|
|
|
homepage = string(markdown.Render(doc, html.NewRenderer(html.RendererOptions{Flags: html.CommonFlags | html.HrefTargetBlank})))
|
|
|
|
|
2023-10-17 19:58:34 +00:00
|
|
|
haClient = homeassistant.NewRestClient(cfg.GetHomeAssistantBaseUrl(), cfg.HomeAssistantToken)
|
2023-10-12 17:23:35 +00:00
|
|
|
router := chi.NewRouter()
|
|
|
|
|
|
|
|
router.Use(middleware.RequestID)
|
|
|
|
router.Use(middleware.RealIP)
|
2023-11-17 18:24:12 +00:00
|
|
|
router.Use(loggerMiddleware)
|
2023-10-12 17:23:35 +00:00
|
|
|
router.Use(middleware.Recoverer)
|
|
|
|
router.Use(middleware.Timeout(60 * time.Second))
|
|
|
|
|
2023-11-17 18:43:50 +00:00
|
|
|
router.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
render.HTML(w, r, homepage)
|
|
|
|
})
|
|
|
|
router.Get("/status", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
render.PlainText(w, r, "OK")
|
|
|
|
})
|
|
|
|
|
|
|
|
router.Route("/api", func(r chi.Router) {
|
2023-12-08 23:37:54 +00:00
|
|
|
r.Use(authMiddleware)
|
2023-11-17 19:16:40 +00:00
|
|
|
r.Get(`/state/{entityId}`, getEntityStateHandler)
|
2023-11-20 22:01:50 +00:00
|
|
|
r.Post("/state/{entityId}/{service}", setEntityStateHandler)
|
2023-10-13 20:31:23 +00:00
|
|
|
|
2023-11-17 19:16:40 +00:00
|
|
|
r.Get("/timer/{timerName}", getTimerHandler)
|
|
|
|
r.Post("/timer/{timerName}", startTimerHandler)
|
|
|
|
r.Delete("/timer/{timerName}", deleteTimerHandler)
|
2023-10-13 20:31:23 +00:00
|
|
|
|
2023-11-17 19:16:40 +00:00
|
|
|
r.Get("/schedule/{scheduleName}", getScheduleHandler)
|
|
|
|
r.Post("/schedule/{scheduleName}", createScheduleHandler)
|
|
|
|
r.Delete("/schedule/{scheduleName}", deleteScheduleHandler)
|
2023-10-12 17:23:35 +00:00
|
|
|
|
2023-11-17 19:16:40 +00:00
|
|
|
r.Post("/ntfy", postNtfyHandler)
|
2023-11-08 23:12:04 +00:00
|
|
|
|
2023-11-17 19:16:40 +00:00
|
|
|
r.Post("/command/{commandName}", postCommandHandler)
|
2023-11-17 18:43:50 +00:00
|
|
|
})
|
2023-11-13 21:54:07 +00:00
|
|
|
|
2023-10-12 17:23:35 +00:00
|
|
|
server = http.Server{
|
|
|
|
Addr: ":8888",
|
|
|
|
Handler: router,
|
|
|
|
}
|
|
|
|
|
2024-04-24 19:48:46 +00:00
|
|
|
return server.ListenAndServe()
|
2023-10-12 17:23:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Close() {
|
|
|
|
if server.Addr != "" {
|
|
|
|
server.Close()
|
|
|
|
}
|
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
|
2023-12-08 23:37:54 +00:00
|
|
|
// authMiddleware checks both basic and bearer auth schemes for a token
|
|
|
|
//
|
|
|
|
// When using basic auth: the username does not matter and the the password should equal the configured token
|
|
|
|
// When using bearer auth: set the "Authorization" header to "Bearer your-token-here"
|
|
|
|
func authMiddleware(next http.Handler) http.Handler {
|
2023-11-17 18:24:12 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if cfg.HatsToken == "" { // No token required
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-12-08 23:37:54 +00:00
|
|
|
_, p, ok := r.BasicAuth()
|
|
|
|
|
|
|
|
if ok && p == cfg.HatsToken {
|
|
|
|
next.ServeHTTP(w, r)
|
2023-11-17 18:24:12 +00:00
|
|
|
return
|
|
|
|
}
|
2023-12-08 23:37:54 +00:00
|
|
|
|
|
|
|
authHeaderPars := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
|
|
|
if len(authHeaderPars) > 1 && strings.EqualFold(authHeaderPars[0], "bearer") && authHeaderPars[1] == cfg.HatsToken {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.Warn("Unauthorized request", "method", r.Method, "path", r.URL.Path, "address", r.RemoteAddr)
|
|
|
|
http.Error(w, "Bearer authorization header doesn't match configured token", http.StatusUnauthorized)
|
2023-11-17 18:24:12 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func loggerMiddleware(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
logger.Debug(fmt.Sprintf("%s %s", r.Method, r.URL.Path), "method", r.Method, "path", r.URL.Path, "address", r.RemoteAddr)
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// HOME ASSISTANT ENTITIES
|
|
|
|
|
|
|
|
func getEntityStateHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
entityId := chi.URLParam(r, "entityId")
|
2023-10-16 16:54:09 +00:00
|
|
|
full := r.URL.Query().Get("full") == "true"
|
2023-11-17 19:15:15 +00:00
|
|
|
l := logger.With("endpoint", "GET /api/state/{entityId}", "entityId", entityId, "full", full)
|
2023-10-16 16:54:09 +00:00
|
|
|
|
|
|
|
if !full {
|
2023-11-17 19:15:15 +00:00
|
|
|
l.Debug("Getting state from KV store")
|
2023-10-16 16:54:09 +00:00
|
|
|
kvVal, err := nats.GetKeyValue(fmt.Sprintf("%s.%s", HA_STATE_PREFIX, entityId))
|
|
|
|
if err == nil && len(kvVal) > 0 {
|
2023-11-17 19:15:15 +00:00
|
|
|
l.Debug("Returning", "value", string(kvVal))
|
|
|
|
render.PlainText(w, r, string(kvVal))
|
2023-10-16 16:54:09 +00:00
|
|
|
return
|
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
2023-11-17 19:15:15 +00:00
|
|
|
l.Debug("Getting state from Home Assistant")
|
2023-10-13 20:31:23 +00:00
|
|
|
data, err := haClient.GetState(entityId)
|
|
|
|
if err != nil {
|
2023-11-17 19:15:15 +00:00
|
|
|
l.Error("Error getting state from Home Assistant", "error", err)
|
2023-10-13 20:31:23 +00:00
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
nats.SetKeyValueString(fmt.Sprintf("%s.%s", HA_STATE_PREFIX, entityId), data.State)
|
2023-10-16 16:54:09 +00:00
|
|
|
if full {
|
|
|
|
render.JSON(w, r, data)
|
|
|
|
} else {
|
|
|
|
render.PlainText(w, r, data.State)
|
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func setEntityStateHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
entityId := chi.URLParam(r, "entityId")
|
|
|
|
service := chi.URLParam(r, "service")
|
2023-11-07 23:09:10 +00:00
|
|
|
domain := r.URL.Query().Get("domain")
|
2023-12-08 23:37:54 +00:00
|
|
|
|
2023-11-25 06:56:40 +00:00
|
|
|
l := logger.With("endpoint", "POST /api/state/{entityId}/{service}", "entityId", entityId, "service", service, "domain", domain)
|
2023-10-13 20:31:23 +00:00
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
var extras map[string]any
|
2023-10-13 20:31:23 +00:00
|
|
|
err := render.DecodeJSON(r.Body, &extras)
|
2023-11-20 21:55:25 +00:00
|
|
|
if err != nil {
|
2023-11-25 07:03:46 +00:00
|
|
|
b, _ := io.ReadAll(r.Body)
|
|
|
|
l.Error("Error decoding JSON body", "error", err, "body", string(b))
|
2023-11-20 21:55:25 +00:00
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
var haErr error
|
|
|
|
if err == nil && len(extras) > 0 {
|
2023-11-07 23:09:10 +00:00
|
|
|
if domain != "" {
|
2023-11-25 06:56:40 +00:00
|
|
|
l.Debug("Calling service manually", "extras", extras)
|
2023-11-07 23:09:10 +00:00
|
|
|
haErr = haClient.CallServiceManual(domain, entityId, service, extras)
|
|
|
|
} else {
|
2023-11-25 06:56:40 +00:00
|
|
|
l.Debug("Calling service", "extras", extras)
|
2023-11-07 23:09:10 +00:00
|
|
|
haErr = haClient.CallService(entityId, service, extras)
|
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
} else {
|
2023-11-07 23:09:10 +00:00
|
|
|
if domain != "" {
|
2023-11-25 06:56:40 +00:00
|
|
|
l.Debug("Calling service manually (without extras)")
|
2023-11-07 23:09:10 +00:00
|
|
|
haErr = haClient.CallServiceManual(domain, entityId, service)
|
|
|
|
} else {
|
2023-11-25 06:56:40 +00:00
|
|
|
l.Debug("Calling service (without extras)")
|
2023-11-07 23:09:10 +00:00
|
|
|
haErr = haClient.CallService(entityId, service)
|
|
|
|
}
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if haErr != nil {
|
2023-11-25 06:56:40 +00:00
|
|
|
l.Error("Error setting state", "error", haErr)
|
2023-10-13 20:31:23 +00:00
|
|
|
http.Error(w, fmt.Sprintf("error proxying request: %s", haErr.Error()), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
render.Status(r, http.StatusOK)
|
|
|
|
render.PlainText(w, r, "OK")
|
|
|
|
}
|
|
|
|
|
|
|
|
// TIMERS
|
|
|
|
|
|
|
|
func getTimerHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
timerName := chi.URLParam(r, "timerName")
|
|
|
|
|
|
|
|
timer, err := nats.GetTimer(timerName)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Unable to get timer: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
render.PlainText(w, r, timer.ToString())
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
type StartTimerData struct {
|
2023-10-13 20:31:23 +00:00
|
|
|
Duration string `json:"duration"`
|
|
|
|
Force bool `json:"force"`
|
|
|
|
}
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
func startTimerHandler(w http.ResponseWriter, r *http.Request) {
|
2023-10-13 20:31:23 +00:00
|
|
|
timerName := chi.URLParam(r, "timerName")
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
data := &StartTimerData{}
|
2023-10-13 20:31:23 +00:00
|
|
|
if err := render.DecodeJSON(r.Body, data); err != nil {
|
|
|
|
http.Error(w, "Unable to parse timer data", http.StatusNotAcceptable)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
timer, err := nats.GetTimer(timerName)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Unable to get timer: "+err.Error(), http.StatusInternalServerError)
|
2023-10-13 20:31:23 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-10-18 18:35:46 +00:00
|
|
|
if data.Duration == "" {
|
|
|
|
data.Duration = timer.Duration.String()
|
|
|
|
}
|
|
|
|
|
2023-10-13 20:31:23 +00:00
|
|
|
if data.Force {
|
2023-10-18 18:35:46 +00:00
|
|
|
timer.Activate(data.Duration)
|
2023-10-13 20:31:23 +00:00
|
|
|
} else {
|
2023-10-18 18:35:46 +00:00
|
|
|
timer.ActivateIfNotAlready(data.Duration)
|
2023-10-13 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
getTimerHandler(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func deleteTimerHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
timerName := chi.URLParam(r, "timerName")
|
|
|
|
|
|
|
|
timer, err := nats.GetTimer(timerName)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Unable to get timer: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
timer.Cancel()
|
|
|
|
render.PlainText(w, r, "OK")
|
|
|
|
}
|
|
|
|
|
|
|
|
// SCHEDULES
|
|
|
|
|
|
|
|
func getScheduleHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
scheduleName := chi.URLParam(r, "scheduleName")
|
|
|
|
|
|
|
|
schedule, err := nats.GetSchedule(scheduleName)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Unable to get schedule: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
render.PlainText(w, r, string(schedule.GetNext()))
|
|
|
|
}
|
|
|
|
|
|
|
|
type CreateScheduleData struct {
|
|
|
|
Cron string `json:"cron"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func createScheduleHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
scheduleName := chi.URLParam(r, "scheduleName")
|
|
|
|
|
|
|
|
data := &CreateScheduleData{}
|
|
|
|
if err := render.DecodeJSON(r.Body, data); err != nil {
|
|
|
|
http.Error(w, "Unable to parse schedule data", http.StatusNotAcceptable)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if data.Cron == "" {
|
|
|
|
http.Error(w, "cron required", http.StatusNotAcceptable)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
schedule := nats.NewSchedule(scheduleName, data.Cron)
|
|
|
|
schedule.Activate()
|
|
|
|
|
|
|
|
getScheduleHandler(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func deleteScheduleHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
scheduleName := chi.URLParam(r, "scheduleName")
|
|
|
|
|
|
|
|
schedule, err := nats.GetSchedule(scheduleName)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, "Unable to get schedule: "+err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
schedule.Cancel()
|
|
|
|
render.PlainText(w, r, "OK")
|
|
|
|
}
|
2023-11-08 23:12:04 +00:00
|
|
|
|
|
|
|
// NTFY
|
|
|
|
|
|
|
|
func postNtfyHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
data := &ntfyPkg.Message{}
|
|
|
|
if err := render.DecodeJSON(r.Body, data); err != nil {
|
|
|
|
http.Error(w, "Unable to parse message data", http.StatusNotAcceptable)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := ntfy.Send(*data); err != nil {
|
|
|
|
http.Error(w, "Unable to send message", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
render.PlainText(w, r, "OK")
|
|
|
|
}
|
2023-11-13 21:54:07 +00:00
|
|
|
|
|
|
|
// Command
|
|
|
|
|
|
|
|
func postCommandHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
commandName := chi.URLParam(r, "commandName")
|
|
|
|
|
2023-11-20 19:24:33 +00:00
|
|
|
body, err := io.ReadAll(r.Body)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("Error reading request body", "error", err, "url", r.URL.String())
|
2023-11-13 21:54:07 +00:00
|
|
|
}
|
2023-11-20 19:24:33 +00:00
|
|
|
nats.Publish(fmt.Sprintf("command.%s", commandName), body)
|
|
|
|
render.PlainText(w, r, "OK")
|
2023-11-13 21:54:07 +00:00
|
|
|
}
|