From 71f152ef2aa5788741be5806539e2da219fcde00 Mon Sep 17 00:00:00 2001 From: 2mal3 <56305732+2mal3@users.noreply.github.com> Date: Fri, 30 Jan 2026 15:26:57 +0100 Subject: [PATCH] refactor(display): use chrome devtools protocol (#38) --- control/frontend/src/lib/ts/api_handler.ts | 11 ++ .../frontend/src/routes/ControlView.svelte | 5 +- control/main.go | 2 +- {shared => control}/open_browser.go | 15 +- display/README.md | 6 + display/browser/main.go | 72 +++++++ display/go.mod | 13 +- display/go.sum | 18 ++ display/main.go | 14 +- display/pkg/file_handler.go | 75 -------- display/pkg/main.go | 53 +++--- display/pkg/main.templ | 148 +++++++++++++++ display/pkg/open_file.go | 108 +++++++++++ display/pkg/start_screen.go | 117 ++++++++++++ display/requests/openWebsite.bru | 22 +++ display/web/embed.go | 12 -- display/web/main.go | 178 ++---------------- display/web/main.templ | 123 ------------ display/web/sse.go | 75 -------- display/web/static/htmx-ext-sse.min.js | 1 - display/web/static/htmx.min.js | 1 - go.work.sum | 2 + nixos/configuration.nix | 1 - shared/embed.go | 2 +- 24 files changed, 570 insertions(+), 504 deletions(-) rename {shared => control}/open_browser.go (69%) create mode 100644 display/browser/main.go delete mode 100644 display/pkg/file_handler.go create mode 100644 display/pkg/main.templ create mode 100644 display/pkg/open_file.go create mode 100644 display/pkg/start_screen.go create mode 100644 display/requests/openWebsite.bru delete mode 100644 display/web/embed.go delete mode 100644 display/web/main.templ delete mode 100644 display/web/sse.go delete mode 100644 display/web/static/htmx-ext-sse.min.js delete mode 100644 display/web/static/htmx.min.js diff --git a/control/frontend/src/lib/ts/api_handler.ts b/control/frontend/src/lib/ts/api_handler.ts index e9d9317..a282ab5 100755 --- a/control/frontend/src/lib/ts/api_handler.ts +++ b/control/frontend/src/lib/ts/api_handler.ts @@ -51,6 +51,17 @@ export async function show_html(ip: string, html: string): Promise { await request_display(ip, '/showHTML', options); } +export async function open_website(ip: string, url: string): Promise { + const options = { + method: 'PATCH', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + url: url + }) + }; + await request_display(ip, '/openWebsite', options); +} + export async function get_file_data( ip: string, path: string diff --git a/control/frontend/src/routes/ControlView.svelte b/control/frontend/src/routes/ControlView.svelte index d0161fb..a169236 100644 --- a/control/frontend/src/routes/ControlView.svelte +++ b/control/frontend/src/routes/ControlView.svelte @@ -21,7 +21,8 @@ show_blackscreen, shutdown, startup, - show_html + show_html, + open_website } from '$lib/ts/api_handler'; import { get_display_by_id, @@ -144,7 +145,7 @@ async function send_website() { popup_content.open = false; await run_on_all_selected_displays((d) => - show_html(d.ip, ``) + open_website(d.ip, website_url) ); } diff --git a/control/main.go b/control/main.go index 4b35913..261e3c7 100644 --- a/control/main.go +++ b/control/main.go @@ -64,7 +64,7 @@ func main() { os.Exit(1) } }() - err = shared.OpenBrowserWindow("http://localhost:"+port, false, "control") + err = openBrowserWindow("http://localhost:" + port) if err != nil { slog.Error("Failed to open browser window", "error", err) os.Exit(1) diff --git a/shared/open_browser.go b/control/open_browser.go similarity index 69% rename from shared/open_browser.go rename to control/open_browser.go index 9f9e678..2d45d58 100644 --- a/shared/open_browser.go +++ b/control/open_browser.go @@ -1,4 +1,4 @@ -package shared +package main import ( "errors" @@ -6,35 +6,30 @@ import ( "os" "os/exec" "path/filepath" + "plg-mudics/shared" ) -func OpenBrowserWindow(url string, fullscreen bool, profile string) error { +func openBrowserWindow(url string) error { bins := []string{"chromium", "chromium-browser"} home, err := os.UserHomeDir() if err != nil { return fmt.Errorf("unable to determine user home directory: %w", err) } - browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", fmt.Sprintf("browser-%s", profile)) + browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", "browser-control") if err := os.MkdirAll(browserProfileDirPath, os.ModePerm); err != nil { return fmt.Errorf("failed to create local config directory: %w", err) } args := []string{ fmt.Sprintf("--app=%s", url), - "--autoplay-policy=no-user-gesture-required", fmt.Sprintf("--user-data-dir=%s", browserProfileDirPath), - "--allow-running-insecure-content", - "--disable-features=XFrameOptions", - } - if fullscreen { - args = append(args, "--start-fullscreen") } errs := []string{} for _, bin := range bins { cmd := exec.Command(bin, args...) - commandOutput := RunShellCommand(cmd) + commandOutput := shared.RunShellCommand(cmd) if commandOutput.ExitCode == 0 { return nil } diff --git a/display/README.md b/display/README.md index 1c6b335..f884b7c 100644 --- a/display/README.md +++ b/display/README.md @@ -62,6 +62,12 @@ Even when the command itself fails. The screenshot as binary in the response body. +## PATCH `/openWebsite` + +### Request Body + +- `url`: string + ## POST `/file/` - Upload File ### Responses diff --git a/display/browser/main.go b/display/browser/main.go new file mode 100644 index 0000000..4a4ef70 --- /dev/null +++ b/display/browser/main.go @@ -0,0 +1,72 @@ +package browser + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/chromedp/chromedp" +) + +var Browser BrowserType = BrowserType{} + +type BrowserType struct { + Ctx context.Context + Cancel context.CancelFunc +} + +func (b *BrowserType) Init() error { + home, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("unable to determine user home directory: %w", err) + } + browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", "browser-display") + if err := os.MkdirAll(browserProfileDirPath, os.ModePerm); err != nil { + return fmt.Errorf("failed to create local config directory: %w", err) + } + + opts := []chromedp.ExecAllocatorOption{ + chromedp.Flag("headless", false), + chromedp.Flag("app", "http://example.com"), // app mode prevents a few unwanted features of chrome, the start url is directly overwritten + chromedp.Flag("start-fullscreen", true), + chromedp.Flag("hide-scrollbars", true), + chromedp.Flag("allow-file-access-from-files", true), + chromedp.Flag("user-data-dir", browserProfileDirPath), + chromedp.Flag("autoplay-policy", "no-user-gesture-required"), + } + + initCtx, _ := chromedp.NewExecAllocator(context.Background(), opts...) + b.Ctx, b.Cancel = chromedp.NewContext(initCtx) + + return nil +} + +func (b *BrowserType) OpenPage(url string) { + chromedp.Run(b.Ctx, chromedp.Navigate(url)) +} + +// Yes, we need that trick with creating a temp file and not directly sending html since +// chrome only allows us to access local files via other local files +func (b *BrowserType) OpenHTML(html string) error { + var err error + + tempFile, err := os.CreateTemp("", "mudics-*.html") + if err != nil { + return fmt.Errorf("could not create tempfile: %w", err) + } + defer tempFile.Close() + + _, err = tempFile.WriteString(html) + if err != nil { + return fmt.Errorf("could not write to tempfile: %w", err) + } + + chromedp.Run(b.Ctx, chromedp.Navigate("file://"+tempFile.Name())) + + return nil +} + +func (b *BrowserType) OpenPDF(path string) { + b.OpenPage("file://" + path + "#toolbar=0&view=Fit") +} diff --git a/display/go.mod b/display/go.mod index 78209ca..b5291b6 100644 --- a/display/go.mod +++ b/display/go.mod @@ -1,9 +1,10 @@ module plg-mudics/display -go 1.24.4 +go 1.25 require ( - github.com/a-h/templ v0.3.960 + github.com/a-h/templ v0.3.977 + github.com/chromedp/chromedp v0.14.2 github.com/gabriel-vasile/mimetype v1.4.11 github.com/labstack/echo/v4 v4.15.0 github.com/micmonay/keybd_event v1.1.2 @@ -14,9 +15,15 @@ require ( github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect github.com/andybalholm/brotli v1.1.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d // indirect + github.com/chromedp/sysutil v1.1.0 // indirect github.com/cli/browser v1.3.0 // indirect github.com/fatih/color v1.16.0 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gobwas/ws v1.4.0 // indirect github.com/labstack/gommon v0.4.2 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -27,7 +34,7 @@ require ( golang.org/x/mod v0.30.0 // indirect golang.org/x/net v0.48.0 // indirect golang.org/x/sync v0.19.0 // indirect - golang.org/x/sys v0.39.0 // indirect + golang.org/x/sys v0.40.0 // indirect golang.org/x/text v0.32.0 // indirect golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.39.0 // indirect diff --git a/display/go.sum b/display/go.sum index 4f13d10..28a87f5 100644 --- a/display/go.sum +++ b/display/go.sum @@ -2,10 +2,18 @@ github.com/a-h/parse v0.0.0-20250122154542-74294addb73e h1:HjVbSQHy+dnlS6C3XajZ6 github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ= github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM= github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo= +github.com/a-h/templ v0.3.977 h1:kiKAPXTZE2Iaf8JbtM21r54A8bCNsncrfnokZZSrSDg= +github.com/a-h/templ v0.3.977/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo= github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU= +github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k= +github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM= +github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo= +github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM= +github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8= github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo= github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -16,6 +24,14 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik= github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU= +github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs= +github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA= @@ -64,6 +80,8 @@ golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= diff --git a/display/main.go b/display/main.go index ba4ab5c..a2f5792 100644 --- a/display/main.go +++ b/display/main.go @@ -4,9 +4,9 @@ import ( "log/slog" "os" + "plg-mudics/display/browser" "plg-mudics/display/pkg" "plg-mudics/display/web" - "plg-mudics/shared" ) //go:generate go tool templ generate @@ -25,10 +25,10 @@ func main() { // the order is important, the open browser command exitsts as soon as the winodw is closed // and since its the last action in the main go func all other goroutines (e.g. the webserver) are killed - go web.StartWebServer(shared.Version, port) - err = shared.OpenBrowserWindow("http://localhost:"+port, true, "display") - if err != nil { - slog.Error("Failed to open browser window", "error", err) - os.Exit(1) - } + go web.StartWebServer(port) + + browser.Browser.Init() + pkg.OpenStartScreen() + defer browser.Browser.Cancel() + <-browser.Browser.Ctx.Done() } diff --git a/display/pkg/file_handler.go b/display/pkg/file_handler.go deleted file mode 100644 index c751f15..0000000 --- a/display/pkg/file_handler.go +++ /dev/null @@ -1,75 +0,0 @@ -package pkg - -import ( - "fmt" - "log/slog" - "os" - "os/exec" - "path/filepath" - "plg-mudics/shared" - "syscall" - - "github.com/gabriel-vasile/mimetype" -) - -var FileHandler fileHandler = fileHandler{} - -type fileHandler struct { - runningProgram *exec.Cmd -} - -func (fh *fileHandler) OpenFile(path string) error { - var err error - - mType, err := mimetype.DetectFile(path) - if err != nil { - return fmt.Errorf("failed to detect mime type: %w", err) - } - - tempDirPath, err := os.MkdirTemp("", "plg-mudics-program-profile-") - if err != nil { - return fmt.Errorf("failed to create temporary profile directory: %w", err) - } - - err = fh.CloseRunningProgram() - if err != nil { - return err - } - - switch mType.String() { - case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation": - // yes, we need this weird workaround to delete lock files since libreoffice - // doesn't expose an option to ignore them or prevent their creation - // the --view argument for some reason doesn't work with --show - parent := filepath.Dir(path) - cmd := exec.Command("find", parent, "-name", ".~lock*", "-type", "f", "-delete") - result := shared.RunShellCommand(cmd) - if result.ExitCode != 0 { - slog.Warn("could not remove lock files", "path", parent, "stderr", result.Stderr, "exitCode", result.ExitCode) - } - - fh.runningProgram = exec.Command("soffice", "--show", path, "--nologo", "--norestore", fmt.Sprintf("-env:UserInstallation=file://%s", tempDirPath)) - case "application/pdf": - fh.runningProgram = exec.Command("xreader", path, "--presentation") - default: - return fmt.Errorf("unsupported file type: %s", mType.String()) - } - - fh.runningProgram.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - - result := shared.RunShellCommandNonBlocking(fh.runningProgram) - if result.ExitCode != 0 { - return fmt.Errorf("could not open pdf: %s (%d)", result.Stderr, result.ExitCode) - } - - return nil -} - -func (fh *fileHandler) CloseRunningProgram() error { - if fh.runningProgram == nil { - return nil - } - err := syscall.Kill(-fh.runningProgram.Process.Pid, syscall.SIGTERM) - fh.runningProgram = nil - return err -} diff --git a/display/pkg/main.go b/display/pkg/main.go index 3e01841..70faaa5 100644 --- a/display/pkg/main.go +++ b/display/pkg/main.go @@ -1,49 +1,21 @@ package pkg import ( + "bytes" + "context" "errors" "fmt" - "net" + "log/slog" "os" "os/exec" "path/filepath" "strings" "time" + "plg-mudics/display/browser" "plg-mudics/shared" ) -func GetDeviceIp() (string, error) { - addrs, err := net.InterfaceAddrs() - if err != nil { - return "", fmt.Errorf("failed to get network interfaces: %w", err) - } - for _, addr := range addrs { - ipNet, ok := addr.(*net.IPNet) - if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil { - return ipNet.IP.String(), nil - } - } - - return "", fmt.Errorf("no suitable IP address found") -} - -func GetDeviceMac() (string, error) { - interfaces, err := net.Interfaces() - if err != nil { - return "", fmt.Errorf("failed to get network interfaces: %w", err) - } - - for _, interf := range interfaces { - mac := interf.HardwareAddr.String() - if mac != "" { - return mac, nil - } - } - - return "", fmt.Errorf("no suitable MAC address found") -} - func TakeScreenshot() (string, error) { tempFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("screenshot_%d.png", time.Now().Unix())) @@ -106,3 +78,20 @@ func ResolveStorageFilePath(pathParam string) (string, bool, error) { return fullPath, true, nil } + +func ShowHTML(html string) error { + ResetView() + + var templateBuffer bytes.Buffer + htmlTemplate(html).Render(context.Background(), &templateBuffer) + err := browser.Browser.OpenHTML(templateBuffer.String()) + + return err +} + +func ResetView() { + err := fileHandler.closeRunningProgram() + if err != nil { + slog.Error("Failed to close running program", "error", err) + } +} diff --git a/display/pkg/main.templ b/display/pkg/main.templ new file mode 100644 index 0000000..9c54103 --- /dev/null +++ b/display/pkg/main.templ @@ -0,0 +1,148 @@ +package pkg + +templ basicTemplate() { + + + + + + PLG MuDiCS Display + + + + { children... } + + +} + +templ videoTemplate(path string) { + @basicTemplate() { + + } +} + +templ htmlTemplate(html string) { + @basicTemplate() { + @templ.Raw(html) + } +} + +templ imageTemplate(path string) { + @basicTemplate() { + + } +} + +templ deviceInfoTemplate(ip string, mac string, showQR bool) { + @basicTemplate() { +
+
+ { ip } + { mac } +
+ if showQR { +
+
+ QR-Code +
+
+ } +
+ + } +} + +templ startScreenTemplate(splashScreenHtml string, ip string, mac string, qrPath string) { + @basicTemplate() { +
+
+ { ip } + { mac } +
+ if qrPath != "" { +
+
+ QR-Code +
+
+ } +
+ @templ.Raw(splashScreenHtml) + + } +} diff --git a/display/pkg/open_file.go b/display/pkg/open_file.go new file mode 100644 index 0000000..5448d47 --- /dev/null +++ b/display/pkg/open_file.go @@ -0,0 +1,108 @@ +package pkg + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "os" + "os/exec" + "path/filepath" + "plg-mudics/shared" + "syscall" + + "github.com/gabriel-vasile/mimetype" + + "plg-mudics/display/browser" +) + +var fileHandler fileHandlerType = fileHandlerType{} + +type fileHandlerType struct { + runningProgram *exec.Cmd +} + +func OpenFile(path string) error { + ResetView() + + mType, err := mimetype.DetectFile(path) + if err != nil { + slog.Error("Failed to detect mime type", "file", path, "error", err) + } + + switch mType.String() { + case "video/mp4": + var templateBuffer bytes.Buffer + videoTemplate(path).Render(context.Background(), &templateBuffer) + browser.Browser.OpenHTML(templateBuffer.String()) + case "image/jpeg", "image/png", "image/gif": + var templateBuffer bytes.Buffer + imageTemplate(path).Render(context.Background(), &templateBuffer) + browser.Browser.OpenHTML(templateBuffer.String()) + case "application/pdf": + browser.Browser.OpenPDF(path) + case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation": + err = fileHandler.openFileWithApp(path) + default: + return fmt.Errorf("unsupported file type: %s", mType.String()) + } + + return nil +} + +func (fh *fileHandlerType) openFileWithApp(path string) error { + var err error + + mType, err := mimetype.DetectFile(path) + if err != nil { + return fmt.Errorf("failed to detect mime type: %w", err) + } + + switch mType.String() { + case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation": + err = fh.openLibreoffice(path) + if err != nil { + return err + } + default: + return fmt.Errorf("unsupported file type: %s", mType.String()) + } + + fh.runningProgram.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + + result := shared.RunShellCommandNonBlocking(fh.runningProgram) + if result.ExitCode != 0 { + return fmt.Errorf("could not open pdf: %s (%d)", result.Stderr, result.ExitCode) + } + + return nil +} + +func (fh *fileHandlerType) openLibreoffice(path string) error { + // yes, we need this weird workaround to delete lock files since libreoffice + // doesn't expose an option to ignore them or prevent their creation + // the --view argument for some reason doesn't work with --show + parent := filepath.Dir(path) + cmd := exec.Command("find", parent, "-name", ".~lock*", "-type", "f", "-delete") + result := shared.RunShellCommand(cmd) + if result.ExitCode != 0 { + slog.Warn("could not remove lock files", "path", parent, "stderr", result.Stderr, "exitCode", result.ExitCode) + } + + tempDirPath, err := os.MkdirTemp("", "plg-mudics-program-profile-") + if err != nil { + return fmt.Errorf("failed to create temporary profile directory: %w", err) + } + fh.runningProgram = exec.Command("soffice", "--show", path, "--nologo", "--norestore", fmt.Sprintf("-env:UserInstallation=file://%s", tempDirPath)) + + return nil +} + +func (fh *fileHandlerType) closeRunningProgram() error { + if fh.runningProgram == nil { + return nil + } + err := syscall.Kill(-fh.runningProgram.Process.Pid, syscall.SIGTERM) + fh.runningProgram = nil + return err +} diff --git a/display/pkg/start_screen.go b/display/pkg/start_screen.go new file mode 100644 index 0000000..dfc3514 --- /dev/null +++ b/display/pkg/start_screen.go @@ -0,0 +1,117 @@ +package pkg + +import ( + "bytes" + "context" + "fmt" + "image/color" + "log/slog" + "net" + "os" + "plg-mudics/shared" + "strings" + + "plg-mudics/display/browser" + + "github.com/skip2/go-qrcode" +) + +func OpenStartScreen() { + var err error + + raw := shared.RawSplashScreenTemplate + html := strings.ReplaceAll(raw, "%%APP-VERSION%%", shared.Version) + + ip, err := getDeviceIp() + if err != nil { + slog.Error("Failed to get device IP", "error", err) + } + mac, err := getDeviceMac() + if err != nil { + slog.Error("Failed to get device MAC address", "error", err) + } + + port := 8080 + showQrCode := !isPortFree(port) + qrCodePath := "" + if showQrCode { + qrCodePath, err = generateQRCode(fmt.Sprintf("http://%s:%d", ip, port)) + if err != nil { + slog.Error("could not generate qr code", "error", err) + } + } + + var templateBuffer bytes.Buffer + startScreenTemplate(html, ip, mac, qrCodePath).Render(context.Background(), &templateBuffer) + browser.Browser.OpenHTML(templateBuffer.String()) +} + +func getDeviceIp() (string, error) { + addrs, err := net.InterfaceAddrs() + if err != nil { + return "", fmt.Errorf("failed to get network interfaces: %w", err) + } + for _, addr := range addrs { + ipNet, ok := addr.(*net.IPNet) + if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil { + return ipNet.IP.String(), nil + } + } + + return "", fmt.Errorf("no suitable IP address found") +} + +func isPortFree(port int) bool { + addr := fmt.Sprintf("127.0.0.1:%d", port) + l, err := net.Listen("tcp", addr) + if err != nil { + return false + } + _ = l.Close() + return true +} + +func getDeviceMac() (string, error) { + interfaces, err := net.Interfaces() + if err != nil { + return "", fmt.Errorf("failed to get network interfaces: %w", err) + } + + for _, interf := range interfaces { + mac := interf.HardwareAddr.String() + if mac != "" { + return mac, nil + } + } + + return "", fmt.Errorf("no suitable MAC address found") +} + +func generateQRCode(data string) (string, error) { + qr, err := qrcode.New(data, qrcode.Medium) + if err != nil { + return "", fmt.Errorf("could not generate qr code: %w", err) + } + + qr.DisableBorder = true + qr.ForegroundColor = color.RGBA{R: 0x1c, G: 0x19, B: 0x17, A: 0xff} + qr.BackgroundColor = color.RGBA{R: 0xe7, G: 0xe5, B: 0xe4, A: 0xff} + + png, err := qr.PNG(-1) + if err != nil { + return "", fmt.Errorf("could not render qr code: %w", err) + } + + file, err := os.CreateTemp("", "mudics-qr-code-*.png") + if err != nil { + return "", fmt.Errorf("could not save qr code: %w", err) + } + defer file.Close() + + _, err = file.Write(png) + if err != nil { + return "", fmt.Errorf("could not write qr code to file: %w", err) + } + + return file.Name(), nil +} diff --git a/display/requests/openWebsite.bru b/display/requests/openWebsite.bru new file mode 100644 index 0000000..1ea05fd --- /dev/null +++ b/display/requests/openWebsite.bru @@ -0,0 +1,22 @@ +meta { + name: openWebsite + type: http + seq: 10 +} + +patch { + url: 127.0.0.1:1323/api/openWebsite + body: json + auth: inherit +} + +body:json { + { + "url": "https://example.com" + } +} + +settings { + encodeUrl: true + timeout: 0 +} diff --git a/display/web/embed.go b/display/web/embed.go deleted file mode 100644 index 2a15322..0000000 --- a/display/web/embed.go +++ /dev/null @@ -1,12 +0,0 @@ -package web - -import ( - "embed" - "io/fs" -) - -//go:embed all:static -var staticDir embed.FS - -// BuildDirFS contains the embedded dist directory files (without the "build" prefix) -var StaticDirFS, _ = fs.Sub(staticDir, "static") diff --git a/display/web/main.go b/display/web/main.go index e976847..68c493e 100644 --- a/display/web/main.go +++ b/display/web/main.go @@ -1,53 +1,27 @@ package web import ( - "bytes" - "context" "errors" "fmt" - "image/color" "io" "log/slog" - "net" "net/http" "net/url" "os" "os/exec" "path/filepath" shared "plg-mudics/shared" - "strings" - "github.com/gabriel-vasile/mimetype" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" - "github.com/skip2/go-qrcode" + "plg-mudics/display/browser" "plg-mudics/display/pkg" ) -var version string -var sseConnection chan string - -func StartWebServer(v string, port string) { - version = v - +func StartWebServer(port string) { e := echo.New() - e.GET("/", indexRoute) - e.GET("/sse", sseRoute) - e.GET("/splash", func(ctx echo.Context) error { - html := shared.SplashScreenTemplate - html = strings.ReplaceAll(html, "%%APP-VERSION%%", version) - return ctx.HTML(http.StatusOK, html) - }) - e.GET("/qr", qrRoute) - - staticGroup := e.Group("/static") - staticGroup.Use(middleware.StaticWithConfig(middleware.StaticConfig{ - Filesystem: http.FS(StaticDirFS), - HTML5: true, - })) - apiGroup := e.Group("/api") apiGroup.Use(middleware.CORS()) apiGroup.GET("/ping", pingRoute) @@ -55,6 +29,7 @@ func StartWebServer(v string, port string) { apiGroup.PATCH("/keyboardInput", keyboardInputRoute) apiGroup.PATCH("/showHTML", showHTMLRoute) apiGroup.PATCH("/takeScreenshot", takeScreenshotRoute) + apiGroup.PATCH("/openWebsite", openWebsiteRoute) fileGroup := apiGroup.Group("/file") fileGroup.Use(extractFilePathMiddleware) @@ -69,85 +44,6 @@ func StartWebServer(v string, port string) { } } -func indexRoute(ctx echo.Context) error { - return indexTemplate().Render(ctx.Request().Context(), ctx.Response().Writer) -} - -func sseRoute(ctx echo.Context) error { - slog.Info("SSE client connected") - - w := ctx.Response() - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.WriteHeader(http.StatusOK) - flusher, _ := w.Writer.(http.Flusher) - - sseConnection = make(chan string) - - // init display - ip, err := pkg.GetDeviceIp() - if err != nil { - slog.Error("Failed to get device IP address", "error", err) - } - mac, err := pkg.GetDeviceMac() - if err != nil { - slog.Error("Failed to get device MAC address", "error", err) - } - showQR := !isPortFree(8080) - var status bytes.Buffer - deviceInfoTemplate(ip, mac, showQR).Render(context.Background(), &status) - connectedEvent := Event{ - Data: status.Bytes(), - } - connectedEvent.MarshalTo(w) - flusher.Flush() - - for { - select { - case <-ctx.Request().Context().Done(): - slog.Info("SSE client disconnected") - sseConnection = nil - return nil - - case event := <-sseConnection: - rawEvent := Event{ - Event: []byte(""), - Data: []byte(event), - } - - if err := rawEvent.MarshalTo(w); err != nil { - slog.Warn("Error writing to client", "error", err) - return err - } - flusher.Flush() - } - } -} - -func qrRoute(c echo.Context) error { - data := c.QueryParam("data") - if data == "" { - return c.String(http.StatusBadRequest, "missing data") - } - - qr, err := qrcode.New(data, qrcode.Medium) - if err != nil { - return c.String(http.StatusInternalServerError, "could not generate qr") - } - - qr.DisableBorder = true - qr.ForegroundColor = color.RGBA{R: 0x1c, G: 0x19, B: 0x17, A: 0xff} - qr.BackgroundColor = color.RGBA{R: 0xe7, G: 0xe5, B: 0xe4, A: 0xff} - - png, err := qr.PNG(-1) - if err != nil { - return c.String(http.StatusInternalServerError, "could not encode png") - } - - return c.Blob(http.StatusOK, "image/png", png) -} - func extractFilePathMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(ctx echo.Context) error { raw := ctx.Param("path") @@ -308,38 +204,7 @@ func openFileRoute(ctx echo.Context) error { return ctx.JSON(http.StatusNotFound, shared.ErrorResponse{Description: "File not found"}) } - if sseConnection == nil { - return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Cant connect to display browser client"}) - } - - err = resetView() - if err != nil { - slog.Error("Failed to reset view", "error", err) - } - - mType, err := mimetype.DetectFile(fullPath) - if err != nil { - slog.Error("Failed to detect mime type", "file", pathParam, "error", err) - return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to detect file type"}) - } - - switch mType.String() { - case "video/mp4": - var templateBuffer bytes.Buffer - videoTemplate(pathParam).Render(context.Background(), &templateBuffer) - - sseConnection <- templateBuffer.String() - case "image/jpeg", "image/png", "image/gif": - var templateBuffer bytes.Buffer - imageTemplate(pathParam).Render(context.Background(), &templateBuffer) - sseConnection <- templateBuffer.String() - case "application/pdf", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation": - err = pkg.FileHandler.OpenFile(fullPath) - default: - slog.Info("Unsupported file type", "type", mType) - return ctx.JSON(http.StatusUnsupportedMediaType, shared.ErrorResponse{Description: "Unsupported file type: " + mType.String()}) - } - + err = pkg.OpenFile(fullPath) if err != nil { slog.Error("Failed to open file", "file", pathParam, "error", err) return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open file"}) @@ -358,13 +223,12 @@ func showHTMLRoute(ctx echo.Context) error { return ctx.JSON(http.StatusBadRequest, shared.ErrorResponse{Description: shared.BadRequestDescription}) } - err := resetView() + err := pkg.ShowHTML(request.HTML) if err != nil { - slog.Error("Failed to reset view", "error", err) + slog.Error("Failed to open html", "error", err) + return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open html"}) } - sseConnection <- request.HTML - slog.Info("HTML content sent to client") return ctx.JSON(http.StatusOK, struct{}{}) } @@ -372,7 +236,7 @@ func showHTMLRoute(ctx echo.Context) error { func pingRoute(ctx echo.Context) error { return ctx.JSON(http.StatusOK, struct { Version string `json:"version"` - }{Version: version}) + }{Version: shared.Version}) } func takeScreenshotRoute(ctx echo.Context) error { @@ -415,24 +279,18 @@ func previewRoute(ctx echo.Context) error { return ctx.File(outputFilePath) } -// Reset previous file views so they dont collide with the new one -func resetView() error { - err := pkg.FileHandler.CloseRunningProgram() - if err != nil { - return fmt.Errorf("failed to close running program: %w", err) +func openWebsiteRoute(ctx echo.Context) error { + var request struct { + URL string `json:"url"` + } + if err := ctx.Bind(&request); err != nil { + slog.Error("Failed to parse website input", "error", err) + return ctx.JSON(http.StatusBadRequest, shared.ErrorResponse{Description: shared.BadRequestDescription}) } - sseConnection <- "" + slog.Info("Opening url") - return nil -} + browser.Browser.OpenPage(request.URL) -func isPortFree(port int) bool { - addr := fmt.Sprintf("127.0.0.1:%d", port) - l, err := net.Listen("tcp", addr) - if err != nil { - return false - } - _ = l.Close() - return true + return ctx.JSON(http.StatusOK, struct{}{}) } diff --git a/display/web/main.templ b/display/web/main.templ deleted file mode 100644 index fec26df..0000000 --- a/display/web/main.templ +++ /dev/null @@ -1,123 +0,0 @@ -package web - -templ indexTemplate() { - - - - - - PLG MuDiCS Display - - - - - - -
-
-
- -} - -templ videoTemplate(path string) { - -} - -templ imageTemplate(path string) { - -} - -templ deviceInfoTemplate(ip string, mac string, showQR bool) { -
-
- { ip } - { mac } -
- if showQR { -
-
- QR-Code -
-
- } -
- -} diff --git a/display/web/sse.go b/display/web/sse.go deleted file mode 100644 index ca393a2..0000000 --- a/display/web/sse.go +++ /dev/null @@ -1,75 +0,0 @@ -package web - -import ( - "bytes" - "fmt" - "io" -) - -// Event represents Server-Sent Event. -// SSE explanation: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format -type Event struct { - // ID is used to set the EventSource object's last event ID value. - ID []byte - // Data field is for the message. When the EventSource receives multiple consecutive lines - // that begin with data:, it concatenates them, inserting a newline character between each one. - // Trailing newlines are removed. - Data []byte - // Event is a string identifying the type of event described. If this is specified, an event - // will be dispatched on the browser to the listener for the specified event name; the website - // source code should use addEventListener() to listen for named events. The onmessage handler - // is called if no event name is specified for a message. - Event []byte - // Retry is the reconnection time. If the connection to the server is lost, the browser will - // wait for the specified time before attempting to reconnect. This must be an integer, specifying - // the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored. - Retry []byte - // Comment line can be used to prevent connections from timing out; a server can send a comment - // periodically to keep the connection alive. - Comment []byte -} - -// MarshalTo marshals Event to given Writer -func (ev *Event) MarshalTo(w io.Writer) error { - // Marshalling part is taken from: https://github.com/r3labs/sse/blob/c6d5381ee3ca63828b321c16baa008fd6c0b4564/http.go#L16 - if len(ev.Data) == 0 && len(ev.Comment) == 0 { - return nil - } - - if len(ev.Data) > 0 { - if _, err := fmt.Fprintf(w, "id: %s\n", ev.ID); err != nil { - return err - } - - sd := bytes.Split(ev.Data, []byte("\n")) - for i := range sd { - if _, err := fmt.Fprintf(w, "data: %s\n", sd[i]); err != nil { - return err - } - } - - if len(ev.Event) > 0 { - if _, err := fmt.Fprintf(w, "event: %s\n", ev.Event); err != nil { - return err - } - } - - if len(ev.Retry) > 0 { - if _, err := fmt.Fprintf(w, "retry: %s\n", ev.Retry); err != nil { - return err - } - } - } - - if len(ev.Comment) > 0 { - if _, err := fmt.Fprintf(w, ": %s\n", ev.Comment); err != nil { - return err - } - } - - if _, err := fmt.Fprint(w, "\n"); err != nil { - return err - } - - return nil -} diff --git a/display/web/static/htmx-ext-sse.min.js b/display/web/static/htmx-ext-sse.min.js deleted file mode 100644 index 4528733..0000000 --- a/display/web/static/htmx-ext-sse.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){var g;htmx.defineExtension("sse",{init:function(e){g=e;if(htmx.createEventSource==undefined){htmx.createEventSource=t}},getSelectors:function(){return["[sse-connect]","[data-sse-connect]","[sse-swap]","[data-sse-swap]"]},onEvent:function(e,t){var r=t.target||t.detail.elt;switch(e){case"htmx:beforeCleanupElement":var n=g.getInternalData(r);var s=n.sseEventSource;if(s){g.triggerEvent(r,"htmx:sseClose",{source:s,type:"nodeReplaced"});n.sseEventSource.close()}return;case"htmx:afterProcessNode":i(r)}}});function t(e){return new EventSource(e,{withCredentials:true})}function a(n){if(g.getAttributeValue(n,"sse-swap")){var s=g.getClosestMatch(n,v);if(s==null){return null}var e=g.getInternalData(s);var a=e.sseEventSource;var t=g.getAttributeValue(n,"sse-swap");var r=t.split(",");for(var i=0;i0){const t=r.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]");for(let e=0;e=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function B(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function X(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function V(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function j(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function $(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function _(e,t){e=w(e);if(t){b().setTimeout(function(){_(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function z(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(P(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=z(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=D(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!X()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||ne(e,"hx-push-url");const c=t.etc.replace||ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/go.work.sum b/go.work.sum index 78b8cfb..6b0dfa9 100644 --- a/go.work.sum +++ b/go.work.sum @@ -1,4 +1,6 @@ github.com/a-h/htmlformat v0.0.0-20250209131833-673be874c677/go.mod h1:FMIm5afKmEfarNbIXOaPHFY8X7fo+fRQB6I9MPG2nB0= +github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs= +github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0= github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= diff --git a/nixos/configuration.nix b/nixos/configuration.nix index d4199ee..f77c086 100644 --- a/nixos/configuration.nix +++ b/nixos/configuration.nix @@ -92,7 +92,6 @@ nushell unzip iputils - xreader tree jq diff --git a/shared/embed.go b/shared/embed.go index f569902..7128d9a 100644 --- a/shared/embed.go +++ b/shared/embed.go @@ -6,7 +6,7 @@ import ( ) //go:embed splash_screen.html -var SplashScreenTemplate string +var RawSplashScreenTemplate string //go:embed version.txt var versionNotTrimmed string