2022-09-25 14:07:47 -04:00
|
|
|
package frontend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"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-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-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 13:31:31 -05:00
|
|
|
func Setup(_ blas.Core) (blas.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)
|
|
|
|
|
|
|
|
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
|
|
|
}
|