blasphem/pkg/frontend/frontend.go

83 lines
1.5 KiB
Go
Raw Permalink Normal View History

2022-09-25 14:07:47 -04:00
package frontend
import (
2022-12-21 13:22:18 -05:00
"context"
2022-09-25 14:07:47 -04:00
"embed"
2022-10-29 10:39:06 -04:00
"io"
2022-09-30 14:37:40 -04:00
"io/fs"
"net/http"
2022-12-20 13:16:30 -05:00
"sync"
"dynatron.me/x/blasphem/pkg/blas"
2022-12-20 16:26:04 -05:00
"dynatron.me/x/blasphem/pkg/blas/core"
"dynatron.me/x/blasphem/pkg/components"
2022-10-29 10:39:06 -04:00
"github.com/labstack/echo/v4"
2022-09-25 14:07:47 -04:00
)
2022-12-20 13:16:30 -05:00
const FrontendKey = "frontend"
2022-09-25 14:07:47 -04:00
//go:embed frontend/hass_frontend
2022-09-30 14:37:40 -04:00
var root embed.FS
2022-12-20 13:16:30 -05:00
type Frontend struct {
fsHandler echo.HandlerFunc
rootFS fs.FS
routeInstall sync.Once
}
2022-09-30 14:37:40 -04:00
2022-12-20 13:16:30 -05:00
func (fe *Frontend) InstallRoutes(e *echo.Echo) {
fe.routeInstall.Do(func() {
e.GET("/*", fe.fsHandler)
2022-12-20 16:26:04 -05:00
e.GET("/auth/authorize", fe.AliasHandler("authorize.html"))
2022-12-20 13:16:30 -05:00
})
}
2022-10-29 10:39:06 -04:00
2022-12-20 13:16:30 -05:00
func (fe *Frontend) AliasHandler(toFile string) echo.HandlerFunc {
2022-10-29 10:39:06 -04:00
return func(c echo.Context) error {
2022-12-20 13:16:30 -05:00
file, err := fe.rootFS.Open(toFile)
2022-10-29 10:39:06 -04:00
if err != nil {
return err
}
defer file.Close()
b, err := io.ReadAll(file)
if err != nil {
return err
}
return c.HTML(http.StatusOK, string(b))
}
}
2022-12-20 13:16:30 -05:00
func (*Frontend) Shutdown() {}
2022-12-20 20:30:58 -05:00
func newData(_ []string) interface{} {
return map[string]interface{}{}
}
2022-12-21 13:22:18 -05:00
func wsHand(ctx context.Context, wss core.WebSocketSession, msgID int, cmd []string, msg interface{}) error {
2022-12-20 20:30:58 -05:00
return nil
}
func Setup(b core.Blas) (components.Component, error) {
2022-12-20 13:16:30 -05:00
fe := &Frontend{}
2022-09-30 14:37:40 -04:00
var err error
2022-11-11 18:02:52 -05:00
2022-12-20 13:16:30 -05:00
fe.rootFS, err = fs.Sub(root, "frontend/hass_frontend")
2022-09-30 14:37:40 -04:00
if err != nil {
2022-12-20 13:16:30 -05:00
return nil, err
2022-09-30 14:37:40 -04:00
}
2022-12-20 13:16:30 -05:00
fe.fsHandler = echo.StaticDirectoryHandler(fe.rootFS, false)
2022-12-20 20:30:58 -05:00
b.RegisterWSCommand("frontend", wsHand, newData)
2022-12-20 13:16:30 -05:00
return fe, nil
}
func init() {
2022-12-20 13:31:31 -05:00
blas.Register(FrontendKey, Setup)
2022-09-30 14:37:40 -04:00
}