144 lines
2.1 KiB
Go
144 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"github.com/gorilla/websocket"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/gommon/log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
var upgrader = websocket.Upgrader{}
|
|
|
|
func helloWorld(c echo.Context) error {
|
|
return c.JSON(http.StatusOK, "Hello world!")
|
|
}
|
|
|
|
func getOpened(c echo.Context) error {
|
|
mut.Lock()
|
|
o := opened
|
|
mut.Unlock()
|
|
|
|
return c.JSON(http.StatusOK, o)
|
|
}
|
|
|
|
func getOpenedWs(c echo.Context) error {
|
|
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = ws.Close() }()
|
|
|
|
// empty the channel
|
|
emptied := false
|
|
for !emptied {
|
|
select {
|
|
case <-openedChange:
|
|
default:
|
|
emptied = true
|
|
}
|
|
}
|
|
|
|
for {
|
|
<-openedChange
|
|
mut.Lock()
|
|
|
|
err = ws.WriteJSON(opened)
|
|
mut.Unlock()
|
|
|
|
if err != nil {
|
|
log.Error(err)
|
|
break
|
|
}
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func setOpened(c echo.Context) error {
|
|
var data ChangeOpenReq
|
|
err := c.Bind(&data)
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
if data.Opened == opened {
|
|
return c.NoContent(http.StatusOK)
|
|
}
|
|
|
|
mut.Lock()
|
|
opened = data.Opened
|
|
if locked && alerts {
|
|
var action string
|
|
if opened {
|
|
action = "opened"
|
|
} else {
|
|
action = "closed"
|
|
}
|
|
|
|
go sendAlert(action)
|
|
}
|
|
|
|
openedChange <- 0
|
|
mut.Unlock()
|
|
return c.NoContent(http.StatusOK)
|
|
}
|
|
|
|
func getLocked(c echo.Context) error {
|
|
mut.Lock()
|
|
l := locked
|
|
mut.Unlock()
|
|
|
|
return c.JSON(http.StatusOK, l)
|
|
}
|
|
|
|
func setLocked(c echo.Context) error {
|
|
var data ChangeLockReq
|
|
err := c.Bind(&data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if data.Locked == locked {
|
|
return c.NoContent(http.StatusOK)
|
|
}
|
|
|
|
mut.Lock()
|
|
locked = data.Locked
|
|
mut.Unlock()
|
|
|
|
return c.NoContent(http.StatusOK)
|
|
}
|
|
|
|
func getAlerts(c echo.Context) error {
|
|
mut.Lock()
|
|
a := alerts
|
|
mut.Unlock()
|
|
|
|
return c.JSON(http.StatusOK, a)
|
|
}
|
|
|
|
func setAlerts(c echo.Context) error {
|
|
var data ChangeAlertReq
|
|
err := c.Bind(&data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if data.For > 0 {
|
|
go func() {
|
|
time.Sleep(time.Duration(data.For) * time.Second)
|
|
|
|
mut.Lock()
|
|
alerts = !data.Alerts
|
|
mut.Unlock()
|
|
}()
|
|
}
|
|
|
|
mut.Lock()
|
|
alerts = data.Alerts
|
|
mut.Unlock()
|
|
|
|
return c.NoContent(http.StatusOK)
|
|
}
|