79 lines
No EOL
2.2 KiB
Go
79 lines
No EOL
2.2 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/go-resty/resty/v2"
|
|
"github.com/google/uuid"
|
|
"jonasled.dev/jonasled/go-libs/log"
|
|
"jonasled.dev/jonasled/shelly-smoke-alamos/configuration"
|
|
)
|
|
|
|
// @Summary Webhook
|
|
// @Description Webhook for smoke detector to trigger alarm
|
|
// @Tags webhook
|
|
// @Success 200
|
|
// @Param secret path string true "Smoke Detector secret"
|
|
// @Router /api/webhook/{secret} [get]
|
|
func initWebhook() {
|
|
conf := configuration.ReadConfig()
|
|
R.GET("/api/webhook/:secret", func(ctx *gin.Context) {
|
|
triggerAlamosWebhook(ctx, false, conf)
|
|
})
|
|
R.GET("/api/webhook/:secret/test", func(ctx *gin.Context) {
|
|
triggerAlamosWebhook(ctx, true, conf)
|
|
})
|
|
|
|
}
|
|
|
|
|
|
// @Summary Webhook Test
|
|
// @Description Webhook for smoke detector test function
|
|
// @Tags webhook
|
|
// @Success 200
|
|
// @Param secret path string true "Smoke Detector secret"
|
|
// @Router /api/webhook/{secret}/test [get]
|
|
func triggerAlamosWebhook(ctx *gin.Context, test bool, conf configuration.Config) {
|
|
id := ctx.Param("secret")
|
|
for _, sensor := range conf.SmokeDetectors {
|
|
if sensor.ID == id {
|
|
keyword := conf.Targets[sensor.Target].Keyword
|
|
if test {
|
|
keyword = conf.Targets[sensor.Target].KeywordTest
|
|
}
|
|
|
|
log.Log.Debug("Set REST baseurl to ", conf.Targets[sensor.Target].URL)
|
|
client := resty.New().SetBaseURL(conf.Targets[sensor.Target].URL)
|
|
|
|
resp, err := client.R().SetBody(&AlamosAlarm{
|
|
Type: "ALARM",
|
|
Sender: sensor.Name,
|
|
Authorization: conf.Targets[sensor.Target].Secret,
|
|
Timestamp: time.Now(),
|
|
Data: AlamosAlarmData{
|
|
ExternalID: uuid.New().String(),
|
|
Keyword: keyword,
|
|
Message: []string{sensor.Name},
|
|
},
|
|
}).Post("rest/external/http/alarm/v2")
|
|
if err != nil {
|
|
log.Log.Error("Unexpected error from Alamos API call ", err.Error())
|
|
ctx.String(http.StatusInternalServerError, "Something went wrong")
|
|
return
|
|
}
|
|
if resp.StatusCode() != 200 {
|
|
log.Log.Error("Unexpected status from Alamos API call ", resp.StatusCode())
|
|
ctx.String(http.StatusInternalServerError, "Something went wrong")
|
|
return
|
|
}
|
|
|
|
ctx.String(http.StatusOK, "OK")
|
|
return
|
|
|
|
}
|
|
}
|
|
ctx.String(http.StatusNotFound, "Not found")
|
|
|
|
} |