From 5f0524ed3cc25436284ff16a2bc93a3b439a7e73 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Mon, 7 Sep 2026 16:00:08 +0200 Subject: [PATCH] Sync shared snapshot from c5c3ec3 --- .../.github/workflows/media-backend-lint.yml | 32 - .../.github/workflows/media-backend-tests.yml | 32 - shared/README.md | 21 +- shared/backend/authproxy/authproxy.go | 8 +- .../carriernodeclient/carriernodeclient.go | 381 +++ .../auth => backend/mediaauth}/auth.go | 16 +- .../auth => backend/mediaauth}/auth_test.go | 2 +- .../mediacore/mediacore.go} | 823 +++---- shared/backend/mediacore/migrate.go | 181 ++ .../syncsocket/syncsocket.go} | 268 +- shared/media-backend/.env.example | 23 - shared/media-backend/README.md | 53 - shared/media-backend/SECURITY_AUDIT.md | 19 - shared/media-backend/cmd/mediabackend/main.go | 42 - shared/media-backend/go.mod | 21 - shared/media-backend/go.sum | 32 - .../internal/auth/auth_authguard_test.go | 252 -- .../media-backend/internal/config/config.go | 238 -- .../internal/config/config_test.go | 43 - .../internal/database/database.go | 55 - .../database/migrations/001_initial.sql | 321 --- .../internal/server/admin_storage.go | 1521 ------------ .../media-backend/internal/server/analyzer.go | 2182 ----------------- .../internal/server/analyzer_ai.go | 710 ------ .../internal/server/analyzer_schedule.go | 139 -- .../internal/server/carriernode_client.go | 331 --- shared/media-backend/internal/server/kiosk.go | 195 -- .../internal/server/path_test.go | 83 - .../media-backend/internal/server/server.go | 432 ---- .../internal/server/workflows.go | 1005 -------- shared/packages/java-backend/README.md | 2 +- shared/scripts/sync-consumers.ps1 | 43 +- shared/webui/.prettierignore | 3 - shared/webui/README.md | 18 - shared/webui/eslint.config.js | 62 - shared/webui/package.json | 52 - shared/webui/prettier.config.js | 9 - shared/webui/project-icons.json | 9 - shared/webui/scripts/build-all.mjs | 48 - shared/webui/scripts/project-favicon.mjs | 49 - shared/webui/src/app.css | 167 -- shared/webui/src/app.d.ts | 2 - shared/webui/src/app.html | 14 - shared/webui/src/lib/api.ts | 55 - shared/webui/src/lib/app-config.ts | 256 -- .../webui/src/lib/components/AppShell.svelte | 232 -- .../webui/src/lib/components/AuthPage.svelte | 22 - .../components/ContentScannerHistory.svelte | 207 -- .../ContentScannerLiveStatus.svelte | 208 -- .../ContentScannerPipelineBreakdown.svelte | 84 - .../lib/components/PipelineFlowDiagram.svelte | 352 --- .../src/lib/components/ProjectIcon.svelte | 20 - .../src/lib/components/SettingsDialog.svelte | 105 - .../src/lib/components/WorkspacePage.svelte | 84 - .../src/lib/features/AboutWorkspace.svelte | 5 - .../lib/features/CarrierNodeWorkspace.svelte | 180 -- .../src/lib/features/ConfigWorkspace.svelte | 1177 --------- .../features/ContentScannerWorkspace.svelte | 620 ----- .../lib/features/CraftStudioWorkspace.svelte | 466 ---- .../src/lib/features/FeedWorkspace.svelte | 113 - .../src/lib/features/KioskWorkspace.svelte | 227 -- .../src/lib/features/MediaTypePipeline.svelte | 486 ---- .../lib/features/ModeratorWorkspace.svelte | 496 ---- .../src/lib/features/TagsWorkspace.svelte | 267 -- .../webui/src/lib/features/VideoPage.svelte | 1057 -------- .../src/lib/features/ViewerWorkspace.svelte | 628 ----- .../features/about/TechStackSection.svelte | 76 - shared/webui/src/lib/language.svelte.ts | 63 - shared/webui/src/lib/layout.svelte.ts | 43 - .../src/lib/stores/page-actions.svelte.ts | 6 - shared/webui/src/lib/theme.svelte.ts | 84 - shared/webui/src/lib/types.ts | 74 - shared/webui/src/lib/utils/cn.ts | 6 - shared/webui/src/routes/+layout.svelte | 16 - shared/webui/src/routes/+page.svelte | 5 - .../webui/src/routes/[...path]/+page.svelte | 5 - shared/webui/static/favicon.svg | 4 - shared/webui/svelte.config.js | 10 - shared/webui/tsconfig.json | 14 - shared/webui/vite.config.ts | 58 - 80 files changed, 1152 insertions(+), 16598 deletions(-) delete mode 100644 shared/.github/workflows/media-backend-lint.yml delete mode 100644 shared/.github/workflows/media-backend-tests.yml create mode 100644 shared/backend/carriernodeclient/carriernodeclient.go rename shared/{media-backend/internal/auth => backend/mediaauth}/auth.go (98%) rename shared/{media-backend/internal/auth => backend/mediaauth}/auth_test.go (97%) rename shared/{media-backend/internal/server/media.go => backend/mediacore/mediacore.go} (55%) create mode 100644 shared/backend/mediacore/migrate.go rename shared/{media-backend/internal/server/sync.go => backend/syncsocket/syncsocket.go} (59%) delete mode 100644 shared/media-backend/.env.example delete mode 100644 shared/media-backend/README.md delete mode 100644 shared/media-backend/SECURITY_AUDIT.md delete mode 100644 shared/media-backend/cmd/mediabackend/main.go delete mode 100644 shared/media-backend/go.mod delete mode 100644 shared/media-backend/go.sum delete mode 100644 shared/media-backend/internal/auth/auth_authguard_test.go delete mode 100644 shared/media-backend/internal/config/config.go delete mode 100644 shared/media-backend/internal/config/config_test.go delete mode 100644 shared/media-backend/internal/database/database.go delete mode 100644 shared/media-backend/internal/database/migrations/001_initial.sql delete mode 100644 shared/media-backend/internal/server/admin_storage.go delete mode 100644 shared/media-backend/internal/server/analyzer.go delete mode 100644 shared/media-backend/internal/server/analyzer_ai.go delete mode 100644 shared/media-backend/internal/server/analyzer_schedule.go delete mode 100644 shared/media-backend/internal/server/carriernode_client.go delete mode 100644 shared/media-backend/internal/server/kiosk.go delete mode 100644 shared/media-backend/internal/server/path_test.go delete mode 100644 shared/media-backend/internal/server/server.go delete mode 100644 shared/media-backend/internal/server/workflows.go delete mode 100644 shared/webui/.prettierignore delete mode 100644 shared/webui/README.md delete mode 100644 shared/webui/eslint.config.js delete mode 100644 shared/webui/package.json delete mode 100644 shared/webui/prettier.config.js delete mode 100644 shared/webui/project-icons.json delete mode 100644 shared/webui/scripts/build-all.mjs delete mode 100644 shared/webui/scripts/project-favicon.mjs delete mode 100644 shared/webui/src/app.css delete mode 100644 shared/webui/src/app.d.ts delete mode 100644 shared/webui/src/app.html delete mode 100644 shared/webui/src/lib/api.ts delete mode 100644 shared/webui/src/lib/app-config.ts delete mode 100644 shared/webui/src/lib/components/AppShell.svelte delete mode 100644 shared/webui/src/lib/components/AuthPage.svelte delete mode 100644 shared/webui/src/lib/components/ContentScannerHistory.svelte delete mode 100644 shared/webui/src/lib/components/ContentScannerLiveStatus.svelte delete mode 100644 shared/webui/src/lib/components/ContentScannerPipelineBreakdown.svelte delete mode 100644 shared/webui/src/lib/components/PipelineFlowDiagram.svelte delete mode 100644 shared/webui/src/lib/components/ProjectIcon.svelte delete mode 100644 shared/webui/src/lib/components/SettingsDialog.svelte delete mode 100644 shared/webui/src/lib/components/WorkspacePage.svelte delete mode 100644 shared/webui/src/lib/features/AboutWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/CarrierNodeWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/ConfigWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/ContentScannerWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/CraftStudioWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/FeedWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/KioskWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/MediaTypePipeline.svelte delete mode 100644 shared/webui/src/lib/features/ModeratorWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/TagsWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/VideoPage.svelte delete mode 100644 shared/webui/src/lib/features/ViewerWorkspace.svelte delete mode 100644 shared/webui/src/lib/features/about/TechStackSection.svelte delete mode 100644 shared/webui/src/lib/language.svelte.ts delete mode 100644 shared/webui/src/lib/layout.svelte.ts delete mode 100644 shared/webui/src/lib/stores/page-actions.svelte.ts delete mode 100644 shared/webui/src/lib/theme.svelte.ts delete mode 100644 shared/webui/src/lib/types.ts delete mode 100644 shared/webui/src/lib/utils/cn.ts delete mode 100644 shared/webui/src/routes/+layout.svelte delete mode 100644 shared/webui/src/routes/+page.svelte delete mode 100644 shared/webui/src/routes/[...path]/+page.svelte delete mode 100644 shared/webui/static/favicon.svg delete mode 100644 shared/webui/svelte.config.js delete mode 100644 shared/webui/tsconfig.json delete mode 100644 shared/webui/vite.config.ts diff --git a/shared/.github/workflows/media-backend-lint.yml b/shared/.github/workflows/media-backend-lint.yml deleted file mode 100644 index 3bf2201..0000000 --- a/shared/.github/workflows/media-backend-lint.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Lint (media-backend) - -on: - push: - branches: ['**'] - paths: - - 'media-backend/**' - - '.github/workflows/media-backend-lint.yml' - pull_request: - branches: [main, master] - paths: - - 'media-backend/**' - - '.github/workflows/media-backend-lint.yml' - workflow_dispatch: {} - -jobs: - vet: - name: Lint - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: '1.26.x' - cache-dependency-path: media-backend/go.sum - - name: Vet backend - working-directory: media-backend - run: go vet ./... diff --git a/shared/.github/workflows/media-backend-tests.yml b/shared/.github/workflows/media-backend-tests.yml deleted file mode 100644 index d14f440..0000000 --- a/shared/.github/workflows/media-backend-tests.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: Tests (media-backend) - -on: - push: - branches: ['**'] - paths: - - 'media-backend/**' - - '.github/workflows/media-backend-tests.yml' - pull_request: - branches: [main, master] - paths: - - 'media-backend/**' - - '.github/workflows/media-backend-tests.yml' - workflow_dispatch: {} - -jobs: - test: - name: Tests - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: '1.26.x' - cache-dependency-path: media-backend/go.sum - - name: Test backend - working-directory: media-backend - run: go test ./... diff --git a/shared/README.md b/shared/README.md index 0ceb42e..862121d 100644 --- a/shared/README.md +++ b/shared/README.md @@ -1,6 +1,6 @@ # shared -The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages, and the Go media-backend/webui powering the whole `MEDIA_SERVICE`-family of projects. +The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — including the media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, MediaKiosk, ModerationHub, ProjectConfigurator) — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore. --- @@ -21,12 +21,11 @@ The single source of truth for code reused across every project in this workspac |---|---|---| | `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. | | `@gabriel20xx/web-ui` | Svelte | Application shell, header/navigation, auth screens, dialogs, buttons, cards, badges. | -| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets for the media-backend/`MEDIA_SERVICE` family. | -| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations. | +| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets, kept for a handful of older pages. | +| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). | | `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. | | `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. | | `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. | -| `media-backend` / `webui` | Go / Svelte | The Go binary and web UI powering the `MEDIA_SERVICE`-family projects (see below). | The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks. @@ -38,7 +37,7 @@ There are two different distribution paths in this workspace, used for different ### Vendored snapshot (the one every project actually uses) -Every consumer project vendors a full copy of this repo's tracked files into its own `shared/` (or, for the `media-backend` family, `engine/`) directory, committed directly rather than installed from a registry. This exists because none of these projects are meant to resolve a private registry dependency in a fresh CI checkout without extra credentials, and because a git submodule pointing at this (private) repo breaks the same way — see `scripts/sync-consumers.ps1`'s own comments for the full history. +Every consumer project vendors a full copy of this repo's tracked files into its own `shared/` directory, committed directly rather than installed from a registry. This exists because none of these projects are meant to resolve a private registry dependency in a fresh CI checkout without extra credentials, and because a git submodule pointing at this (private) repo breaks the same way — see `scripts/sync-consumers.ps1`'s own comments for the full history. To pull the latest snapshot into every registered consumer: @@ -47,7 +46,7 @@ To pull the latest snapshot into every registered consumer: .\scripts\sync-consumers.ps1 -Commit -Push ``` -The script copies every tracked file in this repo into each consumer's destination folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared/engine snapshot from ``"). Consumers are registered in the script's `$consumerProjects` list, each with a destination folder (`shared` by default, `engine` for the media-backend family). A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step. +The script copies every tracked file in this repo into each consumer's `shared/` folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared snapshot from ``"). Consumers are registered in the script's `$consumerProjects` list. A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step. ### Published registry packages (for standalone/external use) @@ -70,12 +69,6 @@ go test ./... go vet ./... ``` -```bash -cd media-backend -go test ./... -go vet ./... -``` - --- ## Typical `web-ui` wiring @@ -107,7 +100,7 @@ go vet ./... Import the stylesheet once, before project-specific overrides: `@import '@gabriel20xx/web-ui/styles.css';`. It uses an `sc-` class prefix, so it doesn't require Tailwind and doesn't collide with existing project classes. Set `data-theme="light"` or `data-theme="dark"` on the application root; dark is the default. -For authentication, use `AuthPage` and wire its callbacks to the project's auth service — every project in this workspace either talks to AuthGuard directly or proxies through its own backend to AuthGuard. See `Central/AuthGuard/README.md` for the identity service this whole authentication surface is built to work with. +For authentication, use `AuthPage` and wire its callbacks to the project's auth service — every project in this workspace either talks to AuthGuard directly or proxies through its own backend to AuthGuard. See `Core/AuthGuard/README.md` for the identity service this whole authentication surface is built to work with. --- @@ -143,4 +136,4 @@ The Go module lives under `backend`, so its release tag uses the submodule prefi ## CI/CD -`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python — plus dedicated `media-backend-lint.yml`/`media-backend-tests.yml` for the `media-backend` Go module. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above. +`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above. diff --git a/shared/backend/authproxy/authproxy.go b/shared/backend/authproxy/authproxy.go index a1bbdba..2a5a1cc 100644 --- a/shared/backend/authproxy/authproxy.go +++ b/shared/backend/authproxy/authproxy.go @@ -4,10 +4,12 @@ // of embedding its own local user table. // // Three services independently reimplemented the same handful of pieces -// below before this package existed (Forks/Bitmagnet/backend/internal/auth/service.go, +// below before this package existed (Fork/Bitmagnet/backend/internal/auth/service.go, // Original/GameStream/backend/cmd/gamestreamd/auth.go, -// Central/shared/media-backend/internal/auth/auth.go — read any one of -// their top-of-file doc comments for the fuller AuthGuard-migration +// this same module's own mediaauth/auth.go, formerly +// Core/shared/media-backend/internal/auth/auth.go before that generic +// multi-service binary was split up — read any one of their top-of-file +// doc comments for the fuller AuthGuard-migration // rationale: session cookie forwarding, the local one-time setup-claim // flag, "auth disabled" mode, etc.). Those pieces stay project-specific // (they depend on each project's own storage/framework/response shape) — diff --git a/shared/backend/carriernodeclient/carriernodeclient.go b/shared/backend/carriernodeclient/carriernodeclient.go new file mode 100644 index 0000000..149ab26 --- /dev/null +++ b/shared/backend/carriernodeclient/carriernodeclient.go @@ -0,0 +1,381 @@ +// Package carriernodeclient is the HTTP client the 6 non-CarrierNode +// media-family services (MediaViewer, CraftStudio, ContentScanner, +// ModerationHub, ProjectConfigurator, MediaKiosk) use to store and serve +// media by calling CarrierNode's API, instead of touching a local +// MediaRoots/ThumbnailRoot/OutputRoot/DownloadsRoot/InputRoot/CopyRoot +// filesystem directly. CarrierNode's own backend keeps resolving and +// serving those roots itself - this client is never used from CarrierNode's +// own code path. +// +// Promoted unchanged (aside from being detached from a shared *Server type) +// from each service's own internal carriernode_client.go into this shared +// library, so all 6 callers use one copy instead of duplicating it. +package carriernodeclient + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +// httpClient has no blanket timeout since it streams large media files; +// callers bound individual calls with a context deadline instead. +var httpClient = &http.Client{} + +var forwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} +var forwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} + +// Client calls CarrierNode's HTTP API on behalf of one of the other 6 +// media-family services. +type Client struct { + // InternalServiceSecret is sent as the X-Internal-Auth header on every + // request, so CarrierNode can distinguish trusted service-to-service + // calls from public traffic. Empty means no header is sent. + InternalServiceSecret string + + // BaseURL resolves CarrierNode's current base URL for a request. It is a + // function rather than a fixed string because CarrierNode's URL is + // configured live through ProjectConfigurator's Projects workspace + // (stored in the shared `settings` table under the "carriernode_url" + // key) - a change there takes effect on this client's very next call + // with no restart needed. Callers typically wire this as a closure over + // their own settings lookup, falling back to a static CARRIERNODE_URL + // env var default when no setting has been saved yet. + BaseURL func(ctx context.Context) string +} + +// New returns a Client. baseURL is called fresh on every request (see +// Client.BaseURL's doc comment for why). +func New(internalServiceSecret string, baseURL func(ctx context.Context) string) *Client { + return &Client{InternalServiceSecret: internalServiceSecret, BaseURL: baseURL} +} + +func (c *Client) newRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { + request, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(c.BaseURL(ctx), "/")+path, body) + if err != nil { + return nil, err + } + if c.InternalServiceSecret != "" { + request.Header.Set("X-Internal-Auth", c.InternalServiceSecret) + } + return request, nil +} + +// Proxy streams a CarrierNode response straight through to the original +// client, preserving range/conditional-request semantics so video scrubbing +// keeps working without reimplementing http.ServeContent on this side. +func (c *Client) Proxy(w http.ResponseWriter, r *http.Request, carrierNodePath string) { + request, err := c.newRequest(r.Context(), r.Method, carrierNodePath, nil) + if err != nil { + writeError(w, http.StatusBadGateway, "media service unavailable") + return + } + for _, header := range forwardRequestHeaders { + if value := r.Header.Get(header); value != "" { + request.Header.Set(header, value) + } + } + response, err := httpClient.Do(request) + if err != nil { + writeError(w, http.StatusBadGateway, "media service unavailable") + return + } + defer response.Body.Close() + for _, header := range forwardResponseHeaders { + if value := response.Header.Get(header); value != "" { + w.Header().Set(header, value) + } + } + w.WriteHeader(response.StatusCode) + if r.Method != http.MethodHead { + _, _ = io.Copy(w, response.Body) + } +} + +// Probe checks whether a CarrierNode-served path exists without fetching its +// bytes. A 404 is reported as exists=false with a nil error, not a failure - +// only transport/5xx problems are surfaced as errors. +func (c *Client) Probe(ctx context.Context, carrierNodePath string) (exists bool, size int64, modTime time.Time, err error) { + request, err := c.newRequest(ctx, http.MethodHead, carrierNodePath, nil) + if err != nil { + return false, 0, time.Time{}, err + } + response, err := httpClient.Do(request) + if err != nil { + return false, 0, time.Time{}, err + } + defer response.Body.Close() + if response.StatusCode == http.StatusNotFound { + return false, 0, time.Time{}, nil + } + if response.StatusCode >= 400 { + return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status) + } + size, _ = strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64) + modTime, _ = http.ParseTime(response.Header.Get("Last-Modified")) + return true, size, modTime, nil +} + +// FetchToScratch downloads a CarrierNode-served path into an ephemeral temp +// file for local processing (ffmpeg/ffprobe/yt-dlp all need a real file +// handle). Callers must invoke the returned cleanup once done; it removes +// the scratch file unconditionally. +func (c *Client) FetchToScratch(ctx context.Context, carrierNodePath, suffix string) (path string, cleanup func(), err error) { + request, err := c.newRequest(ctx, http.MethodGet, carrierNodePath, nil) + if err != nil { + return "", nil, err + } + response, err := httpClient.Do(request) + if err != nil { + return "", nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status) + } + scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix) + if err != nil { + return "", nil, err + } + cleanup = func() { _ = os.Remove(scratch.Name()) } + if _, err := io.Copy(scratch, response.Body); err != nil { + scratch.Close() + cleanup() + return "", nil, err + } + if err := scratch.Close(); err != nil { + cleanup() + return "", nil, err + } + return scratch.Name(), cleanup, nil +} + +// push streams a local file as the request body without buffering it in +// memory. +func (c *Client) push(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) { + file, err := os.Open(localPath) + if err != nil { + return nil, err + } + defer file.Close() + request, err := c.newRequest(ctx, method, carrierNodePath, file) + if err != nil { + return nil, err + } + if info, statErr := file.Stat(); statErr == nil { + request.ContentLength = info.Size() + } + response, err := httpClient.Do(request) + if err != nil { + return nil, err + } + if response.StatusCode >= 400 { + body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + response.Body.Close() + return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body)) + } + return response, nil +} + +func pushedSize(response *http.Response) int64 { + defer response.Body.Close() + var payload struct { + Size int64 `json:"size"` + } + _ = json.NewDecoder(response.Body).Decode(&payload) + return payload.Size +} + +// PushThumbnail uploads a locally-generated thumbnail to CarrierNode. +func (c *Client) PushThumbnail(ctx context.Context, id, localPath string) (int64, error) { + response, err := c.push(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath) + if err != nil { + return 0, err + } + return pushedSize(response), nil +} + +// DeleteThumbnail removes a thumbnail from CarrierNode. A 404 is treated as +// already-deleted, not an error. +func (c *Client) DeleteThumbnail(ctx context.Context, id string) error { + request, err := c.newRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) + if err != nil { + return err + } + response, err := httpClient.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound { + return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status) + } + return nil +} + +// PushOutput uploads a locally-produced output file (e.g. a converted or +// generated media file) to CarrierNode's OutputRoot. +func (c *Client) PushOutput(ctx context.Context, name, localPath string) (int64, error) { + response, err := c.push(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return pushedSize(response), nil +} + +// PushInput uploads a local file to CarrierNode's InputRoot. +func (c *Client) PushInput(ctx context.Context, name, localPath string) (int64, error) { + response, err := c.push(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return pushedSize(response), nil +} + +// PushCopy uploads a local file to CarrierNode's CopyRoot. +func (c *Client) PushCopy(ctx context.Context, name, localPath string) (int64, error) { + response, err := c.push(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return pushedSize(response), nil +} + +// UploadDownload streams a locally-produced file (e.g. a completed yt-dlp +// download staged in a scratch dir) into CarrierNode's DownloadsRoot via its +// raw-upload endpoint. +func (c *Client) UploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) { + response, err := c.push(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath) + if err != nil { + return nil, err + } + defer response.Body.Close() + var payload map[string]any + _ = json.NewDecoder(response.Body).Decode(&payload) + return payload, nil +} + +// StoreDownload catalogs an already-uploaded file into CarrierNode's +// media/downloaded_media tables via its /api/store endpoint. +func (c *Client) StoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) { + body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status}) + if err != nil { + return nil, err + } + request, err := c.newRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body)) + if err != nil { + return nil, err + } + request.Header.Set("Content-Type", "application/json") + response, err := httpClient.Do(request) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode >= 400 { + errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody)) + } + var payload map[string]any + _ = json.NewDecoder(response.Body).Decode(&payload) + return payload, nil +} + +// FileEntry describes one file CarrierNode reports via /api/files(/recent). +type FileEntry struct { + Rel string `json:"rel"` + Path string `json:"path"` + Type string `json:"type"` + Size int64 `json:"size"` + Mtime int64 `json:"mtime"` +} + +// ListFiles lists files under CarrierNode's MediaRoots via its /api/files +// (recent=false) or /api/files/recent (recent=true) endpoints - the +// replacement for a local filepath.WalkDir over MediaRoots. +func (c *Client) ListFiles(ctx context.Context, relative string, recent bool, limit int) ([]FileEntry, error) { + endpoint := "/api/files" + if recent { + endpoint = "/api/files/recent" + } + query := url.Values{} + if relative != "" { + query.Set("path", relative) + } + if limit > 0 { + query.Set("limit", strconv.Itoa(limit)) + } + if encoded := query.Encode(); encoded != "" { + endpoint += "?" + encoded + } + request, err := c.newRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + response, err := httpClient.Do(request) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status) + } + var payload struct { + Files []FileEntry `json:"files"` + } + if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { + return nil, err + } + return payload.Files, nil +} + +// ProbeResult is the ffprobe-derived metadata CarrierNode's /api/probe +// endpoint reports for a media file. +type ProbeResult struct { + DurationMs int64 `json:"durationMs"` + Width int `json:"width"` + Height int `json:"height"` +} + +// ProbeMedia runs ffprobe on CarrierNode against a MediaRoots-relative path +// and returns just the metadata fields - bytes never leave CarrierNode, +// unlike every other method on Client. +func (c *Client) ProbeMedia(ctx context.Context, relative string) (ProbeResult, error) { + query := url.Values{} + query.Set("path", relative) + request, err := c.newRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil) + if err != nil { + return ProbeResult{}, err + } + response, err := httpClient.Do(request) + if err != nil { + return ProbeResult{}, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return ProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status) + } + var result ProbeResult + if err := json.NewDecoder(response.Body).Decode(&result); err != nil { + return ProbeResult{}, err + } + return result, nil +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message, "message": message}) +} diff --git a/shared/media-backend/internal/auth/auth.go b/shared/backend/mediaauth/auth.go similarity index 98% rename from shared/media-backend/internal/auth/auth.go rename to shared/backend/mediaauth/auth.go index 37fa313..aeb095e 100644 --- a/shared/media-backend/internal/auth/auth.go +++ b/shared/backend/mediaauth/auth.go @@ -1,5 +1,9 @@ -// Package auth is the shared media-backend family's /auth/... and /api/auth/... -// handlers, proxied to AuthGuard. +// Package mediaauth is the shared media-backend family's /auth/... and /api/auth/... +// handlers, proxied to AuthGuard. Promoted from each service's own +// internal/auth into this shared library so all 7 independent media-family +// backends (CarrierNode, ModerationHub, ProjectConfigurator, MediaKiosk, +// MediaViewer, ContentScanner, CraftStudio) use one copy instead of +// duplicating it. // // AuthGuard migration // ==================== @@ -9,16 +13,16 @@ // CREATE TABLE statements are kept but no longer used for identity - see // below). // -// It now proxies every auth operation to AuthGuard (Web/Central/AuthGuard), +// It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard), // a centralized identity service other projects in this workspace share, -// via the `authclient` package (Web/Central/shared/backend/authclient, +// via the `authclient` package (Web/Core/shared/backend/authclient, // resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend` // dependency - same module that already provided `sharedauth`). This // service's own /auth/... and /api/auth/... URL paths and JSON response // shapes are UNCHANGED - the frontend (webui) was not touched - only // what backs them changed. This mirrors the migration // Original/GameStream/backend/cmd/gamestreamd/auth.go and -// Forks/Bitmagnet/backend/internal/auth/service.go already did; read either +// Fork/Bitmagnet/backend/internal/auth/service.go already did; read either // file's top-of-file doc comment for the fuller rationale behind each // design choice below. // @@ -113,7 +117,7 @@ // centralized in AuthGuard now, and only AuthGuard's own web UI exposes an // admin-reset affordance. Those two routes are removed entirely, not // adapted (see server.go). -package auth +package mediaauth import ( "context" diff --git a/shared/media-backend/internal/auth/auth_test.go b/shared/backend/mediaauth/auth_test.go similarity index 97% rename from shared/media-backend/internal/auth/auth_test.go rename to shared/backend/mediaauth/auth_test.go index fc3099f..2c7c273 100644 --- a/shared/media-backend/internal/auth/auth_test.go +++ b/shared/backend/mediaauth/auth_test.go @@ -1,4 +1,4 @@ -package auth +package mediaauth import "testing" diff --git a/shared/media-backend/internal/server/media.go b/shared/backend/mediacore/mediacore.go similarity index 55% rename from shared/media-backend/internal/server/media.go rename to shared/backend/mediacore/mediacore.go index 767038d..e235bb9 100644 --- a/shared/media-backend/internal/server/media.go +++ b/shared/backend/mediacore/mediacore.go @@ -1,10 +1,36 @@ -package server +// Package mediacore is the media-backend family's cross-service HTTP surface: +// media like/save/view stats, tags, playlists, cross-device playback sync +// state, and profile - the routes every media-family service mounts +// regardless of its own specialty (MediaViewer's own library/browse routes, +// CraftStudio's generator/downloader/converter, ContentScanner's AI +// pipeline, etc. are NOT here; each service owns those itself). +// +// Promoted from each service's own internal/server mountSharedRoutes/media.go +// into this shared library so all 7 independent media-family backends use +// one copy instead of duplicating it. Behavior is unchanged from the +// pre-split monolith - this is a mechanical extraction, not a rewrite. +// +// A service wires this up as: +// +// core := mediacore.New(mediacore.Config{ +// DB: pool, +// Auth: authService, +// Sync: syncsocket.NewHub(), +// CarrierNode: carrierNodeClient, +// ServiceName: "CarrierNode", // cfg.ServiceName +// MediaRoots: func(ctx context.Context) []string { return cfg.MediaRoots }, +// }) +// if err := core.Migrate(ctx); err != nil { ... } +// router.Route("/api", func(r chi.Router) { +// core.Mount(r) +// // ... the service's own routes ... +// }) +package mediacore import ( "context" "encoding/json" "errors" - "fmt" "io" "mime" "net/http" @@ -16,53 +42,84 @@ import ( "time" "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5/pgxpool" - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth" + "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" + "repos.gfranz.ch/Gabriel20xx/shared/backend/mediaauth" + "repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" ) -func (s *Server) mountSharedRoutes(r chi.Router) { - r.With(s.auth.Require).Get("/security/totp/status", s.auth.TOTPStatus) - r.With(s.auth.Require).Get("/security/totp/initiate", s.auth.TOTPInitiate) - r.With(s.auth.Require).Post("/security/totp/verify", s.auth.TOTPVerify) - r.With(s.auth.Require).Post("/security/totp/disable", s.auth.TOTPDisable) - r.With(s.auth.Optional).Get("/sync", s.getSyncState) - r.With(s.auth.Optional).Put("/sync", s.putSyncState) - r.With(s.auth.Optional).Get("/media/state", s.mediaState) - r.With(s.auth.Require).Post("/media/like", s.mediaLike) - r.With(s.auth.Require).Post("/media/save", s.mediaSave) - r.With(s.auth.Optional).Post("/media/view", s.mediaView) - r.With(s.auth.Optional).Post("/media/view-session", s.mediaViewSession) - r.With(s.auth.Require).Get("/media/liked", s.mediaLiked) - r.Get("/media/stream", s.streamMediaByQuery) - r.Head("/media/stream", s.streamMediaByQuery) - r.Get("/media/thumb", s.thumbnailMediaByQuery) - - r.With(s.auth.Optional).Get("/media/{id}/tags", s.mediaTags) - r.With(s.auth.Require).Post("/media/{id}/tags", s.addMediaTag) - r.With(s.auth.Require).Post("/media/{id}/tags/{tag}/vote", s.voteMediaTag) - r.Get("/tags/suggestions", s.tagSuggestions) - r.Get("/tags/{tag}/media", s.tagMedia) - - r.With(s.auth.Require).Get("/playlists", s.playlists) - r.With(s.auth.Optional).Get("/playlists/summary", s.playlistSummary) - r.With(s.auth.Optional).Get("/playlists/{id}", s.playlist) - r.With(s.auth.Require).Post("/playlists", s.createPlaylist) - r.With(s.auth.Require).Delete("/playlists/{id}", s.deletePlaylist) - r.With(s.auth.Optional).Get("/playlists/{id}/items", s.playlistItems) - r.With(s.auth.Require).Post("/playlists/{id}/items", s.addPlaylistItem) - r.With(s.auth.Require).Delete("/playlists/{id}/items", s.deletePlaylistItem) - r.With(s.auth.Optional).Get("/playlists/{id}/random", s.randomPlaylistItem) - r.With(s.auth.Require).Patch("/playlists/{id}/items/reorder", s.reorderPlaylist) - - r.With(s.auth.Optional).Get("/profile", s.profile) +// Config wires a Core to the rest of one service's dependencies. +type Config struct { + DB *pgxpool.Pool + Auth *mediaauth.Service + Sync *syncsocket.Hub + CarrierNode *carriernodeclient.Client + // ServiceName is recorded on mutations that track which app produced + // them (e.g. media_stats.app) - a service's own cfg.ServiceName. + ServiceName string } -func (s *Server) getSyncState(w http.ResponseWriter, r *http.Request) { +// Core mounts the shared media/tags/playlists/sync/profile routes and holds +// what they need to run. +type Core struct { + db *pgxpool.Pool + auth *mediaauth.Service + sync *syncsocket.Hub + carrierNode *carriernodeclient.Client + serviceName string +} + +// New returns a Core ready to Mount and Migrate. +func New(cfg Config) *Core { + return &Core{db: cfg.DB, auth: cfg.Auth, sync: cfg.Sync, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName} +} + +// Mount wires the shared routes onto r, exactly matching the pre-split +// monolith's mountSharedRoutes route table. +func (c *Core) Mount(r chi.Router) { + r.With(c.auth.Require).Get("/security/totp/status", c.auth.TOTPStatus) + r.With(c.auth.Require).Get("/security/totp/initiate", c.auth.TOTPInitiate) + r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify) + r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable) + r.With(c.auth.Optional).Get("/sync", c.getSyncState) + r.With(c.auth.Optional).Put("/sync", c.putSyncState) + r.With(c.auth.Optional).Get("/media/state", c.mediaState) + r.With(c.auth.Require).Post("/media/like", c.mediaLike) + r.With(c.auth.Require).Post("/media/save", c.mediaSave) + r.With(c.auth.Optional).Post("/media/view", c.mediaView) + r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession) + r.With(c.auth.Require).Get("/media/liked", c.mediaLiked) + r.Get("/media/stream", c.streamMediaByQuery) + r.Head("/media/stream", c.streamMediaByQuery) + r.Get("/media/thumb", c.thumbnailMediaByQuery) + + r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags) + r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag) + r.With(c.auth.Require).Post("/media/{id}/tags/{tag}/vote", c.voteMediaTag) + r.Get("/tags/suggestions", c.tagSuggestions) + r.Get("/tags/{tag}/media", c.tagMedia) + + r.With(c.auth.Require).Get("/playlists", c.playlists) + r.With(c.auth.Optional).Get("/playlists/summary", c.playlistSummary) + r.With(c.auth.Optional).Get("/playlists/{id}", c.playlist) + r.With(c.auth.Require).Post("/playlists", c.createPlaylist) + r.With(c.auth.Require).Delete("/playlists/{id}", c.deletePlaylist) + r.With(c.auth.Optional).Get("/playlists/{id}/items", c.playlistItems) + r.With(c.auth.Require).Post("/playlists/{id}/items", c.addPlaylistItem) + r.With(c.auth.Require).Delete("/playlists/{id}/items", c.deletePlaylistItem) + r.With(c.auth.Optional).Get("/playlists/{id}/random", c.randomPlaylistItem) + r.With(c.auth.Require).Patch("/playlists/{id}/items/reorder", c.reorderPlaylist) + + r.With(c.auth.Optional).Get("/profile", c.profile) +} + +func (c *Core) getSyncState(w http.ResponseWriter, r *http.Request) { sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default")) - writeJSON(w, http.StatusOK, s.sync.httpState(sessionID)) + writeJSON(w, http.StatusOK, c.sync.HTTPState(sessionID)) } -func (s *Server) putSyncState(w http.ResponseWriter, r *http.Request) { +func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) { var input map[string]any if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") @@ -87,292 +144,102 @@ func (s *Server) putSyncState(w http.ResponseWriter, r *http.Request) { if value, ok := input["playAt"]; ok { state["playAt"] = value } - s.sync.setHTTPState(sessionID, state) - s.sync.broadcast(sessionID) + c.sync.SetHTTPState(sessionID, state) + c.sync.Broadcast(sessionID) writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state}) } -func (s *Server) mountViewerRoutes(r chi.Router) { - r.Get("/media", s.listMedia) - r.Get("/media/random", s.randomMedia) - r.Get("/media/random/{category}", s.randomMedia) - r.Get("/media/{id}/stream", s.streamMedia) - r.Head("/media/{id}/stream", s.streamMedia) - r.Get("/media/{id}/thumb", s.thumbnailMedia) - r.Get("/media/{id}/funscript", s.funscriptMedia) - r.Get("/media/{id}/fileinfo", s.mediaFileInfo) - r.Get("/media/{id}/probe", s.probeMedia) - r.Get("/library/unified", s.unifiedLibrary) - r.Get("/routes", s.mediaRoutes) - r.Get("/categories", s.mediaCategories) +// MediaRecord is one row of the shared `media` table. +type MediaRecord struct { + ID int64 + MediaKey string + MediaType string + Title *string + Description *string + FilePath string + OriginalName string + Source string + Width *int + Height *int + DurationMs *int64 + SizeBytes *int64 + IsVR bool + HasFunscript bool + Speed *float32 + ModifiedAt time.Time } -func (s *Server) listMedia(w http.ResponseWriter, r *http.Request) { - pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000) - pageSize := optionalInt(firstNonEmpty(r.URL.Query().Get("pageSize"), r.URL.Query().Get("limit")), 24, 1, 100) - search := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("q"), r.URL.Query().Get("search"))) - conditions := []string{"active = TRUE"} - args := make([]any, 0, 10) - add := func(value any) string { - args = append(args, value) - return "$" + strconv.Itoa(len(args)) - } - if search != "" { - placeholder := add("%" + search + "%") - conditions = append(conditions, "(media_key ILIKE "+placeholder+" OR COALESCE(title, '') ILIKE "+placeholder+" OR COALESCE(original_filename, '') ILIKE "+placeholder+" OR COALESCE(file_path, '') ILIKE "+placeholder+")") - } - if value := r.URL.Query().Get("minHeight"); value != "" { - if height, err := strconv.Atoi(value); err == nil && height > 0 { - conditions = append(conditions, "COALESCE(height, 0) >= "+add(height)) - } - } - for key, expression := range map[string]string{"isVr": "is_vr", "hasFunscript": "has_funscript"} { - if value := boolQuery(r.URL.Query().Get(key)); value != nil { - conditions = append(conditions, expression+" = "+add(*value)) - } - } - if value := r.URL.Query().Get("minDurationSec"); value != "" { - if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 { - conditions = append(conditions, "COALESCE(duration_ms, 0) >= "+add(seconds*1000)) - } - } - if value := r.URL.Query().Get("maxDurationSec"); value != "" { - if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 { - conditions = append(conditions, "COALESCE(duration_ms, 0) <= "+add(seconds*1000)) - } - } - if value := r.URL.Query().Get("minSpeed"); value != "" { - if speed, err := strconv.ParseFloat(value, 32); err == nil && speed >= 0 { - conditions = append(conditions, "COALESCE(speed, 0) >= "+add(float32(speed))) - } - } - if value := r.URL.Query().Get("maxSpeed"); value != "" { - if speed, err := strconv.ParseFloat(value, 32); err == nil && speed >= 0 { - conditions = append(conditions, "COALESCE(speed, 0) <= "+add(float32(speed))) - } - } - where := strings.Join(conditions, " AND ") - var total int64 - if err := s.db.QueryRow(r.Context(), "SELECT COUNT(*) FROM media WHERE "+where, args...).Scan(&total); err != nil { - writeError(w, http.StatusInternalServerError, "media count unavailable") - return - } - sortColumn := "modified_at" - switch r.URL.Query().Get("sortBy") { - case "created": - sortColumn = "created_at" - case "title": - sortColumn = "LOWER(COALESCE(title, original_filename, media_key))" - } - sortDirection := "DESC" - if strings.EqualFold(r.URL.Query().Get("sortDir"), "asc") { - sortDirection = "ASC" - } - limitPlaceholder := add(pageSize) - offsetPlaceholder := add((pageNumber - 1) * pageSize) - query := fmt.Sprintf(` - SELECT id, media_key, COALESCE(media_type, 'unknown'), COALESCE(title, ''), COALESCE(description, ''), - COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'), - COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), - COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), COALESCE(speed, 0), COALESCE(modified_at, created_at) - FROM media WHERE %s ORDER BY %s %s, id DESC LIMIT %s OFFSET %s`, where, sortColumn, sortDirection, limitPlaceholder, offsetPlaceholder) - rows, err := s.db.Query(r.Context(), query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "media list unavailable") - return - } - defer rows.Close() - items := make([]map[string]any, 0, pageSize) - for rows.Next() { - record, err := scanMedia(rows) - if err != nil { - writeError(w, http.StatusInternalServerError, "media record unavailable") - return - } - items = append(items, record.toJSON()) - } - writeJSON(w, http.StatusOK, map[string]any{"items": items, "total": total, "page": pageNumber, "pageSize": pageSize}) +func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { + c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } -func (s *Server) randomMedia(w http.ResponseWriter, r *http.Request) { - exact := strings.TrimSpace(r.URL.Query().Get("exact")) - query := ` - SELECT id, media_key, COALESCE(media_type, 'unknown'), COALESCE(title, ''), COALESCE(description, ''), - COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'), - COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), - COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), COALESCE(speed, 0), COALESCE(modified_at, created_at) - FROM media WHERE active = TRUE` - args := []any{} - if exact != "" { - query += ` AND (media_key = $1 OR CAST(id AS TEXT) = $1) LIMIT 1` - args = append(args, exact) - } else { - query += ` ORDER BY RANDOM() LIMIT 1` - } - rows, err := s.db.Query(r.Context(), query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "random media unavailable") - return - } - defer rows.Close() - if !rows.Next() { - writeJSON(w, http.StatusNotFound, map[string]any{"data": nil, "error": "no media found"}) - return - } - record, err := scanMedia(rows) - if err != nil { - writeError(w, http.StatusInternalServerError, "random media unavailable") - return - } - item := record.toJSON() - writeJSON(w, http.StatusOK, map[string]any{"data": item, "item": item}) -} - -func (s *Server) streamMedia(w http.ResponseWriter, r *http.Request) { - s.streamMediaIdentifier(w, r, chi.URLParam(r, "id")) -} - -func (s *Server) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { - s.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) -} - -func (s *Server) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { - record, err := s.findMedia(r.Context(), identifier) +func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { + record, err := c.findMedia(r.Context(), identifier) if err != nil { writeError(w, http.StatusNotFound, "media not found") return } - s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath)) + c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath)) } -func (s *Server) thumbnailMedia(w http.ResponseWriter, r *http.Request) { - s.thumbnailMediaIdentifier(w, r, chi.URLParam(r, "id")) +func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { + c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } -func (s *Server) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { - s.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) -} - -func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { +func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { id := identifier - if !safeRelative(id) { + if !SafeRelative(id) { writeError(w, http.StatusBadRequest, "invalid media id") return } if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") { thumbnailPath := "/thumbnails/" + id + ".jpg" - if exists, _, _, err := s.probeCarrierNode(r.Context(), thumbnailPath); err == nil && exists { - s.proxyCarrierNode(w, r, thumbnailPath) + if exists, _, _, err := c.carrierNode.Probe(r.Context(), thumbnailPath); err == nil && exists { + c.carrierNode.Proxy(w, r, thumbnailPath) return } } - record, err := s.findMedia(r.Context(), id) + record, err := c.findMedia(r.Context(), id) if err != nil || !isImagePath(record.FilePath) { writeError(w, http.StatusNotFound, "thumbnail not found") return } - s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath)) + c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath)) } -func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) { - record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) - if err != nil { - writeError(w, http.StatusNotFound, "media not found") - return - } - base := strings.TrimSuffix(record.FilePath, filepath.Ext(record.FilePath)) - for _, candidate := range []string{base + ".funscript", base + ".json"} { - candidatePath := "/media/" + urlPath(candidate) - if exists, _, _, err := s.probeCarrierNode(r.Context(), candidatePath); err == nil && exists { - s.proxyCarrierNode(w, r, candidatePath) - return - } - } - writeError(w, http.StatusNotFound, "funscript not found") -} - -func (s *Server) mediaFileInfo(w http.ResponseWriter, r *http.Request) { - record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) - if err != nil { - writeError(w, http.StatusNotFound, "media not found") - return - } - response := record.toJSON() - if exists, size, modTime, err := s.probeCarrierNode(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists { - response["absolutePath"] = "" - response["sizeBytes"] = size - response["modifiedAt"] = modTime - } - writeJSON(w, http.StatusOK, response) -} - -func (s *Server) probeMedia(w http.ResponseWriter, r *http.Request) { - record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) - if err != nil { - writeError(w, http.StatusNotFound, "media not found") - return - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "media": record.toJSON()}) -} - -func (s *Server) unifiedLibrary(w http.ResponseWriter, r *http.Request) { - s.listMedia(w, r) -} - -func (s *Server) mediaRoutes(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"routes": []string{"/", "/feed", "/tags", "/playlists"}}) -} - -func (s *Server) mediaCategories(w http.ResponseWriter, r *http.Request) { - rows, err := s.db.Query(r.Context(), `SELECT DISTINCT COALESCE(category, '') FROM media WHERE active = TRUE AND COALESCE(category, '') <> '' ORDER BY 1`) - if err != nil { - writeError(w, http.StatusInternalServerError, "categories unavailable") - return - } - defer rows.Close() - categories := make([]string, 0) - for rows.Next() { - var category string - if rows.Scan(&category) == nil { - categories = append(categories, category) - } - } - writeJSON(w, http.StatusOK, map[string]any{"categories": categories}) -} - -func (s *Server) mediaState(w http.ResponseWriter, r *http.Request) { +func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("mediaKey"), chi.URLParam(r, "id"))) if key == "" { writeError(w, http.StatusBadRequest, "missing mediaKey") return } - user := auth.UserFromContext(r.Context()) + user := mediaauth.UserFromContext(r.Context()) var likes, saves, views int64 - if err := s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'like'`, key).Scan(&likes); err != nil { + if err := c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'like'`, key).Scan(&likes); err != nil { writeError(w, http.StatusInternalServerError, "media state unavailable") return } - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'save'`, key).Scan(&saves) - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'view'`, key).Scan(&views) + _ = c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'save'`, key).Scan(&saves) + _ = c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'view'`, key).Scan(&views) liked, saved := false, false if user != nil { - _ = s.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='like')`, user.ID, key).Scan(&liked) - _ = s.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='save')`, user.ID, key).Scan(&saved) + _ = c.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='like')`, user.ID, key).Scan(&liked) + _ = c.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='save')`, user.ID, key).Scan(&saved) } data := map[string]any{"mediaKey": key, "likeCount": likes, "saveCount": saves, "viewCount": views, "likedByUser": liked, "savedByUser": saved} writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": data, "mediaKey": key, "likes": likes, "saves": saves, "views": views}) } -func (s *Server) mediaLike(w http.ResponseWriter, r *http.Request) { - s.mediaStatMutation(w, r, "like") +func (c *Core) mediaLike(w http.ResponseWriter, r *http.Request) { + c.mediaStatMutation(w, r, "like") } -func (s *Server) mediaSave(w http.ResponseWriter, r *http.Request) { - s.mediaStatMutation(w, r, "save") +func (c *Core) mediaSave(w http.ResponseWriter, r *http.Request) { + c.mediaStatMutation(w, r, "save") } -func (s *Server) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { - user := auth.UserFromContext(r.Context()) +func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { + user := mediaauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusUnauthorized, "not authenticated") return @@ -403,19 +270,19 @@ func (s *Server) mediaStatMutation(w http.ResponseWriter, r *http.Request, statT enabled = *input.Value } if enabled { - _, err := s.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, key, user.ID, statType, s.cfg.ServiceName) + _, err := c.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, key, user.ID, statType, c.serviceName) if err != nil { writeError(w, http.StatusInternalServerError, "media state update failed") return } } else { - _, _ = s.db.Exec(r.Context(), `DELETE FROM media_stats WHERE media_key = $1 AND user_id = $2 AND stat_type = $3`, key, user.ID, statType) + _, _ = c.db.Exec(r.Context(), `DELETE FROM media_stats WHERE media_key = $1 AND user_id = $2 AND stat_type = $3`, key, user.ID, statType) } writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"mediaKey": key, "enabled": enabled}}) } -func (s *Server) mediaView(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` } @@ -431,15 +298,15 @@ func (s *Server) mediaView(w http.ResponseWriter, r *http.Request) { if user != nil { userID = user.ID } - if _, err := s.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, 'view', $3)`, key, userID, s.cfg.ServiceName); err != nil { + if _, err := c.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, 'view', $3)`, key, userID, c.serviceName); err != nil { writeError(w, http.StatusInternalServerError, "view could not be recorded") return } writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) } -func (s *Server) mediaViewSession(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` DurationMs int64 `json:"durationMs"` @@ -461,7 +328,7 @@ func (s *Server) mediaViewSession(w http.ResponseWriter, r *http.Request) { if user != nil { userID = user.ID } - _, err := s.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration) + _, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration) if err != nil { writeError(w, http.StatusInternalServerError, "view session could not be recorded") return @@ -469,9 +336,9 @@ func (s *Server) mediaViewSession(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) } -func (s *Server) mediaLiked(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - rows, err := s.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) +func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) + rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "liked media unavailable") return @@ -488,9 +355,9 @@ func (s *Server) mediaLiked(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items}) } -func (s *Server) mediaTags(w http.ResponseWriter, r *http.Request) { +func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(chi.URLParam(r, "id")) - rows, err := s.db.Query(r.Context(), ` + rows, err := c.db.Query(r.Context(), ` SELECT tag, COALESCE(SUM(vote), 0) AS score FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag) WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key) @@ -510,8 +377,8 @@ func (s *Server) mediaTags(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) } -func (s *Server) addMediaTag(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) var input struct { Tag string `json:"tag"` } @@ -525,7 +392,7 @@ func (s *Server) addMediaTag(w http.ResponseWriter, r *http.Request) { return } key := strings.TrimSpace(chi.URLParam(r, "id")) - _, err := s.db.Exec(r.Context(), `INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, key, tag, user.ID) + _, err := c.db.Exec(r.Context(), `INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, key, tag, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "tag could not be added") return @@ -533,8 +400,8 @@ func (s *Server) addMediaTag(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, map[string]any{"tag": tag}) } -func (s *Server) voteMediaTag(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) var input struct { Vote int `json:"vote"` } @@ -548,9 +415,9 @@ func (s *Server) voteMediaTag(w http.ResponseWriter, r *http.Request) { } key, tag := strings.TrimSpace(chi.URLParam(r, "id")), strings.TrimSpace(chi.URLParam(r, "tag")) if input.Vote == 0 { - _, _ = s.db.Exec(r.Context(), `DELETE FROM media_tag_votes WHERE media_key=$1 AND LOWER(tag)=LOWER($2) AND user_id=$3`, key, tag, user.ID) + _, _ = c.db.Exec(r.Context(), `DELETE FROM media_tag_votes WHERE media_key=$1 AND LOWER(tag)=LOWER($2) AND user_id=$3`, key, tag, user.ID) } else { - _, err := s.db.Exec(r.Context(), `INSERT INTO media_tag_votes (media_key, tag, user_id, vote) VALUES ($1, $2, $3, $4) ON CONFLICT (media_key, tag, user_id) DO UPDATE SET vote = EXCLUDED.vote`, key, tag, user.ID, input.Vote) + _, err := c.db.Exec(r.Context(), `INSERT INTO media_tag_votes (media_key, tag, user_id, vote) VALUES ($1, $2, $3, $4) ON CONFLICT (media_key, tag, user_id) DO UPDATE SET vote = EXCLUDED.vote`, key, tag, user.ID, input.Vote) if err != nil { writeError(w, http.StatusInternalServerError, "tag vote failed") return @@ -559,9 +426,9 @@ func (s *Server) voteMediaTag(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote}) } -func (s *Server) tagSuggestions(w http.ResponseWriter, r *http.Request) { +func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) { limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 1000) - rows, err := s.db.Query(r.Context(), `SELECT tag, COUNT(*) AS frequency FROM media_tags GROUP BY tag ORDER BY frequency DESC, LOWER(tag) LIMIT $1`, limit) + rows, err := c.db.Query(r.Context(), `SELECT tag, COUNT(*) AS frequency FROM media_tags GROUP BY tag ORDER BY frequency DESC, LOWER(tag) LIMIT $1`, limit) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) return @@ -578,12 +445,12 @@ func (s *Server) tagSuggestions(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) } -func (s *Server) tagMedia(w http.ResponseWriter, r *http.Request) { +func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) { tag := strings.ToLower(strings.TrimSpace(chi.URLParam(r, "tag"))) pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000) limit := optionalInt(r.URL.Query().Get("limit"), 24, 1, 100) offset := (pageNumber - 1) * limit - rows, err := s.db.Query(r.Context(), `SELECT DISTINCT media_key FROM media_tags WHERE LOWER(tag) = $1 ORDER BY media_key LIMIT $2 OFFSET $3`, tag, limit, offset) + rows, err := c.db.Query(r.Context(), `SELECT DISTINCT media_key FROM media_tags WHERE LOWER(tag) = $1 ORDER BY media_key LIMIT $2 OFFSET $3`, tag, limit, offset) if err != nil { writeError(w, http.StatusInternalServerError, "tag media unavailable") return @@ -599,9 +466,9 @@ func (s *Server) tagMedia(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber}) } -func (s *Server) playlists(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) - rows, err := s.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID) +func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) + rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "playlists unavailable") return @@ -619,13 +486,13 @@ func (s *Server) playlists(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists")) } -func (s *Server) playlistSummary(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists")) return } - rows, err := s.db.Query(r.Context(), `SELECT p.id, p.name, p.created_at, COUNT(i.id) FROM playlists p LEFT JOIN playlist_items i ON p.id=i.playlist_id WHERE p.user_id=$1 GROUP BY p.id ORDER BY p.created_at DESC`, user.ID) + rows, err := c.db.Query(r.Context(), `SELECT p.id, p.name, p.created_at, COUNT(i.id) FROM playlists p LEFT JOIN playlist_items i ON p.id=i.playlist_id WHERE p.user_id=$1 GROUP BY p.id ORDER BY p.created_at DESC`, user.ID) if err != nil { writeError(w, http.StatusInternalServerError, "playlist summary unavailable") return @@ -643,8 +510,8 @@ func (s *Server) playlistSummary(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists summary")) } -func (s *Server) playlist(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { writeError(w, http.StatusNotFound, "playlist not found") @@ -652,15 +519,15 @@ func (s *Server) playlist(w http.ResponseWriter, r *http.Request) { } var name string var created time.Time - if err := s.db.QueryRow(r.Context(), `SELECT name, created_at FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID).Scan(&name, &created); err != nil { + if err := c.db.QueryRow(r.Context(), `SELECT name, created_at FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID).Scan(&name, &created); err != nil { writeError(w, http.StatusNotFound, "playlist not found") return } writeJSON(w, http.StatusOK, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist")) } -func (s *Server) createPlaylist(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) var input struct { Name string `json:"name"` } @@ -673,24 +540,24 @@ func (s *Server) createPlaylist(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "playlist name is invalid") return } - _, _ = s.db.Exec(r.Context(), `INSERT INTO playlists (user_id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING`, user.ID, name) + _, _ = c.db.Exec(r.Context(), `INSERT INTO playlists (user_id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING`, user.ID, name) var id int64 var created time.Time - if err := s.db.QueryRow(r.Context(), `SELECT id, created_at FROM playlists WHERE user_id=$1 AND LOWER(name)=LOWER($2)`, user.ID, name).Scan(&id, &created); err != nil { + if err := c.db.QueryRow(r.Context(), `SELECT id, created_at FROM playlists WHERE user_id=$1 AND LOWER(name)=LOWER($2)`, user.ID, name).Scan(&id, &created); err != nil { writeError(w, http.StatusInternalServerError, "playlist could not be created") return } writeJSON(w, http.StatusCreated, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist created")) } -func (s *Server) deletePlaylist(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") return } - result, err := s.db.Exec(r.Context(), `DELETE FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID) + result, err := c.db.Exec(r.Context(), `DELETE FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID) if err != nil || result.RowsAffected() == 0 { writeError(w, http.StatusNotFound, "playlist not found") return @@ -698,19 +565,19 @@ func (s *Server) deletePlaylist(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist deleted")) } -func (s *Server) playlistItems(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { writeError(w, http.StatusNotFound, "playlist not found") return } var owner int64 - if err := s.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID { + if err := c.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID { writeError(w, http.StatusNotFound, "playlist not found") return } - rows, err := s.db.Query(r.Context(), `SELECT id, media_key, COALESCE(position, 0), created_at FROM playlist_items WHERE playlist_id=$1 ORDER BY COALESCE(position, 0), created_at`, id) + rows, err := c.db.Query(r.Context(), `SELECT id, media_key, COALESCE(position, 0), created_at FROM playlist_items WHERE playlist_id=$1 ORDER BY COALESCE(position, 0), created_at`, id) if err != nil { writeError(w, http.StatusInternalServerError, "playlist items unavailable") return @@ -729,15 +596,15 @@ func (s *Server) playlistItems(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"items": items}, "Playlist items")) } -func (s *Server) addPlaylistItem(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") return } var owner int64 - if err := s.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID { + if err := c.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID { writeError(w, http.StatusNotFound, "playlist not found") return } @@ -754,7 +621,7 @@ func (s *Server) addPlaylistItem(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "mediaKey is required") return } - _, err = s.db.Exec(r.Context(), `INSERT INTO playlist_items (playlist_id, media_key) VALUES ($1, $2) ON CONFLICT DO NOTHING`, id, key) + _, err = c.db.Exec(r.Context(), `INSERT INTO playlist_items (playlist_id, media_key) VALUES ($1, $2) ON CONFLICT DO NOTHING`, id, key) if err != nil { writeError(w, http.StatusInternalServerError, "playlist item could not be added") return @@ -762,8 +629,8 @@ func (s *Server) addPlaylistItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, success(map[string]any{"mediaKey": key}, "Playlist item added")) } -func (s *Server) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -778,7 +645,7 @@ func (s *Server) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { return } key := strings.TrimSpace(firstNonEmpty(input.MediaKey, input.MediaKeySnake)) - result, err := s.db.Exec(r.Context(), `DELETE FROM playlist_items WHERE playlist_id=$1 AND media_key=$2 AND EXISTS (SELECT 1 FROM playlists WHERE id=$1 AND user_id=$3)`, id, key, user.ID) + result, err := c.db.Exec(r.Context(), `DELETE FROM playlist_items WHERE playlist_id=$1 AND media_key=$2 AND EXISTS (SELECT 1 FROM playlists WHERE id=$1 AND user_id=$3)`, id, key, user.ID) if err != nil || result.RowsAffected() == 0 { writeError(w, http.StatusNotFound, "playlist item not found") return @@ -786,8 +653,8 @@ func (s *Server) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist item deleted")) } -func (s *Server) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusNotFound, "playlist not found") return @@ -798,15 +665,15 @@ func (s *Server) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { return } var key string - if err := s.db.QueryRow(r.Context(), `SELECT i.media_key FROM playlist_items i JOIN playlists p ON p.id=i.playlist_id WHERE i.playlist_id=$1 AND p.user_id=$2 ORDER BY RANDOM() LIMIT 1`, id, user.ID).Scan(&key); err != nil { + if err := c.db.QueryRow(r.Context(), `SELECT i.media_key FROM playlist_items i JOIN playlists p ON p.id=i.playlist_id WHERE i.playlist_id=$1 AND p.user_id=$2 ORDER BY RANDOM() LIMIT 1`, id, user.ID).Scan(&key); err != nil { writeError(w, http.StatusNotFound, "no media in playlist") return } writeJSON(w, http.StatusOK, success(map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}, "Random playlist media")) } -func (s *Server) reorderPlaylist(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid playlist id") @@ -825,13 +692,13 @@ func (s *Server) reorderPlaylist(w http.ResponseWriter, r *http.Request) { ids = input.ItemIDs } for position, itemID := range ids { - _, _ = s.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID) + _, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID) } writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered")) } -func (s *Server) profile(w http.ResponseWriter, r *http.Request) { - user := auth.UserFromContext(r.Context()) +func (c *Core) profile(w http.ResponseWriter, r *http.Request) { + user := mediaauth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, map[string]any{"user": nil}) return @@ -839,10 +706,10 @@ func (s *Server) profile(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"user": user}) } -func (s *Server) findMedia(ctx context.Context, identifier string) (MediaRecord, error) { +func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) { identifier = strings.TrimSpace(identifier) var record MediaRecord - row := s.db.QueryRow(ctx, ` + row := c.db.QueryRow(ctx, ` SELECT id, media_key, COALESCE(media_type, 'unknown'), COALESCE(title, ''), COALESCE(description, ''), COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'), COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), @@ -879,49 +746,18 @@ func (s *Server) findMedia(ctx context.Context, identifier string) (MediaRecord, return record, nil } -type rowScanner interface{ Scan(dest ...any) error } - -func scanMedia(row rowScanner) (MediaRecord, error) { - var record MediaRecord - var title, description string - var width, height int - var duration, size int64 - var speed float32 - if err := row.Scan(&record.ID, &record.MediaKey, &record.MediaType, &title, &description, &record.FilePath, &record.OriginalName, &record.Source, &width, &height, &duration, &size, &record.IsVR, &record.HasFunscript, &speed, &record.ModifiedAt); err != nil { - return record, err - } - if title != "" { - record.Title = &title - } - if description != "" { - record.Description = &description - } - if width > 0 { - record.Width = &width - } - if height > 0 { - record.Height = &height - } - if duration > 0 { - record.DurationMs = &duration - } - if size > 0 { - record.SizeBytes = &size - } - if speed > 0 { - record.Speed = &speed - } - return record, nil -} - -func (record MediaRecord) toJSON() map[string]any { +// ToJSON is the shared wire shape for a media record, matching every +// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/ +// etc.) - services with their own media listing routes (e.g. MediaViewer's +// mountViewerRoutes) should use this too, for a consistent shape. +func (record MediaRecord) ToJSON() map[string]any { filename := record.OriginalName if filename == "" { filename = filepath.Base(urlPath(record.FilePath)) } mediaType := record.MediaType if mediaType == "unknown" || mediaType == "" { - mediaType = inferMediaType(filename) + mediaType = InferMediaType(filename) } return map[string]any{ "id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey, @@ -934,22 +770,74 @@ func (record MediaRecord) toJSON() map[string]any { } } -func (s *Server) resolveMediaPath(ctx context.Context, relative string) (string, error) { - return s.resolveUnderRoots(relative, s.effectiveMediaRoots(ctx)) +// SettingValue reads one key from the shared `settings` table, returning +// fallback if it is unset or the read fails. +func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) string { + var value string + if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" { + return fallback + } + return value } -// resolveAnyMediaPath additionally checks DownloadsRoot and OutputRoot - the mirror image of -// mediaKeyForPath, which computes a key relative to whichever of those roots a file lives under. -func (s *Server) resolveAnyMediaPath(ctx context.Context, relative string) (string, error) { - roots := append(s.effectiveMediaRoots(ctx), s.cfg.DownloadsRoot, s.cfg.OutputRoot) - return s.resolveUnderRoots(relative, roots) +// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true, +// anything else is fallback). +func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool { + value := strings.ToLower(strings.TrimSpace(SettingValue(ctx, db, key, ""))) + if value == "" { + return fallback + } + return value == "1" || value == "true" || value == "yes" || value == "on" } -func (s *Server) resolveThumbnailPath(relative string) (string, error) { - return s.resolveUnderRoots(relative, []string{s.cfg.ThumbnailRoot}) +// SaveSetting upserts one key in the shared `settings` table. +func SaveSetting(ctx context.Context, db *pgxpool.Pool, key, value string) error { + _, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value) + return err } -func (s *Server) resolveUnderRoots(value string, roots []string) (string, error) { +// --- path-safety helpers (generic, no Core dependency) --- + +// SafeRelative reports whether value is a relative path with no `..` +// traversal or absolute-path escape (Windows drive letters included). +func SafeRelative(value string) bool { + value = strings.TrimSpace(value) + windowsAbsolute := len(value) >= 2 && value[1] == ':' + return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`) +} + +// WithinRoot reports whether candidate is (non-strictly) inside root. +func WithinRoot(root, candidate string) bool { + rel, err := filepath.Rel(root, candidate) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) +} + +// SameRealRoot reports whether candidate's symlink-resolved real path is +// still inside root's symlink-resolved real path (guards against a symlink +// planted inside root pointing outside it). +func SameRealRoot(root, candidate string) bool { + realRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return false + } + realCandidate, err := filepath.EvalSymlinks(candidate) + if err != nil { + return false + } + realRoot, err = filepath.Abs(realRoot) + if err != nil { + return false + } + realCandidate, err = filepath.Abs(realCandidate) + return err == nil && WithinRoot(realRoot, realCandidate) +} + +// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative +// path) against each of roots in order, returning the first root it +// actually exists under as a real file (not a directory, and not merely a +// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root +// matches. +func ResolveUnderRoots(value string, roots []string) (string, error) { value = strings.TrimSpace(strings.TrimPrefix(value, "/media/")) value = strings.TrimPrefix(value, "/") if value == "" || strings.ContainsRune(value, 0) { @@ -965,18 +853,20 @@ func (s *Server) resolveUnderRoots(value string, roots []string) (string, error) candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate)) } candidate, err = filepath.Abs(candidate) - if err != nil || !withinRoot(rootAbs, candidate) { + if err != nil || !WithinRoot(rootAbs, candidate) { continue } info, err := os.Stat(candidate) - if err == nil && !info.IsDir() && sameRealRoot(rootAbs, candidate) { + if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) { return candidate, nil } } return "", os.ErrNotExist } -func (s *Server) serveFile(w http.ResponseWriter, r *http.Request, fullPath string) { +// ServeFile serves fullPath (an already-resolved, already-safety-checked +// path) with the correct Content-Type and range-request support. +func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) { file, err := os.Open(fullPath) if err != nil { writeError(w, http.StatusNotFound, "file not found") @@ -994,43 +884,16 @@ func (s *Server) serveFile(w http.ResponseWriter, r *http.Request, fullPath stri http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file) } -func success(data any, message string) map[string]any { - return map[string]any{"success": true, "data": data, "message": message} -} - -func decodeRequestJSON(r *http.Request, target any) error { - defer r.Body.Close() - decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024)) - decoder.DisallowUnknownFields() - return decoder.Decode(target) -} - -func safeRelative(value string) bool { - value = strings.TrimSpace(value) - windowsAbsolute := len(value) >= 2 && value[1] == ':' - return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`) -} - -func withinRoot(root, candidate string) bool { - rel, err := filepath.Rel(root, candidate) - return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) -} - -func sameRealRoot(root, candidate string) bool { - realRoot, err := filepath.EvalSymlinks(root) - if err != nil { - return false +// InferMediaType guesses a media type from a filename's extension. +func InferMediaType(value string) string { + switch strings.ToLower(filepath.Ext(value)) { + case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg": + return "image" + case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", ".wma": + return "audio" + default: + return "video" } - realCandidate, err := filepath.EvalSymlinks(candidate) - if err != nil { - return false - } - realRoot, err = filepath.Abs(realRoot) - if err != nil { - return false - } - realCandidate, err = filepath.Abs(realCandidate) - return err == nil && withinRoot(realRoot, realCandidate) } func isImagePath(value string) bool { @@ -1042,17 +905,6 @@ func isImagePath(value string) bool { } } -func inferMediaType(value string) string { - switch strings.ToLower(filepath.Ext(value)) { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg": - return "image" - case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", ".wma": - return "audio" - default: - return "video" - } -} - func mediaStreamURL(identifier string) string { return "/api/media/stream?mediaKey=" + url.QueryEscape(strings.TrimSpace(identifier)) } @@ -1076,3 +928,104 @@ func firstNonEmpty(values ...string) string { } return "" } + +func optionalInt(value string, fallback, minimum, maximum int) int { + parsed, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return fallback + } + if parsed < minimum { + return minimum + } + if parsed > maximum { + return maximum + } + return parsed +} + +func intValue(value *int) any { + if value == nil { + return nil + } + return *value +} + +func int64Value(value *int64) any { + if value == nil { + return nil + } + return *value +} + +func floatValue(value *float32) any { + if value == nil { + return nil + } + return *value +} + +func success(data any, message string) map[string]any { + return map[string]any{"success": true, "data": data, "message": message} +} + +func decodeRequestJSON(r *http.Request, target any) error { + defer r.Body.Close() + decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024)) + decoder.DisallowUnknownFields() + return decoder.Decode(target) +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message, "message": message}) +} + +// --- sync-message helpers (shared with syncsocket's own copies; duplicated +// here rather than exported from syncsocket, since these are trivially small +// and this keeps mediacore and syncsocket independently buildable) --- + +func syncString(message map[string]any, key string) string { + value, _ := message[key].(string) + return strings.TrimSpace(value) +} + +func boundedSyncString(value string) string { + const maxSyncIdentifier = 128 + value = strings.TrimSpace(value) + if len(value) > maxSyncIdentifier { + return value[:maxSyncIdentifier] + } + return value +} + +func syncBool(message map[string]any, key string) bool { + value, _ := message[key].(bool) + return value +} + +func syncInt(message map[string]any, key string, fallback int64) int64 { + value, ok := message[key].(float64) + if !ok { + return fallback + } + if value < 0 { + return 0 + } + return int64(value) +} + +func syncFPS(message map[string]any) int64 { + fps := syncInt(message, "fps", 30) + if fps < 1 { + return 1 + } + if fps > 240 { + return 240 + } + return fps +} diff --git a/shared/backend/mediacore/migrate.go b/shared/backend/mediacore/migrate.go new file mode 100644 index 0000000..ad457e5 --- /dev/null +++ b/shared/backend/mediacore/migrate.go @@ -0,0 +1,181 @@ +package mediacore + +import "context" + +// Migrate creates every table (and its indexes) mediacore's shared routes +// read or write, using CREATE TABLE/INDEX IF NOT EXISTS so whichever +// media-family service starts first against a fresh database creates them +// and every other service's own startup is a no-op. Statements are copied +// verbatim from the pre-split monolith's +// internal/database/migrations/001_initial.sql, limited to the tables +// mediacore itself owns (media, media_stats, media_view_sessions, +// media_tags, media_tag_votes, settings, playlists, playlist_items, +// workflow_jobs, thumbnails) plus `users`, which several of those +// reference via foreign key even though identity itself now lives in +// AuthGuard (see mediaauth's package doc comment) - the column is kept for +// FK integrity, not queried by mediacore. +// +// Each per-service backend additionally runs its own migration for tables +// it exclusively owns (e.g. ContentScanner's media_worker_jobs/ +// media_analysis_tasks, CraftStudio's generated_media/downloaded_media, +// ProjectConfigurator's mount_paths) - those are NOT run here. +func (c *Core) Migrate(ctx context.Context) error { + for _, statement := range migrationStatements { + if _, err := c.db.Exec(ctx, statement); err != nil { + return err + } + } + return nil +} + +var migrationStatements = []string{ + `CREATE EXTENSION IF NOT EXISTS pgcrypto`, + `CREATE EXTENSION IF NOT EXISTS pg_trgm`, + + `CREATE TABLE IF NOT EXISTS users ( + id BIGSERIAL PRIMARY KEY, + email TEXT NOT NULL UNIQUE, + username TEXT, + password_hash TEXT NOT NULL, + avatar_url TEXT, + bio TEXT, + role TEXT NOT NULL DEFAULT 'user', + permissions JSONB NOT NULL DEFAULT '{}'::jsonb, + disabled BOOLEAN NOT NULL DEFAULT FALSE, + totp_secret TEXT, + mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE, + mfa_backup_codes JSONB, + password_reset_token TEXT, + password_reset_expires TIMESTAMPTZ, + last_login_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL`, + `CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email))`, + + `CREATE TABLE IF NOT EXISTS media ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + media_key TEXT NOT NULL UNIQUE, + media_type TEXT NOT NULL DEFAULT 'unknown', + app TEXT, + source TEXT NOT NULL DEFAULT 'Filesystem', + title TEXT, + description TEXT, + category TEXT, + file_path TEXT, + original_filename TEXT, + active BOOLEAN NOT NULL DEFAULT TRUE, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + width INT, + height INT, + duration_ms BIGINT, + size_bytes BIGINT, + is_vr BOOLEAN NOT NULL DEFAULT FALSE, + has_funscript BOOLEAN NOT NULL DEFAULT FALSE, + speed REAL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `CREATE INDEX IF NOT EXISTS media_active_idx ON media (active)`, + `CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path)`, + `CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')))`, + `CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type)`, + + `CREATE TABLE IF NOT EXISTS media_stats ( + id BIGSERIAL PRIMARY KEY, + media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, + media_key TEXT NOT NULL, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + stat_type TEXT NOT NULL, + app TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL`, + `CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type)`, + + `CREATE TABLE IF NOT EXISTS media_view_sessions ( + id BIGSERIAL PRIMARY KEY, + media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, + media_key TEXT NOT NULL, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + duration_ms BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + + `CREATE TABLE IF NOT EXISTS media_tags ( + id BIGSERIAL PRIMARY KEY, + media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, + media_key TEXT NOT NULL, + tag TEXT NOT NULL, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (media_key, tag, user_id) + )`, + `CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag))`, + `CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key)`, + // AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id) + // constraint does not dedupe NULLs against each other, so a dedicated partial index is + // required to make repeated analysis runs idempotent instead of piling up duplicate tag rows. + `CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL`, + + `CREATE TABLE IF NOT EXISTS media_tag_votes ( + id BIGSERIAL PRIMARY KEY, + media_key TEXT NOT NULL, + tag TEXT NOT NULL, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (media_key, tag, user_id) + )`, + + `CREATE TABLE IF NOT EXISTS playlists ( + id BIGSERIAL PRIMARY KEY, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + name TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (user_id, name) + )`, + `CREATE TABLE IF NOT EXISTS playlist_items ( + id BIGSERIAL PRIMARY KEY, + playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, + media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, + media_key TEXT NOT NULL, + position INT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (playlist_id, media_key) + )`, + + `CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`, + + `CREATE TABLE IF NOT EXISTS workflow_jobs ( + id TEXT PRIMARY KEY, + service TEXT NOT NULL, + tool TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'queued', + progress INT NOT NULL DEFAULT 0, + request JSONB NOT NULL DEFAULT '{}'::jsonb, + result JSONB NOT NULL DEFAULT '{}'::jsonb, + error_message TEXT, + user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + started_at TIMESTAMPTZ, + finished_at TIMESTAMPTZ + )`, + `CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC)`, + + `CREATE TABLE IF NOT EXISTS thumbnails ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, + source_path TEXT UNIQUE, + width INT, + height INT, + file_size_bytes BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, +} diff --git a/shared/media-backend/internal/server/sync.go b/shared/backend/syncsocket/syncsocket.go similarity index 59% rename from shared/media-backend/internal/server/sync.go rename to shared/backend/syncsocket/syncsocket.go index 33da0a0..d6da69f 100644 --- a/shared/media-backend/internal/server/sync.go +++ b/shared/backend/syncsocket/syncsocket.go @@ -1,4 +1,21 @@ -package server +// Package syncsocket is the media-backend family's cross-device playback-sync +// websocket hub: multiple clients viewing the same media session (identified +// by a caller-chosen sessionId) see each other's play/pause/seek/remote-control +// state live. Promoted unchanged from each service's own internal sync.go into +// this shared library so the 6 media-family backends that mount it (every one +// except MediaKiosk) use one copy instead of duplicating it. +// +// A service wires this up as: +// +// hub := syncsocket.NewHub() +// router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { +// hub.ServeWebSocket(w, r, cfg.AllowedOrigin) +// }) +// +// and mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/ +// SetHTTPState/Broadcast to read and mutate the same session state the +// websocket peers see. +package syncsocket import ( "context" @@ -18,7 +35,7 @@ const ( maxSyncSessions = 1000 ) -type syncPeer struct { +type peer struct { conn *websocket.Conn writeMu sync.Mutex clientID string @@ -31,9 +48,11 @@ type syncPeer struct { uiMediaIDSet bool } -type syncHub struct { +// Hub tracks every connected sync websocket peer and the last-known playback +// state per session, broadcasting updates to every peer sharing a session. +type Hub struct { mu sync.Mutex - peers map[*syncPeer]struct{} + peers map[*peer]struct{} states map[string]map[string]any playAt map[string]string playAtLocalMs map[string]int64 @@ -41,9 +60,11 @@ type syncHub struct { controlOwners map[string]string } -func newSyncHub() *syncHub { - return &syncHub{ - peers: make(map[*syncPeer]struct{}), +// NewHub returns an empty Hub ready to accept websocket connections and +// serve/mutate HTTP sync state. +func NewHub() *Hub { + return &Hub{ + peers: make(map[*peer]struct{}), states: make(map[string]map[string]any), playAt: make(map[string]string), playAtLocalMs: make(map[string]int64), @@ -52,92 +73,92 @@ func newSyncHub() *syncHub { } } -func (h *syncHub) add(peer *syncPeer) { +func (h *Hub) add(p *peer) { h.mu.Lock() - h.peers[peer] = struct{}{} + h.peers[p] = struct{}{} h.mu.Unlock() } -func (h *syncHub) remove(peer *syncPeer) string { +func (h *Hub) remove(p *peer) string { h.mu.Lock() defer h.mu.Unlock() - delete(h.peers, peer) - if peer.clientID != "" && !h.hasClientLocked(peer.clientID) { - delete(h.controlOwners, peer.clientID) + delete(h.peers, p) + if p.clientID != "" && !h.hasClientLocked(p.clientID) { + delete(h.controlOwners, p.clientID) for targetID, ownerID := range h.controlOwners { - if ownerID == peer.clientID { + if ownerID == p.clientID { delete(h.controlOwners, targetID) } } } - return peer.sessionID + return p.sessionID } -func (h *syncHub) hasClientLocked(clientID string) bool { - for peer := range h.peers { - if peer.clientID == clientID { +func (h *Hub) hasClientLocked(clientID string) bool { + for p := range h.peers { + if p.clientID == clientID { return true } } return false } -func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) { +func (h *Hub) updatePeer(p *peer, clientID, sessionID string) { h.mu.Lock() if clientID != "" { - peer.clientID = clientID + p.clientID = clientID } if sessionID != "" { - peer.sessionID = sessionID + p.sessionID = sessionID } h.mu.Unlock() } -func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) { +func (h *Hub) clientStatus(p *peer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) { h.mu.Lock() defer h.mu.Unlock() if sessionID != "" { - peer.sessionID = sessionID + p.sessionID = sessionID } if view != "" { - peer.uiView = view + p.uiView = view } if mediaIDSet { - peer.uiMediaID = mediaID - peer.uiMediaIDSet = true + p.uiMediaID = mediaID + p.uiMediaIDSet = true } if remoteSet { - peer.remoteControlEnabled = remote - if !remote && h.controlOwners[peer.clientID] != "" { - delete(h.controlOwners, peer.clientID) + p.remoteControlEnabled = remote + if !remote && h.controlOwners[p.clientID] != "" { + delete(h.controlOwners, p.clientID) } } } -func (h *syncHub) clientsLocked(sessionID string) []map[string]any { +func (h *Hub) clientsLocked(sessionID string) []map[string]any { byID := make(map[string]map[string]any) - for peer := range h.peers { - if peer.sessionID != sessionID || peer.clientID == "" { + for p := range h.peers { + if p.sessionID != sessionID || p.clientID == "" { continue } - entry, exists := byID[peer.clientID] + entry, exists := byID[p.clientID] if !exists { entry = map[string]any{ - "clientId": peer.clientID, - "userAgent": peer.userAgent, - "ipAddress": peer.ipAddress, - "remoteControlEnabled": peer.remoteControlEnabled, + "clientId": p.clientID, + "userAgent": p.userAgent, + "ipAddress": p.ipAddress, + "remoteControlEnabled": p.remoteControlEnabled, "controlOwnerClientId": nil, } - byID[peer.clientID] = entry - } else if peer.remoteControlEnabled { + byID[p.clientID] = entry + } else if p.remoteControlEnabled { entry["remoteControlEnabled"] = true } - if peer.uiView != "" { - entry["uiView"] = peer.uiView + if p.uiView != "" { + entry["uiView"] = p.uiView } - if peer.uiMediaIDSet { - entry["uiMediaId"] = peer.uiMediaID + if p.uiMediaIDSet { + entry["uiMediaId"] = p.uiMediaID } } for clientID, entry := range byID { @@ -152,7 +173,7 @@ func (h *syncHub) clientsLocked(sessionID string) []map[string]any { return clients } -func (h *syncHub) stateLocked(sessionID string) map[string]any { +func (h *Hub) stateLocked(sessionID string) map[string]any { state, ok := h.states[sessionID] if !ok { return map[string]any{ @@ -169,13 +190,18 @@ func (h *syncHub) stateLocked(sessionID string) map[string]any { return cloneMap(state) } -func (h *syncHub) httpState(sessionID string) map[string]any { +// HTTPState returns the current playback state for a session, as seen by the +// GET /sync HTTP endpoint (mounted by mediacore). +func (h *Hub) HTTPState(sessionID string) map[string]any { h.mu.Lock() defer h.mu.Unlock() return h.timingLocked(sessionID, h.stateLocked(sessionID)) } -func (h *syncHub) setHTTPState(sessionID string, state map[string]any) { +// SetHTTPState overwrites a session's playback state, as driven by the +// PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this +// with Broadcast to notify connected websocket peers. +func (h *Hub) SetHTTPState(sessionID string, state map[string]any) { h.mu.Lock() defer h.mu.Unlock() h.states[sessionID] = cloneMap(state) @@ -187,7 +213,7 @@ func (h *syncHub) setHTTPState(sessionID string, state map[string]any) { } } -func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[string]any { +func (h *Hub) timingLocked(sessionID string, state map[string]any) map[string]any { paused, _ := state["paused"].(bool) if !paused { if value := h.playAt[sessionID]; value != "" { @@ -203,41 +229,43 @@ func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[strin return state } -func (h *syncHub) broadcast(sessionID string) { +// Broadcast pushes the current state of sessionID to every connected +// websocket peer sharing that session. +func (h *Hub) Broadcast(sessionID string) { h.mu.Lock() state := h.timingLocked(sessionID, h.stateLocked(sessionID)) clients := h.clientsLocked(sessionID) - peers := make([]*syncPeer, 0) - for peer := range h.peers { - if peer.sessionID == sessionID { - peers = append(peers, peer) + peers := make([]*peer, 0) + for p := range h.peers { + if p.sessionID == sessionID { + peers = append(peers, p) } } h.mu.Unlock() message := map[string]any{"type": "sync:state", "state": state, "clients": clients} - for _, peer := range peers { - if err := peer.send(message); err != nil { - _ = peer.conn.Close(websocket.StatusGoingAway, "write failed") + for _, p := range peers { + if err := p.send(message); err != nil { + _ = p.conn.Close(websocket.StatusGoingAway, "write failed") } } } -func (peer *syncPeer) send(message any) error { +func (p *peer) send(message any) error { data, err := json.Marshal(message) if err != nil { return err } - peer.writeMu.Lock() - defer peer.writeMu.Unlock() + p.writeMu.Lock() + defer p.writeMu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() - return peer.conn.Write(ctx, websocket.MessageText, data) + return p.conn.Write(ctx, websocket.MessageText, data) } -func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions { +func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions { options := &websocket.AcceptOptions{} - if s.cfg.AllowedOrigin == "*" { + if allowedOrigin == "*" { options.InsecureSkipVerify = true return options } @@ -249,7 +277,7 @@ func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOption patterns = append(patterns, parsed.Scheme+"://"+parsed.Host) } } - addOrigin(s.cfg.AllowedOrigin) + addOrigin(allowedOrigin) scheme := "http" if r.TLS != nil { scheme = "https" @@ -259,26 +287,29 @@ func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOption return options } -func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) { - conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r)) +// ServeWebSocket upgrades the request to a websocket connection and services +// it until the client disconnects. allowedOrigin should be the service's own +// CORS_ORIGIN config value (or "*" to accept any origin). +func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) { + conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin)) if err != nil { return } - peer := &syncPeer{ + p := &peer{ conn: conn, userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"), ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"), } - s.sync.add(peer) + h.add(p) defer func() { - sessionID := s.sync.remove(peer) + sessionID := h.remove(p) _ = conn.Close(websocket.StatusNormalClosure, "") if sessionID != "" { - s.sync.broadcast(sessionID) + h.Broadcast(sessionID) } }() - _ = peer.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()}) + _ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()}) for { messageType, payload, readErr := conn.Read(r.Context()) if readErr != nil { @@ -291,15 +322,15 @@ func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) { if json.Unmarshal(payload, &message) != nil { continue } - s.handleSyncMessage(peer, message) + h.handleMessage(p, message) } } -func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) { +func (h *Hub) handleMessage(p *peer, message map[string]any) { typ, _ := message["type"].(string) switch typ { case "ws:ping": - _ = peer.send(map[string]any{ + _ = p.send(map[string]any{ "type": "ws:pong", "nonce": syncString(message, "nonce"), "clientSentAt": syncNumberValue(message, "clientSentAt"), @@ -311,41 +342,41 @@ func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) { if clientID == "" || sessionID == "" { return } - s.sync.updatePeer(peer, clientID, sessionID) - s.sync.broadcast(sessionID) + h.updatePeer(p, clientID, sessionID) + h.Broadcast(sessionID) case "client:status": - clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID)) - sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default")) + clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) + sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) if clientID == "" { return } - s.sync.updatePeer(peer, clientID, sessionID) + h.updatePeer(p, clientID, sessionID) mediaID, mediaIDSet := syncMediaID(message) remote, remoteSet := message["remoteControlEnabled"].(bool) - s.sync.clientStatus(peer, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote) - s.sync.broadcast(sessionID) + h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote) + h.Broadcast(sessionID) case "control:claim", "control:release": - s.handleControlMessage(peer, typ, message) + h.handleControlMessage(p, typ, message) case "sync:update": - s.handleSyncUpdate(peer, message) + h.handleSyncUpdate(p, message) } } -func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[string]any) { - requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID)) - sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default")) +func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) { + requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) + sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) targetID := boundedSyncString(syncString(message, "targetClientId")) - if requesterID == "" || targetID == "" || requesterID != peer.clientID { + if requesterID == "" || targetID == "" || requesterID != p.clientID { return } - s.sync.mu.Lock() - owner := s.sync.controlOwners[targetID] + h.mu.Lock() + owner := h.controlOwners[targetID] ok := false reason := "" if typ == "control:claim" { enabled := false - for candidate := range s.sync.peers { + for candidate := range h.peers { if candidate.clientID == targetID && candidate.remoteControlEnabled { enabled = true break @@ -357,20 +388,20 @@ func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[st case owner != "" && owner != requesterID: reason = "busy" default: - s.sync.controlOwners[targetID] = requesterID + h.controlOwners[targetID] = requesterID owner = requesterID ok = true } } else if owner != "" && owner != requesterID { reason = "not-owner" } else { - delete(s.sync.controlOwners, targetID) + delete(h.controlOwners, targetID) owner = "" ok = true } - s.sync.mu.Unlock() + h.mu.Unlock() - _ = peer.send(map[string]any{ + _ = p.send(map[string]any{ "type": "control:ack", "ok": ok, "action": strings.TrimPrefix(typ, "control:"), @@ -378,13 +409,13 @@ func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[st "ownerClientId": nullableString(owner), "reason": nullableString(reason), }) - s.sync.broadcast(sessionID) + h.Broadcast(sessionID) } -func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) { - clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID)) - sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default")) - if clientID == "" || clientID != peer.clientID { +func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) { + clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID)) + sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default")) + if clientID == "" || clientID != p.clientID { return } mediaID, _ := syncMediaID(message) @@ -407,41 +438,41 @@ func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) { toClientID := boundedSyncString(syncString(message, "toClientId")) playAtRaw, hasPlayAt := message["playAt"] - s.sync.mu.Lock() + h.mu.Lock() if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" { - delete(s.sync.playAt, sessionID) - delete(s.sync.playAtLocalMs, sessionID) + delete(h.playAt, sessionID) + delete(h.playAtLocalMs, sessionID) } else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil { - s.sync.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano) + h.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano) if local := syncInt(message, "playAtLocalMs", 0); local > 0 { - s.sync.playAtLocalMs[sessionID] = local + h.playAtLocalMs[sessionID] = local } else { - delete(s.sync.playAtLocalMs, sessionID) + delete(h.playAtLocalMs, sessionID) } } if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 { - s.sync.capturedAtMs[sessionID] = captured + h.capturedAtMs[sessionID] = captured } if toClientID == "" { - s.sync.states[sessionID] = cloneMap(state) - if len(s.sync.states) > maxSyncSessions { - for key := range s.sync.states { - delete(s.sync.states, key) + h.states[sessionID] = cloneMap(state) + if len(h.states) > maxSyncSessions { + for key := range h.states { + delete(h.states, key) break } } } - state = s.sync.timingLocked(sessionID, state) - clients := s.sync.clientsLocked(sessionID) - peers := make([]*syncPeer, 0) + state = h.timingLocked(sessionID, state) + clients := h.clientsLocked(sessionID) + peers := make([]*peer, 0) if toClientID != "" { - for candidate := range s.sync.peers { + for candidate := range h.peers { if candidate.sessionID == sessionID && candidate.clientID == toClientID { peers = append(peers, candidate) } } } - s.sync.mu.Unlock() + h.mu.Unlock() messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients} if toClientID != "" { @@ -452,7 +483,7 @@ func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) { } return } - s.sync.broadcast(sessionID) + h.Broadcast(sessionID) } func syncMediaID(message map[string]any) (any, bool) { @@ -539,3 +570,12 @@ func cloneMap(value map[string]any) map[string]any { } return result } + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} diff --git a/shared/media-backend/.env.example b/shared/media-backend/.env.example deleted file mode 100644 index c6c0183..0000000 --- a/shared/media-backend/.env.example +++ /dev/null @@ -1,23 +0,0 @@ -DATABASE_URL=postgresql://media:media@127.0.0.1:5432/mediadb -MEDIA_SERVICE=viewer -PORT=3000 -WEB_ROOT=../WebUI/build -MEDIA_ROOTS=../media -INPUT_DIR=../input -UPLOAD_COPY_DIR=../copy -OUTPUT_DIR=../output -DOWNLOADS_DIR=../downloads -THUMBNAIL_DIR=../thumbnails -MODEL_CACHE_DIR=../models -WORKFLOWS_DIR=../CraftStudio/public/workflows -FFMPEG_PATH=ffmpeg -FFPROBE_PATH=ffprobe -YT_DLP_PATH=yt-dlp -COMFYUI_URL=http://127.0.0.1:8188 -ANALYZER_MODELS_URL=http://127.0.0.1:8801 -CORS_ORIGIN=http://localhost:5173 -SESSION_COOKIE=session -COOKIE_SECURE=false -AUTHGUARD_URL= -INTERNAL_SERVICE_SECRET= -MAX_UPLOAD_BYTES=50gb diff --git a/shared/media-backend/README.md b/shared/media-backend/README.md deleted file mode 100644 index b875961..0000000 --- a/shared/media-backend/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Shared media backend - -The backend is one Go module, shared across every `MEDIA_SERVICE` instance in the workspace. Set `MEDIA_SERVICE` to `viewer`, `craftstudio`, `contentscanner`, `config`, `moderator`, `kiosk`, or `carriernode` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation. - -From this directory: - -```bash -go mod download -MEDIA_SERVICE=viewer \ -DATABASE_URL=postgresql://media:media@localhost:5432/mediadb \ -WEB_ROOT=../WebUI/build \ -go run ./cmd/mediabackend -``` - -Important settings: - -- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. CarrierNode also walks - every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in - ProjectConfigurator's Projects workspace (the `configured_mounts` setting) regardless of which - project's tab it was entered under - see `effectiveMediaRoots` in - `internal/server/admin_storage.go`. `MEDIA_ROOTS` is only needed for a root that isn't already - configured there. -- `INPUT_DIR`, `UPLOAD_COPY_DIR`, `THUMBNAIL_DIR`, `OUTPUT_DIR`, `DOWNLOADS_DIR`, and `MODEL_CACHE_DIR` control writable storage. -- `WORKFLOWS_DIR` points to the built-in ComfyUI workflow definitions. -- `FFMPEG_PATH`, `FFPROBE_PATH`, and `YT_DLP_PATH` select workflow executables. -- `COMFYUI_URL` configures the generator service. -- `CARRIERNODE_URL` is only the bootstrap fallback for CarrierNode's URL - once configured through - ProjectConfigurator it's read from the `carriernode_url` row in the `settings` table instead - (see `carrierNodeBaseURL` in `internal/server/carriernode_client.go`). -- `INTERNAL_SERVICE_SECRET` protects service-to-service mount and media-proxy APIs. - -Run `go test ./...` before packaging. Each service repo's Dockerfile builds this module (via the -`engine/` submodule) and copies `webui` into the final image; no Node server runs at runtime. - -### Configuration reference - -| Variable | Default | Purpose | -| --- | --- | --- | -| `DATABASE_URL` | required | PostgreSQL connection string | -| `MEDIA_SERVICE` | `viewer` | Route/service selection | -| `PORT` | service-specific | HTTP port | -| `WEB_ROOT` | service web root | Built webui directory | -| `MEDIA_ROOTS` | `./media` | Comma/semicolon-separated media roots | -| `THUMBNAIL_DIR` | `./thumbnails` | Thumbnail storage | -| `INPUT_DIR` | `./input` | Workflow input storage | -| `UPLOAD_COPY_DIR` | `./copy` | Generator copy-upload storage | -| `OUTPUT_DIR` | `./output` | Generated and converted output | -| `DOWNLOADS_DIR` | `./downloads` | yt-dlp/download storage | -| `WORKFLOWS_DIR` | service-specific | ComfyUI workflow JSON files | -| `INTERNAL_SERVICE_SECRET` | empty | Shared-secret service authentication | -| `CORS_ORIGIN` | `http://localhost:5173` | Allowed browser origin | - -See `.env.example` for the complete list. diff --git a/shared/media-backend/SECURITY_AUDIT.md b/shared/media-backend/SECURITY_AUDIT.md deleted file mode 100644 index 0ca2c85..0000000 --- a/shared/media-backend/SECURITY_AUDIT.md +++ /dev/null @@ -1,19 +0,0 @@ -# Shared media backend security notes - -The backend rewrite consolidates the security boundary in `internal/`. - -Implemented controls include: - -- bcrypt passwords, PostgreSQL cookie sessions, TOTP verification, role checks, and disabled-user checks; -- explicit CORS and WebSocket origin validation, security headers, and bounded request bodies; -- additive PostgreSQL migrations with a startup advisory lock; -- traversal, absolute-path, drive-path, and symlink-escape protection for every configured media root; -- fixed ffmpeg argument construction and bounded workflow workers; -- HTTPS-only downloader URLs with credential, private-IP, link-local, metadata-host, and DNS-rebinding checks; -- internal-service secret checks for mount, download, reload, upload, and catalog mutation routes; -- non-root Docker images and no Node server runtime. - -Before deployment, set a unique `INTERNAL_SERVICE_SECRET`, use a strong database password, configure -`CORS_ORIGIN` to the real frontend origin, and enable TLS so `COOKIE_SECURE` can remain enabled. -Review the canonical Go routes when adding a capability; do not reintroduce the removed JavaScript -server paths or Socket.IO transport. diff --git a/shared/media-backend/cmd/mediabackend/main.go b/shared/media-backend/cmd/mediabackend/main.go deleted file mode 100644 index be48a6a..0000000 --- a/shared/media-backend/cmd/mediabackend/main.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "context" - "errors" - "flag" - "log" - "net/http" - "os" - "os/signal" - "syscall" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database" - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/server" -) - -func main() { - service := flag.String("service", "", "service route set to run") - flag.Parse() - if *service != "" { - _ = os.Setenv("MEDIA_SERVICE", *service) - } - cfg, err := config.Load() - if err != nil { - log.Fatalf("config: %v", err) - } - ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - pool, err := database.Open(ctx, cfg.DatabaseURL) - if err != nil { - log.Fatalf("database: %v", err) - } - defer pool.Close() - if err := database.Migrate(ctx, pool); err != nil { - log.Fatalf("migrate: %v", err) - } - app := server.New(cfg, pool) - if err := app.Run(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) { - log.Fatalf("server: %v", err) - } -} diff --git a/shared/media-backend/go.mod b/shared/media-backend/go.mod deleted file mode 100644 index fb4f5bf..0000000 --- a/shared/media-backend/go.mod +++ /dev/null @@ -1,21 +0,0 @@ -module repos.gfranz.ch/Gabriel20xx/shared/media-backend - -go 1.26.5 - -require ( - github.com/coder/websocket v1.8.15 - github.com/go-chi/chi/v5 v5.3.1 - github.com/jackc/pgx/v5 v5.10.0 - golang.org/x/crypto v0.54.0 - repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1 -) - -replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../backend - -require ( - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/text v0.40.0 // indirect -) diff --git a/shared/media-backend/go.sum b/shared/media-backend/go.sum deleted file mode 100644 index 17000cd..0000000 --- a/shared/media-backend/go.sum +++ /dev/null @@ -1,32 +0,0 @@ -github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= -github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= -github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= -github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= -github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= -github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= -golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= -golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/shared/media-backend/internal/auth/auth_authguard_test.go b/shared/media-backend/internal/auth/auth_authguard_test.go deleted file mode 100644 index ee50c8d..0000000 --- a/shared/media-backend/internal/auth/auth_authguard_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package auth - -import ( - "context" - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgxpool" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database" -) - -// testPool returns a connection pool against a real (throwaway) Postgres -// instance, and a cleanup function. DATABASE_URL is expected to point at -// one - these tests are skipped (not failed) when it is unset, mirroring -// the workspace's existing convention for DB-backed test suites (see -// Forks/HordeWorker/tests/conftest.py's identical approach). -func testPool(t *testing.T) *pgxpool.Pool { - t.Helper() - dsn := strings.TrimSpace(os.Getenv("DATABASE_URL")) - if dsn == "" { - t.Skip("DATABASE_URL not set; skipping AuthGuard-proxy auth tests that need a real Postgres") - } - ctx := context.Background() - pool, err := database.Open(ctx, dsn) - if err != nil { - t.Fatalf("open test database: %v", err) - } - if err := database.Migrate(ctx, pool); err != nil { - t.Fatalf("migrate test database: %v", err) - } - if _, err := pool.Exec(ctx, `DELETE FROM settings`); err != nil { - t.Fatalf("reset settings table: %v", err) - } - if _, err := pool.Exec(ctx, `DELETE FROM users`); err != nil { - t.Fatalf("reset users table: %v", err) - } - t.Cleanup(pool.Close) - return pool -} - -// fakeAuthGuard is a minimal stateful in-memory AuthGuard double: enough of -// setup-status/register/login/me/logout to exercise Service's proxy -// behavior end-to-end, mirroring the httptest-server pattern already used -// by shared/backend/authclient's own tests. -type fakeAuthGuard struct { - server *httptest.Server - hasAccount bool - username string - email string - role string - password string - sessions map[string]bool -} - -func newFakeAuthGuard() *fakeAuthGuard { - f := &fakeAuthGuard{sessions: map[string]bool{}} - mux := http.NewServeMux() - mux.HandleFunc("GET /api/setup-status", func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]bool{"setup_required": !f.hasAccount}) - }) - mux.HandleFunc("POST /api/register", func(w http.ResponseWriter, r *http.Request) { - if f.hasAccount { - writeJSON(w, http.StatusConflict, map[string]string{"error": "setup already completed"}) - return - } - var body struct{ Username, Email, Password string } - _ = json.NewDecoder(r.Body).Decode(&body) - f.hasAccount = true - f.username, f.email, f.role, f.password = body.Username, body.Email, "superadmin", body.Password - token := "tok-" + body.Username - f.sessions[token] = true - http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token}) - writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ - "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, - }}) - }) - mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) { - var body struct { - UsernameOrEmail string `json:"username_or_email"` - Password string `json:"password"` - } - _ = json.NewDecoder(r.Body).Decode(&body) - if !f.hasAccount || body.UsernameOrEmail != f.username && body.UsernameOrEmail != f.email || body.Password != f.password { - writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid username or password."}) - return - } - token := "tok-" + f.username - f.sessions[token] = true - http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token}) - writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ - "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, - }}) - }) - mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) { - token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") - if !f.sessions[token] { - writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"}) - return - } - writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ - "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, - }}) - }) - mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) { - token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") - delete(f.sessions, token) - http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", MaxAge: -1}) - writeJSON(w, http.StatusOK, map[string]any{}) - }) - f.server = httptest.NewServer(mux) - return f -} - -func (f *fakeAuthGuard) close() { f.server.Close() } - -func newRequest(method, target string, body string) *http.Request { - var r *http.Request - if body != "" { - r = httptest.NewRequest(method, target, strings.NewReader(body)) - } else { - r = httptest.NewRequest(method, target, nil) - } - return r -} - -func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) { - svc := New(nil, "session", false, "") - user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil)) - if err != nil { - t.Fatalf("CurrentUser() error = %v", err) - } - if user == nil || user.Role != "superadmin" || !user.CanManageUsers { - t.Fatalf("CurrentUser() = %+v, want local superadmin placeholder", user) - } -} - -func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) { - pool := testPool(t) - guard := newFakeAuthGuard() - defer guard.close() - svc := New(pool, "session", false, guard.server.URL) - ctx := context.Background() - - // Signup - req := newRequest(http.MethodPost, "/auth/signup", `{"email":"a@example.com","username":"admin","password":"correct horse battery staple"}`) - rec := httptest.NewRecorder() - svc.Signup(rec, req) - if rec.Code != http.StatusCreated { - t.Fatalf("Signup() status = %d, body = %s", rec.Code, rec.Body.String()) - } - cookie := firstSetCookie(t, rec) - if cookie == "" { - t.Fatal("Signup() did not forward AuthGuard's Set-Cookie") - } - - claimed, err := svc.isSetupClaimed(ctx) - if err != nil || !claimed { - t.Fatalf("isSetupClaimed() = %v, %v, want true, nil", claimed, err) - } - - // A second signup attempt must be rejected (setup already completed). - req2 := newRequest(http.MethodPost, "/auth/signup", `{"email":"b@example.com","username":"other","password":"correct horse battery staple"}`) - rec2 := httptest.NewRecorder() - svc.Signup(rec2, req2) - if rec2.Code != http.StatusConflict { - t.Fatalf("second Signup() status = %d, want 409", rec2.Code) - } - - // CurrentUser resolves via the forwarded cookie. - authedReq := httptest.NewRequest(http.MethodGet, "/auth/me", nil) - authedReq.Header.Set("Cookie", "auth_session="+cookie) - user, err := svc.CurrentUser(authedReq) - if err != nil { - t.Fatalf("CurrentUser() error = %v", err) - } - if user == nil || user.Username != "admin" || user.Role != "superadmin" { - t.Fatalf("CurrentUser() = %+v, want the AuthGuard-registered admin", user) - } - - // Login with wrong password is rejected. - badLogin := newRequest(http.MethodPost, "/auth/login", `{"identifier":"admin","password":"wrong"}`) - badRec := httptest.NewRecorder() - svc.Login(badRec, badLogin) - if badRec.Code != http.StatusUnauthorized { - t.Fatalf("Login() with wrong password status = %d, want 401", badRec.Code) - } - - // Logout clears the session. - logoutReq := httptest.NewRequest(http.MethodPost, "/auth/logout", nil) - logoutReq.Header.Set("Cookie", "auth_session="+cookie) - logoutRec := httptest.NewRecorder() - svc.Logout(logoutRec, logoutReq) - if logoutRec.Code != http.StatusOK { - t.Fatalf("Logout() status = %d", logoutRec.Code) - } -} - -func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing.T) { - pool := testPool(t) - guard := newFakeAuthGuard() - defer guard.close() - guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one - guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!" - - svc := New(pool, "session", false, guard.server.URL) - req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`) - rec := httptest.NewRecorder() - svc.Signup(rec, req) - if rec.Code != http.StatusConflict { - t.Fatalf("Signup() status = %d, body = %s, want 409 (AuthGuard already has an account)", rec.Code, rec.Body.String()) - } - // The local claim must have been released again so a later legitimate flow isn't locked out. - claimed, err := svc.isSetupClaimed(context.Background()) - if err != nil || claimed { - t.Fatalf("isSetupClaimed() = %v, %v, want false after a rejected signup", claimed, err) - } -} - -func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) { - pool := testPool(t) - svc := New(pool, "session", false, "") - - required, err := svc.LoginRequired(context.Background()) - if err != nil || !required { - t.Fatalf("LoginRequired() default = %v, %v, want true, nil", required, err) - } - - rec := httptest.NewRecorder() - svc.UpdateAccessSettings(rec, newRequest(http.MethodPut, "/api/auth/access", `{"loginRequired":false}`)) - if rec.Code != http.StatusOK { - t.Fatalf("UpdateAccessSettings() status = %d", rec.Code) - } - required, err = svc.LoginRequired(context.Background()) - if err != nil || required { - t.Fatalf("LoginRequired() after disabling = %v, %v, want false, nil", required, err) - } -} - -func firstSetCookie(t *testing.T, rec *httptest.ResponseRecorder) string { - t.Helper() - for _, raw := range rec.Result().Cookies() { - if raw.Name == "auth_session" && raw.Value != "" { - return raw.Value - } - } - return "" -} diff --git a/shared/media-backend/internal/config/config.go b/shared/media-backend/internal/config/config.go deleted file mode 100644 index 5cafe40..0000000 --- a/shared/media-backend/internal/config/config.go +++ /dev/null @@ -1,238 +0,0 @@ -package config - -import ( - "fmt" - "os" - "path/filepath" - "strconv" - "strings" -) - -type Service string - -const ( - Viewer Service = "viewer" - CraftStudio Service = "craftstudio" - ContentScanner Service = "contentscanner" - ConfigService Service = "config" - Moderator Service = "moderator" - Kiosk Service = "kiosk" - CarrierNode Service = "carriernode" -) - -type Config struct { - Port string - DatabaseURL string - Service Service - ServiceName string - WebRoot string - MediaRoots []string - InputRoot string - CopyRoot string - WorkflowsRoot string - ThumbnailRoot string - OutputRoot string - DownloadsRoot string - ModelsRoot string - AllowedOrigin string - PublicURL string - SessionCookie string - SecureCookies bool - // AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard); - // empty means auth-disabled mode (see internal/auth's package doc - // comment). Read raw via os.Getenv rather than envOr since "" is a - // meaningful, distinct value here (not a fallback-worthy blank). - AuthGuardURL string - InternalServiceSecret string - FFmpeg string - FFprobe string - YTDLP string - ComfyURL string - AnalyzerModelsURL string - CarrierNodeURL string - MaxUploadBytes int64 - TLSCertFile string - TLSKeyFile string -} - -func Load() (*Config, error) { - service := normalizeService(os.Getenv("MEDIA_SERVICE")) - if service == "" { - service = normalizeService(os.Getenv("SERVICE")) - } - if service == "" { - service = Viewer - } - - name := serviceName(service) - port := envOr("PORT", defaultPort(service)) - root := envOr("MEDIA_ROOT", envOr("MEDIA_PATH", "./media")) - roots := splitPaths(os.Getenv("MEDIA_ROOTS")) - if len(roots) == 0 { - roots = []string{root} - } - for i := range roots { - roots[i] = filepath.Clean(roots[i]) - } - - maxUpload, err := parseBytes(envOr("MAX_UPLOAD_BYTES", "53687091200")) - if err != nil { - return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err) - } - - cfg := &Config{ - Port: port, - DatabaseURL: strings.TrimSpace(os.Getenv("DATABASE_URL")), - Service: service, - ServiceName: name, - WebRoot: resolveWebRoot(service), - MediaRoots: roots, - InputRoot: filepath.Clean(envOr("INPUT_DIR", "./input")), - CopyRoot: filepath.Clean(envOr("UPLOAD_COPY_DIR", "./copy")), - WorkflowsRoot: filepath.Clean(envOr("WORKFLOWS_DIR", filepath.Join("..", "CraftStudio", "public", "workflows"))), - ThumbnailRoot: filepath.Clean(envOr("THUMBNAIL_DIR", "./thumbnails")), - OutputRoot: filepath.Clean(envOr("OUTPUT_DIR", "./output")), - DownloadsRoot: filepath.Clean(envOr("DOWNLOADS_DIR", "./downloads")), - ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")), - AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"), - PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"), - SessionCookie: envOr("SESSION_COOKIE", "session"), - SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""), - AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")), - InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")), - FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"), - FFprobe: envOr("FFPROBE_PATH", "ffprobe"), - YTDLP: envOr("YT_DLP_PATH", "yt-dlp"), - ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"), - AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"), - CarrierNodeURL: strings.TrimRight(envOr("CARRIERNODE_URL", "http://127.0.0.1:3003"), "/"), - MaxUploadBytes: maxUpload, - TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")), - TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")), - } - - if cfg.DatabaseURL == "" { - return nil, fmt.Errorf("DATABASE_URL is required") - } - if (cfg.TLSCertFile == "") != (cfg.TLSKeyFile == "") { - return nil, fmt.Errorf("TLS_CERT_FILE and TLS_KEY_FILE must be set together") - } - return cfg, nil -} - -func normalizeService(value string) Service { - switch strings.ToLower(strings.TrimSpace(value)) { - case "viewer", "mediaviewer": - return Viewer - case "craftstudio": - return CraftStudio - case "contentscanner": - return ContentScanner - case "config", "mediaconfig", "projectconfigurator": - return ConfigService - case "moderator", "mediamoderator": - return Moderator - case "kiosk", "mediakiosk": - return Kiosk - case "carriernode": - return CarrierNode - default: - return "" - } -} - -func serviceName(service Service) string { - switch service { - case Viewer: - return "MediaViewer" - case CraftStudio: - return "CraftStudio" - case ContentScanner: - return "ContentScanner" - case ConfigService: - return "ProjectConfigurator" - case Moderator: - return "MediaModerator" - case Kiosk: - return "MediaKiosk" - case CarrierNode: - return "CarrierNode" - default: - return "Shared Service" - } -} - -func defaultPort(service Service) string { - switch service { - case ConfigService: - return "3005" - case Moderator: - return "8090" - case CarrierNode: - return "3003" - default: - return "3000" - } -} - -func resolveWebRoot(_ Service) string { - if value := strings.TrimSpace(os.Getenv("WEB_ROOT")); value != "" { - return filepath.Clean(value) - } - return filepath.Join("..", "WebUI", "build") -} - -func splitPaths(value string) []string { - parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' }) - result := make([]string, 0, len(parts)) - for _, part := range parts { - if trimmed := strings.TrimSpace(part); trimmed != "" { - result = append(result, trimmed) - } - } - return result -} - -func parseBytes(value string) (int64, error) { - value = strings.TrimSpace(strings.ToLower(value)) - if value == "" { - return 0, nil - } - multiplier := int64(1) - suffixes := []struct { - suffix string - factor int64 - }{ - {"gb", 1 << 30}, - {"mb", 1 << 20}, - {"kb", 1 << 10}, - {"b", 1}, - } - for _, s := range suffixes { - if strings.HasSuffix(value, s.suffix) { - value = strings.TrimSpace(strings.TrimSuffix(value, s.suffix)) - multiplier = s.factor - break - } - } - n, err := strconv.ParseInt(value, 10, 64) - if err != nil || n < 0 { - return 0, fmt.Errorf("must be a non-negative byte count") - } - return n * multiplier, nil -} - -func envOr(key, fallback string) string { - if value := strings.TrimSpace(os.Getenv(key)); value != "" { - return value - } - return fallback -} - -func envBool(key string, fallback bool) bool { - value := strings.ToLower(strings.TrimSpace(os.Getenv(key))) - if value == "" { - return fallback - } - return value == "1" || value == "true" || value == "yes" || value == "on" -} diff --git a/shared/media-backend/internal/config/config_test.go b/shared/media-backend/internal/config/config_test.go deleted file mode 100644 index 3a3a8ea..0000000 --- a/shared/media-backend/internal/config/config_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package config - -import ( - "testing" -) - -func TestLoadDefaultsAndServiceSelection(t *testing.T) { - t.Setenv("DATABASE_URL", "postgres://media:media@localhost/mediadb") - t.Setenv("MEDIA_SERVICE", "MediaKiosk") - t.Setenv("SERVICE", "viewer") - t.Setenv("MEDIA_ROOTS", `./media;./other-media`) - t.Setenv("MAX_UPLOAD_BYTES", "2mb") - t.Setenv("WEB_ROOT", "./webui") - - cfg, err := Load() - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if cfg.Service != Kiosk { - t.Fatalf("service = %q, want %q", cfg.Service, Kiosk) - } - if len(cfg.MediaRoots) != 2 { - t.Fatalf("media roots = %#v, want two roots", cfg.MediaRoots) - } - if cfg.MaxUploadBytes != 2*1024*1024 { - t.Fatalf("max upload bytes = %d", cfg.MaxUploadBytes) - } -} - -func TestLoadRequiresDatabase(t *testing.T) { - t.Setenv("DATABASE_URL", "") - if _, err := Load(); err == nil { - t.Fatal("Load() succeeded without DATABASE_URL") - } -} - -func TestParseBytesRejectsInvalidValues(t *testing.T) { - for _, value := range []string{"-1", "nope", "1tb"} { - if _, err := parseBytes(value); err == nil { - t.Errorf("parseBytes(%q) succeeded", value) - } - } -} diff --git a/shared/media-backend/internal/database/database.go b/shared/media-backend/internal/database/database.go deleted file mode 100644 index f7b19db..0000000 --- a/shared/media-backend/internal/database/database.go +++ /dev/null @@ -1,55 +0,0 @@ -package database - -import ( - "context" - "embed" - "fmt" - "time" - - "github.com/jackc/pgx/v5/pgxpool" -) - -//go:embed migrations/001_initial.sql -var migrations embed.FS - -func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { - cfg, err := pgxpool.ParseConfig(databaseURL) - if err != nil { - return nil, fmt.Errorf("parse database URL: %w", err) - } - cfg.MaxConns = 20 - cfg.MinConns = 1 - cfg.MaxConnLifetime = 30 * time.Minute - cfg.MaxConnIdleTime = 5 * time.Minute - pool, err := pgxpool.NewWithConfig(ctx, cfg) - if err != nil { - return nil, fmt.Errorf("open database: %w", err) - } - if err := pool.Ping(ctx); err != nil { - pool.Close() - return nil, fmt.Errorf("ping database: %w", err) - } - return pool, nil -} - -func Migrate(ctx context.Context, pool *pgxpool.Pool) error { - data, err := migrations.ReadFile("migrations/001_initial.sql") - if err != nil { - return fmt.Errorf("read migration: %w", err) - } - lockCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) - defer cancel() - conn, err := pool.Acquire(lockCtx) - if err != nil { - return fmt.Errorf("acquire migration connection: %w", err) - } - defer conn.Release() - if _, err := conn.Exec(lockCtx, `SELECT pg_advisory_lock(42424242)`); err != nil { - return fmt.Errorf("acquire migration lock: %w", err) - } - defer func() { _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(42424242)`) }() - if _, err := conn.Exec(lockCtx, string(data)); err != nil { - return fmt.Errorf("run migration: %w", err) - } - return nil -} diff --git a/shared/media-backend/internal/database/migrations/001_initial.sql b/shared/media-backend/internal/database/migrations/001_initial.sql deleted file mode 100644 index 8623c51..0000000 --- a/shared/media-backend/internal/database/migrations/001_initial.sql +++ /dev/null @@ -1,321 +0,0 @@ -CREATE EXTENSION IF NOT EXISTS pgcrypto; -CREATE EXTENSION IF NOT EXISTS pg_trgm; - -CREATE TABLE IF NOT EXISTS users ( - id BIGSERIAL PRIMARY KEY, - email TEXT NOT NULL UNIQUE, - username TEXT, - password_hash TEXT NOT NULL, - avatar_url TEXT, - bio TEXT, - role TEXT NOT NULL DEFAULT 'user', - permissions JSONB NOT NULL DEFAULT '{}'::jsonb, - disabled BOOLEAN NOT NULL DEFAULT FALSE, - totp_secret TEXT, - mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE, - mfa_backup_codes JSONB, - password_reset_token TEXT, - password_reset_expires TIMESTAMPTZ, - last_login_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT; -ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user'; -UPDATE users SET role = 'superadmin' -WHERE id = (SELECT id FROM users ORDER BY created_at, id LIMIT 1) - AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'superadmin'); -ALTER TABLE users ADD COLUMN IF NOT EXISTS permissions JSONB NOT NULL DEFAULT '{}'::jsonb; -ALTER TABLE users ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ; -CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL; -CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email)); - -CREATE TABLE IF NOT EXISTS go_sessions ( - token_hash TEXT PRIMARY KEY, - user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - expires_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -CREATE INDEX IF NOT EXISTS go_sessions_expiry_idx ON go_sessions (expires_at); - -CREATE TABLE IF NOT EXISTS media ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - media_key TEXT NOT NULL UNIQUE, - media_type TEXT NOT NULL DEFAULT 'unknown', - app TEXT, - source TEXT NOT NULL DEFAULT 'Filesystem', - title TEXT, - description TEXT, - category TEXT, - file_path TEXT, - original_filename TEXT, - active BOOLEAN NOT NULL DEFAULT TRUE, - metadata JSONB NOT NULL DEFAULT '{}'::jsonb, - width INT, - height INT, - duration_ms BIGINT, - size_bytes BIGINT, - is_vr BOOLEAN NOT NULL DEFAULT FALSE, - has_funscript BOOLEAN NOT NULL DEFAULT FALSE, - speed REAL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -ALTER TABLE media ADD COLUMN IF NOT EXISTS file_path TEXT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'Filesystem'; -ALTER TABLE media ADD COLUMN IF NOT EXISTS title TEXT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS description TEXT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS category TEXT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS original_filename TEXT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS active BOOLEAN NOT NULL DEFAULT TRUE; -ALTER TABLE media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb; -ALTER TABLE media ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); -ALTER TABLE media ADD COLUMN IF NOT EXISTS media_type TEXT NOT NULL DEFAULT 'unknown'; -ALTER TABLE media ADD COLUMN IF NOT EXISTS width INT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS height INT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS duration_ms BIGINT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS size_bytes BIGINT; -ALTER TABLE media ADD COLUMN IF NOT EXISTS is_vr BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE media ADD COLUMN IF NOT EXISTS has_funscript BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE media ADD COLUMN IF NOT EXISTS speed REAL; -ALTER TABLE media ADD COLUMN IF NOT EXISTS modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); -CREATE INDEX IF NOT EXISTS media_active_idx ON media (active); -CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path); -CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, ''))); - -CREATE TABLE IF NOT EXISTS media_stats ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, - media_key TEXT NOT NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - stat_type TEXT NOT NULL, - app TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_id BIGINT; -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_key TEXT; -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS user_id BIGINT; -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS stat_type TEXT; -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS app TEXT; -ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); -CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL; -CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type); - -CREATE TABLE IF NOT EXISTS media_view_sessions ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, - media_key TEXT NOT NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - duration_ms BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE IF NOT EXISTS media_metrics ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, - media_key TEXT NOT NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - elapsed_ms BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE IF NOT EXISTS media_tags ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, - media_key TEXT NOT NULL, - tag TEXT NOT NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (media_key, tag, user_id) -); -CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag)); -CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key); - -CREATE TABLE IF NOT EXISTS media_tag_votes ( - id BIGSERIAL PRIMARY KEY, - media_key TEXT NOT NULL, - tag TEXT NOT NULL, - user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (media_key, tag, user_id) -); - -CREATE TABLE IF NOT EXISTS playlists ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - name TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (user_id, name) -); -CREATE TABLE IF NOT EXISTS playlist_items ( - id BIGSERIAL PRIMARY KEY, - playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, - media_id BIGINT REFERENCES media(id) ON DELETE CASCADE, - media_key TEXT NOT NULL, - position INT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (playlist_id, media_key) -); - -CREATE TABLE IF NOT EXISTS settings ( - key TEXT PRIMARY KEY, - value TEXT, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -INSERT INTO settings (key, value) -VALUES ('auth_required', 'true') -ON CONFLICT (key) DO NOTHING; - -CREATE TABLE IF NOT EXISTS media_worker_jobs ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, - media_key TEXT, - file_path TEXT NOT NULL, - file_name TEXT NOT NULL DEFAULT '', - media_type TEXT NOT NULL DEFAULT 'unknown', - status TEXT NOT NULL DEFAULT 'queued', - progress INT NOT NULL DEFAULT 0, - queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - started_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ, - duration_ms INT, - error_message TEXT, - extracted_data JSONB, - file_size_bytes BIGINT, - scan_batch_id TEXT, - tags TEXT[], - title TEXT, - description TEXT, - has_funscript BOOLEAN NOT NULL DEFAULT FALSE, - is_vr BOOLEAN NOT NULL DEFAULT FALSE, - vr_fov INT, - vr_stereo TEXT, - data_outcome TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -CREATE INDEX IF NOT EXISTS media_worker_jobs_status_idx ON media_worker_jobs (status, queued_at DESC); -CREATE UNIQUE INDEX IF NOT EXISTS media_worker_jobs_file_path_unique ON media_worker_jobs (file_path); - -CREATE TABLE IF NOT EXISTS generated_media ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - workflow TEXT, - prompt TEXT, - parameters JSONB, - output_filename TEXT, - output_path TEXT, - elapsed_ms INT, - status TEXT NOT NULL DEFAULT 'completed', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -CREATE TABLE IF NOT EXISTS downloaded_media ( - id BIGSERIAL PRIMARY KEY, - media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - job_id BIGINT, - source_url TEXT NOT NULL, - tool TEXT, - file_path TEXT, - file_name TEXT, - file_size_bytes BIGINT, - status TEXT NOT NULL DEFAULT 'completed', - error_message TEXT, - started_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE IF NOT EXISTS workflow_jobs ( - id TEXT PRIMARY KEY, - service TEXT NOT NULL, - tool TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'queued', - progress INT NOT NULL DEFAULT 0, - request JSONB NOT NULL DEFAULT '{}'::jsonb, - result JSONB NOT NULL DEFAULT '{}'::jsonb, - error_message TEXT, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - started_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ -); -CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC); - -CREATE TABLE IF NOT EXISTS workflow_schedules ( - id TEXT PRIMARY KEY, - service TEXT NOT NULL, - tool TEXT NOT NULL, - name TEXT NOT NULL, - interval_minutes INT NOT NULL DEFAULT 60, - enabled BOOLEAN NOT NULL DEFAULT TRUE, - settings JSONB NOT NULL DEFAULT '{}'::jsonb, - last_run_at TIMESTAMPTZ, - last_status TEXT, - next_run_at TIMESTAMPTZ, - user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE IF NOT EXISTS thumbnails ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, - source_path TEXT UNIQUE, - width INT, - height INT, - file_size_bytes BIGINT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); - -CREATE TABLE IF NOT EXISTS mount_paths ( - project TEXT NOT NULL, - function_name TEXT NOT NULL, - path TEXT NOT NULL, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (project, function_name) -); - --- Per-step status tracking for metadata extraction and thumbnail generation, independent of the --- legacy `status`/`error_message` columns above (which track the overall discovery row). -ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_status TEXT NOT NULL DEFAULT 'queued'; -ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_error TEXT; -ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_status TEXT NOT NULL DEFAULT 'queued'; -ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_error TEXT; -CREATE INDEX IF NOT EXISTS media_worker_jobs_metadata_status_idx ON media_worker_jobs (media_type, metadata_status); -CREATE INDEX IF NOT EXISTS media_worker_jobs_thumbnail_status_idx ON media_worker_jobs (media_type, thumbnail_status); - --- One row per (file, AI task) since a single image can have up to six independently toggleable --- AI tasks (tags/title/description/age/gender/nsfw), which doesn't fit the one-row-per-file shape --- of media_worker_jobs. -CREATE TABLE IF NOT EXISTS media_analysis_tasks ( - id BIGSERIAL PRIMARY KEY, - media_key TEXT NOT NULL, - media_type TEXT NOT NULL, - task TEXT NOT NULL, - model TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'queued', - result JSONB, - error_message TEXT, - started_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (media_key, task) -); -CREATE INDEX IF NOT EXISTS media_analysis_tasks_status_idx ON media_analysis_tasks (media_type, status); - --- AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id) --- constraint does not dedupe NULLs against each other, so a dedicated partial index is required --- to make repeated analysis runs idempotent instead of piling up duplicate tag rows. -CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL; - --- Speeds up the ContentScanner dashboard/pipelines/history/live-status queries: analyzerStats and --- analyzerPipelineBreakdown group active media by type (and join it against thumbnails), and --- analyzerHistory sorts media_worker_jobs by queued_at with no status filter, none of which the --- existing media/media_worker_jobs indexes above actually cover. -CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type); -CREATE INDEX IF NOT EXISTS media_worker_jobs_queued_at_idx ON media_worker_jobs (queued_at DESC); -CREATE INDEX IF NOT EXISTS media_worker_jobs_media_type_status_idx ON media_worker_jobs (media_type, status); -CREATE INDEX IF NOT EXISTS media_worker_jobs_funscript_status_idx ON media_worker_jobs (status) WHERE has_funscript = TRUE; diff --git a/shared/media-backend/internal/server/admin_storage.go b/shared/media-backend/internal/server/admin_storage.go deleted file mode 100644 index 12f1921..0000000 --- a/shared/media-backend/internal/server/admin_storage.go +++ /dev/null @@ -1,1521 +0,0 @@ -package server - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "log" - "net/http" - "net/url" - "os" - "path/filepath" - "regexp" - "slices" - "sort" - "strconv" - "strings" - "time" - - "github.com/go-chi/chi/v5" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" -) - -func (s *Server) mountConfigRoutes(r chi.Router) { - admin := r.With(s.auth.RequireAdminIfLoginRequired) - admin.Get("/settings", s.settings) - admin.Post("/settings", s.saveSettings) - admin.Post("/check-connection", s.checkConnection) - admin.Post("/discover-service", s.discoverService) - admin.Post("/settings/sync", s.settingsSync) - r.With(s.internalServiceAuth).Get("/settings/export", s.settingsExport) - r.Get("/info", s.configInfo) - r.With(s.internalServiceAuth).Get("/mounts/paths", s.mountPaths) - admin.Post("/mounts/paths", s.saveMountPaths) - r.With(s.internalServiceAuth).Get("/mounts/resolve", s.resolveMount) -} - -func (s *Server) settings(w http.ResponseWriter, r *http.Request) { - rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, '') FROM settings ORDER BY key`) - if err != nil { - writeError(w, http.StatusInternalServerError, "settings unavailable") - return - } - defer rows.Close() - values := map[string]string{} - for rows.Next() { - var key, value string - if rows.Scan(&key, &value) != nil || sensitiveSetting(key) { - continue - } - values[key] = value - } - writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values}) -} - -func (s *Server) saveSettings(w http.ResponseWriter, r *http.Request) { - var updates map[string]any - if err := decodeRequestJSON(r, &updates); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if len(updates) > 200 { - writeError(w, http.StatusBadRequest, "too many settings") - return - } - count := 0 - for key, value := range updates { - if strings.TrimSpace(key) == "" || len(key) > 160 || (sensitiveSetting(key) && strings.TrimSpace(fmt.Sprint(value)) == "") { - continue - } - text := fmt.Sprint(value) - if encoded, ok := value.(map[string]any); ok { - text = string(mustJSON(encoded)) - } - if _, err := s.db.Exec(r.Context(), `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, text); err != nil { - writeError(w, http.StatusInternalServerError, "setting could not be saved") - return - } - count++ - } - writeJSON(w, http.StatusOK, map[string]any{"success": true, "updated": count}) -} - -// settingsExport is the full-fidelity counterpart to settings: every row (sensitive ones -// included, since this is only ever reachable with the shared X-Internal-Auth secret) plus each -// key's updated_at, so a peer ProjectConfigurator instance can merge it with its own by recency. -// This is what makes running more than one ProjectConfigurator instance for high availability -// actually converge, whether or not the instances share a single Postgres database. -func (s *Server) settingsExport(w http.ResponseWriter, r *http.Request) { - rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, ''), updated_at FROM settings ORDER BY key`) - if err != nil { - writeError(w, http.StatusInternalServerError, "settings unavailable") - return - } - defer rows.Close() - values := map[string]any{} - for rows.Next() { - var key, value string - var updatedAt time.Time - if rows.Scan(&key, &value, &updatedAt) != nil { - continue - } - values[key] = map[string]any{"value": value, "updatedAt": updatedAt} - } - writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values}) -} - -// projectConfiguratorPeers reads the other ProjectConfigurator instances an operator has -// registered in the Projects workspace's Central services section (configured_central, the same -// setting regularProjects/centralInstancesFor reads client-side) - every instance whose base name -// is "ProjectConfigurator" except the unsuffixed entry, which by convention represents this -// instance itself rather than a remote peer. -func (s *Server) projectConfiguratorPeers(ctx context.Context) []string { - raw := s.settingValue(ctx, "configured_central", "") - var central []string - if raw == "" || json.Unmarshal([]byte(raw), ¢ral) != nil { - return nil - } - peers := make([]string, 0, len(central)) - for _, project := range central { - key := strings.ToLower(strings.TrimSpace(project)) - if key == "" || key == "projectconfigurator" || instanceBaseKey(key) != "projectconfigurator" { - continue - } - if peerURL := strings.TrimSpace(s.settingValue(ctx, key+"_url", "")); peerURL != "" { - peers = append(peers, peerURL) - } - } - return peers -} - -// pullSettingsFrom fetches one peer's full settings export and applies every key that peer last -// touched more recently than this instance did - last-write-wins per key, the same rule -// saveSettings already applies within a single instance, just extended across instances. -func (s *Server) pullSettingsFrom(ctx context.Context, peerURL string) (int, error) { - target, err := normalizeServiceURL(peerURL) - if err != nil { - return 0, err - } - reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, strings.TrimRight(target, "/")+"/api/settings/export", nil) - if err != nil { - return 0, err - } - if s.cfg.InternalServiceSecret != "" { - request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret) - } - response, err := http.DefaultClient.Do(request) - if err != nil { - return 0, err - } - defer response.Body.Close() - if response.StatusCode != http.StatusOK { - return 0, fmt.Errorf("peer returned status %d", response.StatusCode) - } - var body struct { - Settings map[string]struct { - Value string `json:"value"` - UpdatedAt time.Time `json:"updatedAt"` - } `json:"settings"` - } - if err := json.NewDecoder(io.LimitReader(response.Body, 4<<20)).Decode(&body); err != nil { - return 0, err - } - updated := 0 - for key, remote := range body.Settings { - key = strings.TrimSpace(key) - if key == "" || len(key) > 160 { - continue - } - result, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,$3) - ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=EXCLUDED.updated_at - WHERE settings.updated_at < EXCLUDED.updated_at`, key, remote.Value, remote.UpdatedAt) - if err != nil { - continue - } - if result.RowsAffected() > 0 { - updated++ - } - } - return updated, nil -} - -// settingsSync is the "Sync now" button's endpoint: pull every registered ProjectConfigurator -// peer's settings on demand, on top of the periodic background sync (runSettingsSyncScheduler). -func (s *Server) settingsSync(w http.ResponseWriter, r *http.Request) { - peers := s.projectConfiguratorPeers(r.Context()) - results := make([]map[string]any, 0, len(peers)) - updated := 0 - for _, peer := range peers { - count, err := s.pullSettingsFrom(r.Context(), peer) - result := map[string]any{"url": peer} - if err != nil { - result["ok"] = false - result["error"] = err.Error() - } else { - result["ok"] = true - result["updated"] = count - updated += count - } - results = append(results, result) - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "peers": len(peers), "updated": updated, "results": results}) -} - -// runSettingsSyncScheduler periodically pulls every registered peer's settings so multiple -// ProjectConfigurator instances converge on their own, without an operator needing to click -// "Sync now" - the actual high-availability behavior. Only started for the config service (see -// Run). A fresh deployment with no peers registered yet just polls configured_central and finds -// nothing to do each tick, which is cheap enough not to bother special-casing. -func (s *Server) runSettingsSyncScheduler(ctx context.Context) { - ticker := time.NewTicker(2 * time.Minute) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - for _, peer := range s.projectConfiguratorPeers(ctx) { - if _, err := s.pullSettingsFrom(ctx, peer); err != nil { - log.Printf("settings sync: pulling from %s: %v", peer, err) - } - } - } - } -} - -func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) { - var input struct { - URL string `json:"url"` - Project string `json:"project"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if strings.TrimSpace(input.URL) == "" { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "No URL provided"}) - return - } - target, err := normalizeServiceURL(input.URL) - if err != nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "service": nil, "mismatch": false, "error": err.Error()}) - return - } - ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) - defer cancel() - request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/healthz", nil) - response, err := http.DefaultClient.Do(request) - if err != nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "service": nil, "mismatch": false}) - return - } - defer response.Body.Close() - var body struct { - Service string `json:"service"` - } - _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) - mismatch := input.Project != "" && body.Service != "" && !strings.EqualFold(input.Project, body.Service) - writeJSON(w, http.StatusOK, map[string]any{"ok": response.StatusCode < 500, "service": body.Service, "mismatch": mismatch}) -} - -func (s *Server) configInfo(w http.ResponseWriter, r *http.Request) { - host := r.Host - if s.cfg.PublicURL != "" { - host = s.cfg.PublicURL - } - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, "hostname": host, "port": s.cfg.Port, "url": host, - "name": s.cfg.ServiceName, "service": s.cfg.ServiceName, - "tabs": serviceTabs(s.cfg.Service), "mountTypes": serviceMountTypes(s.cfg.Service), - }) -} - -// tabOption mirrors one entry of a project's nav (see webui's app-config.ts) plus the -// global About dialog every instance exposes - the set of "pages" ProjectConfigurator's Projects -// workspace lets an operator require login for individually. -type tabOption struct { - Label string `json:"label"` - Token string `json:"token"` -} - -// serviceTabsByService mirrors webui/src/lib/app-config.ts's nav per Service, plus the -// About dialog (AppShell.svelte, not itself part of app.nav). Kept in sync by hand - there is no -// single source of truth shared between the Go backend and the SvelteKit frontend for this. -var serviceTabsByService = map[config.Service][]tabOption{ - config.Viewer: { - {"Library", "/"}, {"Feed", "/feed"}, {"Tags", "/tags"}, {"Playlists", "/playlists"}, {"About", "/about"}, - }, - config.CraftStudio: { - {"Generator", "/"}, {"Downloader", "/downloader"}, {"Converter", "/converter"}, - {"Schedules", "/schedules"}, {"Library", "/library"}, {"About", "/about"}, - }, - config.ContentScanner: { - {"Dashboard", "/"}, {"Discover", "/discover"}, {"Images", "/images"}, {"Videos", "/videos"}, - {"Audios", "/audios"}, {"Funscripts", "/funscripts"}, {"Schedules", "/schedules"}, {"About", "/about"}, - }, - config.ConfigService: {{"Projects", "/"}, {"About", "/about"}}, - config.Moderator: { - {"Dashboard", "/"}, {"Users", "/users"}, {"Media", "/media"}, {"About", "/about"}, - }, - config.Kiosk: {{"Kiosk", "/"}, {"About", "/about"}}, - config.CarrierNode: {{"Overview", "/"}, {"Files", "/files"}, {"About", "/about"}}, -} - -// serviceMountTypesByService mirrors ConfigWorkspace.svelte's PROJECT_AVAILABLE_MOUNTS - the -// mount "type" values each service's own tab accepts when configuring its mounts. -var serviceMountTypesByService = map[config.Service][]string{ - config.Viewer: {"media", "thumbnails", "funscripts"}, - config.CraftStudio: {"downloads", "generated", "converted", "converter input", "generator input", "generator copy"}, - config.ContentScanner: {"images", "videos", "audios", "funscripts", "models", "thumbnails"}, - config.Moderator: {"media", "thumbnails"}, - config.Kiosk: {"media"}, - config.CarrierNode: {"media", "output"}, - config.ConfigService: {}, -} - -func serviceTabs(service config.Service) []tabOption { - if tabs, ok := serviceTabsByService[service]; ok { - return tabs - } - return []tabOption{{"Main", "/"}, {"About", "/about"}} -} - -func serviceMountTypes(service config.Service) []string { - if types, ok := serviceMountTypesByService[service]; ok { - return types - } - return []string{} -} - -// discoverService lets ProjectConfigurator's Projects workspace populate a new service's name, -// tabs, and mount types from just its URL: it fetches the target's own public GET /api/info -// server-side (avoiding a browser CORS round-trip, same reasoning as checkConnection) and relays -// whatever it reports. A target that doesn't implement this yet (or is unreachable) reports -// {"ok":false} so the caller can fall back to manual entry instead of erroring out. -func (s *Server) discoverService(w http.ResponseWriter, r *http.Request) { - var input struct { - URL string `json:"url"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - target, err := normalizeServiceURL(input.URL) - if err != nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()}) - return - } - ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) - defer cancel() - request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/api/info", nil) - response, err := http.DefaultClient.Do(request) - if err != nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "unreachable"}) - return - } - defer response.Body.Close() - var body struct { - OK bool `json:"ok"` - Name string `json:"name"` - Service string `json:"service"` - Tabs []tabOption `json:"tabs"` - MountTypes []string `json:"mountTypes"` - } - if response.StatusCode >= 300 || json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) != nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "invalid response"}) - return - } - name := strings.TrimSpace(body.Name) - if name == "" { - name = strings.TrimSpace(body.Service) - } - if name == "" { - writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "service did not report a name"}) - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, "name": name, "tabs": body.Tabs, "mountTypes": body.MountTypes, - }) -} - -func (s *Server) mountPaths(w http.ResponseWriter, r *http.Request) { - mappings := s.mountMappings(r.Context()) - writeJSON(w, http.StatusOK, map[string]any{"success": true, "mappings": mappings}) -} - -func (s *Server) saveMountPaths(w http.ResponseWriter, r *http.Request) { - var payload struct { - Mappings map[string]any `json:"mappings"` - } - if err := decodeRequestJSON(r, &payload); err != nil || payload.Mappings == nil { - writeError(w, http.StatusBadRequest, "mappings are required") - return - } - if err := s.saveSetting(r.Context(), "mounts_path_mappings", string(mustJSON(payload.Mappings))); err != nil { - writeError(w, http.StatusInternalServerError, "mount mappings could not be saved") - return - } - writeJSON(w, http.StatusOK, map[string]any{"success": true}) -} - -func (s *Server) resolveMount(w http.ResponseWriter, r *http.Request) { - project := r.URL.Query().Get("project") - functionName := r.URL.Query().Get("function") - if project == "" || functionName == "" { - writeError(w, http.StatusBadRequest, "project and function required") - return - } - mappings := s.mountMappings(r.Context()) - projectValue, ok := mappings[project] - if !ok { - for key, value := range mappings { - if strings.EqualFold(key, project) { - projectValue, ok = value, true - break - } - } - } - if !ok { - writeError(w, http.StatusNotFound, "mapping not found") - return - } - functions, ok := projectValue.(map[string]any) - if !ok { - writeError(w, http.StatusNotFound, "mapping not found") - return - } - value, ok := functions[functionName] - if !ok { - writeError(w, http.StatusNotFound, "mapping not found") - return - } - paths := normalizeMappingPaths(value) - if filename := r.URL.Query().Get("filename"); filename != "" { - for _, base := range paths { - if !safeRelative(filename) { - continue - } - if _, err := os.Stat(filepath.Join(base, filepath.FromSlash(filename))); err == nil { - writeJSON(w, http.StatusOK, map[string]any{"success": true, "absolutePath": filepath.Join(base, filepath.FromSlash(filename)), "basePath": base, "filename": filename, "basePaths": paths}) - return - } - } - } - if len(paths) == 0 { - writeError(w, http.StatusNotFound, "mapping not found") - return - } - writeJSON(w, http.StatusOK, map[string]any{"success": true, "absolutePath": paths[0], "basePath": paths[0], "filename": r.URL.Query().Get("filename"), "basePaths": paths}) -} - -// mountEntry mirrors WebUI's ConfigWorkspace.svelte MountEntry ({type, path}) - one row in a -// project's mount list in ProjectConfigurator's Projects workspace. -type mountEntry struct { - Type string `json:"type"` - Path string `json:"path"` -} - -// configuredMounts parses the configured_mounts setting - the live source ProjectConfigurator's -// Projects workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project -// key -> mount entries. Returns nil if unset or malformed. -func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry { - raw := s.settingValue(ctx, "configured_mounts", "") - if raw == "" { - return nil - } - var byProject map[string][]mountEntry - if json.Unmarshal([]byte(raw), &byProject) != nil { - return nil - } - return byProject -} - -// mountMappings returns each project's mount configuration as project -> mount type -> path(s), -// the shape /mounts/resolve and /mounts/paths (and CarrierNode's own "Mount health" panel via -// /mounts) expect. configured_mounts is the live source and wins per-project when present; -// mounts_path_mappings is an older format nothing has written since the Projects workspace moved -// to configured_mounts, kept only so a deployment that hasn't resaved its mounts since upgrading -// doesn't lose data it already had. Keys are used as stored, not case-normalized - configured_mounts -// is processed first so a legacy entry for a project already covered there (under the exact same -// key) is skipped instead of showing up as a second, redundant copy. -func (s *Server) mountMappings(ctx context.Context) map[string]any { - mappings := map[string]any{} - seen := map[string]bool{} - - for project, entries := range s.configuredMounts(ctx) { - key := strings.TrimSpace(project) - if key == "" { - continue - } - functions := map[string]any{} - for _, entry := range entries { - mountType := strings.TrimSpace(entry.Type) - path := strings.TrimSpace(entry.Path) - if mountType == "" || path == "" { - continue - } - switch existing := functions[mountType].(type) { - case nil: - functions[mountType] = path - case string: - if existing != path { - functions[mountType] = []string{existing, path} - } - case []string: - if !slices.Contains(existing, path) { - functions[mountType] = append(existing, path) - } - } - } - if len(functions) > 0 { - mappings[key] = functions - seen[key] = true - } - } - - legacyValue := s.settingValue(ctx, "mounts_path_mappings", "{}") - var legacy map[string]any - if json.Unmarshal([]byte(legacyValue), &legacy) == nil { - for project, value := range legacy { - key := strings.TrimSpace(project) - if key == "" || seen[key] { - continue - } - mappings[key] = value - } - } - - return mappings -} - -// mediaLibraryMountTypes are the mount "type" values ProjectConfigurator's Projects workspace (the -// configured_mounts setting) accepts that describe an actual media-library directory, as -// opposed to a project-specific working directory like "downloads", "generated", -// "thumbnails", or "models", which have their own dedicated Root config fields instead and -// are deliberately left out here. A path is entered under whichever project's tab happens to -// need it (ContentScanner's "images"/"videos"/"audios", MediaViewer/MediaKiosk's "media", ...) -// but they're all describing locations CarrierNode itself has to walk, since it's the only -// service with the volume mounted - see effectiveMediaRoots. -var mediaLibraryMountTypes = map[string]bool{ - "media": true, "images": true, "videos": true, "audios": true, "funscripts": true, -} - -// mediaRootsFromMounts extracts every distinct path configured under a media-library mount -// type across every project in the configured_mounts setting. -func (s *Server) mediaRootsFromMounts(ctx context.Context) []string { - seen := map[string]bool{} - roots := make([]string, 0) - for _, entries := range s.configuredMounts(ctx) { - for _, entry := range entries { - path := strings.TrimSpace(entry.Path) - if path == "" || !mediaLibraryMountTypes[strings.ToLower(strings.TrimSpace(entry.Type))] { - continue - } - path = filepath.Clean(path) - if seen[path] { - continue - } - seen[path] = true - roots = append(roots, path) - } - } - return roots -} - -// effectiveMediaRoots is what CarrierNode actually walks and resolves files under: the static -// MEDIA_ROOTS/MEDIA_ROOT env config (if any) plus every media-library path configured through -// ProjectConfigurator's Projects workspace, deduped. Settings are read fresh from the DB on every -// call (no caching, same as carriernode_url/carrierNodeBaseURL), so a mount saved in -// ProjectConfigurator takes effect on CarrierNode's very next request - no reload or restart needed. -func (s *Server) effectiveMediaRoots(ctx context.Context) []string { - seen := map[string]bool{} - roots := make([]string, 0, len(s.cfg.MediaRoots)) - for _, root := range append(append([]string{}, s.cfg.MediaRoots...), s.mediaRootsFromMounts(ctx)...) { - if root == "" || seen[root] { - continue - } - seen[root] = true - roots = append(roots, root) - } - return roots -} - -func (s *Server) mountModeratorRoutes(r chi.Router) { - admin := r.With(s.auth.RequireAdmin) - admin.Get("/admin/users", s.adminUsers) - admin.Post("/admin/users", s.adminCreateUser) - admin.Post("/admin/users/actions", s.adminUserActions) - admin.Get("/admin/users/{id}/media", s.adminUserMedia) - admin.Patch("/admin/users/{id}", s.adminUpdateUser) - admin.Put("/admin/users/{id}", s.adminUpdateUser) - admin.Delete("/admin/users/{id}", s.adminDeleteUser) - admin.Get("/admin/media", s.adminMedia) - admin.Post("/admin/media/actions", s.adminMediaActions) - admin.Get("/admin/media/likers", s.adminMediaLikers) - admin.Get("/admin/stats", s.adminStats) - r.Get("/search/images", s.adminMedia) - r.Get("/search/media", s.adminMedia) - r.Get("/__ready", s.ready) -} - -func (s *Server) adminUsers(w http.ResponseWriter, r *http.Request) { - users, total, err := s.auth.ListUsers(r.Context(), r.URL.Query().Get("search"), optionalInt(r.URL.Query().Get("limit"), 50, 1, 200), 0) - if err != nil { - writeError(w, http.StatusInternalServerError, "users unavailable") - return - } - writeJSON(w, http.StatusOK, map[string]any{"users": users, "items": users, "total": total}) -} - -func (s *Server) adminCreateUser(w http.ResponseWriter, r *http.Request) { - var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - Role string `json:"role"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - user, err := s.auth.CreateUser(r.Context(), input.Email, input.Username, input.Password, input.Role) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - writeJSON(w, http.StatusCreated, map[string]any{"user": user}) -} - -func (s *Server) adminUpdateUser(w http.ResponseWriter, r *http.Request) { - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid user id") - return - } - var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - Role string `json:"role"` - Disabled *bool `json:"disabled"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if err := s.auth.UpdateUser(r.Context(), id, input.Email, input.Username, input.Role, input.Disabled); err != nil { - writeError(w, http.StatusBadRequest, "user could not be updated") - return - } - if strings.TrimSpace(input.Password) != "" { - if err := s.auth.SetPassword(r.Context(), id, input.Password); err != nil { - writeError(w, http.StatusBadRequest, "password could not be updated") - return - } - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil || s.auth.DeleteUser(r.Context(), id) != nil { - writeError(w, http.StatusNotFound, "user not found") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) adminUserActions(w http.ResponseWriter, r *http.Request) { - var input struct { - Action string `json:"action"` - IDs []json.RawMessage `json:"ids"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - for _, raw := range input.IDs { - var id int64 - if json.Unmarshal(raw, &id) != nil { - var text string - if json.Unmarshal(raw, &text) == nil { - id, _ = strconv.ParseInt(text, 10, 64) - } - } - if id == 0 { - continue - } - switch strings.ToLower(input.Action) { - case "delete": - _ = s.auth.DeleteUser(r.Context(), id) - case "disable": - _ = s.auth.UpdateUser(r.Context(), id, "", "", "", ptrBool(true)) - case "enable", "activate": - _ = s.auth.UpdateUser(r.Context(), id, "", "", "", ptrBool(false)) - } - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (s *Server) adminUserMedia(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"media": []any{}, "items": []any{}}) -} - -func (s *Server) adminMedia(w http.ResponseWriter, r *http.Request) { - search := strings.TrimSpace(r.URL.Query().Get("search")) - pattern := "%" + search + "%" - rows, err := s.db.Query(r.Context(), `SELECT id, media_key, COALESCE(media_type,'unknown'), COALESCE(title,''), COALESCE(original_filename,''), active, COALESCE(source,'Filesystem'), COALESCE(size_bytes,0), COALESCE(modified_at, created_at) FROM media WHERE ($1='' OR media_key ILIKE $2 OR COALESCE(title,'') ILIKE $2 OR COALESCE(original_filename,'') ILIKE $2) ORDER BY modified_at DESC LIMIT 100`, search, pattern) - if err != nil { - writeError(w, http.StatusInternalServerError, "media unavailable") - return - } - defer rows.Close() - items := make([]map[string]any, 0) - for rows.Next() { - var id int64 - var key, mediaType, title, name, source string - var active bool - var size int64 - var modified time.Time - if rows.Scan(&id, &key, &mediaType, &title, &name, &active, &source, &size, &modified) == nil { - items = append(items, map[string]any{"id": id, "mediaKey": key, "media_key": key, "mediaType": mediaType, "title": title, "filename": name, "active": active, "source": source, "sizeBytes": size, "modifiedAt": modified}) - } - } - writeJSON(w, http.StatusOK, map[string]any{"media": items, "items": items, "total": len(items)}) -} - -func (s *Server) adminMediaActions(w http.ResponseWriter, r *http.Request) { - var input struct { - Action string `json:"action"` - IDs []json.RawMessage `json:"ids"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - for _, raw := range input.IDs { - var id int64 - if json.Unmarshal(raw, &id) != nil { - var text string - _ = json.Unmarshal(raw, &text) - id, _ = strconv.ParseInt(text, 10, 64) - } - if id == 0 { - continue - } - switch strings.ToLower(input.Action) { - case "delete": - _, _ = s.db.Exec(r.Context(), `DELETE FROM media WHERE id=$1`, id) - case "hide", "deactivate": - _, _ = s.db.Exec(r.Context(), `UPDATE media SET active=FALSE WHERE id=$1`, id) - case "show", "activate": - _, _ = s.db.Exec(r.Context(), `UPDATE media SET active=TRUE WHERE id=$1`, id) - } - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (s *Server) adminMediaLikers(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"users": []any{}, "likers": []any{}}) -} - -func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) { - var users, media, likes, views int64 - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM users`).Scan(&users) - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media`).Scan(&media) - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE stat_type='like'`).Scan(&likes) - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE stat_type='view'`).Scan(&views) - writeJSON(w, http.StatusOK, map[string]any{"users": users, "media": media, "likes": likes, "views": views}) -} - -func (s *Server) mountCarrierNodeRoutes(r chi.Router) { - r.Get("/stats", s.carrierNodeStats) - r.Get("/mounts", s.carrierNodeMounts) - r.Get("/files/recent", s.carrierNodeRecentFiles) - r.Get("/files", s.carrierNodeFiles) - r.Get("/files/count", s.carrierNodeFileCount) - r.Get("/folders", s.carrierNodeFolders) - r.Get("/browse", s.carrierNodeBrowse) - r.Get("/watch", s.carrierNodeWatch) - r.With(s.internalServiceAuth).Get("/downloads", s.carrierNodeDownloads) - r.With(s.internalServiceAuth).Post("/reload-mounts", s.carrierNodeReloadMounts) - r.With(s.internalServiceAuth).Get("/probe", s.carrierNodeProbeFile) - protected := r.With(s.auth.Optional, s.requireAdminOrInternal) - protected.Post("/upload", s.carrierNodeUpload) - protected.Post("/upload-mounted", s.carrierNodeUpload) - protected.Delete("/downloads/{filename}", s.carrierNodeDeleteDownload) - protected.Post("/store", s.carrierNodeStore) - internal := r.With(s.internalServiceAuth) - internal.Post("/thumbnails/{id}", s.carrierNodeThumbnailUpload) - internal.Delete("/thumbnails/{id}", s.carrierNodeThumbnailDelete) - internal.Post("/outputs/{name}", s.carrierNodeOutputUpload) - internal.Post("/inputs/{name}", s.carrierNodeInputUpload) - internal.Post("/copies/{name}", s.carrierNodeCopyUpload) - - // Generic, project-agnostic mount access: any project registered in - // ProjectConfigurator's Projects workspace with a mount path configured under - // {type} can read/list/write/delete files there, not just the handful of - // hardcoded media-family routes above (/media, /mount/generated, /thumbnails, ...). - // See carrierNodeMountRoots's doc comment for why no cross-service call is needed. - internal.Get("/mount/{project}/{type}", s.carrierNodeListMount) - internal.Get("/mount/{project}/{type}/*", s.carrierNodeMountFile) - internal.Post("/mount/{project}/{type}/*", s.carrierNodeMountUpload) - internal.Delete("/mount/{project}/{type}/*", s.carrierNodeMountDelete) -} - -// carrierNodeMountRoots resolves every root path registered for {project, type} through -// ProjectConfigurator's Projects workspace (the same configured_mounts setting -// /api/mounts/resolve serves) - not limited to the media-family's own hardcoded mount -// categories (media/output/generated/...), any project name and any mount type an -// operator has configured there works. No HTTP call to ProjectConfigurator is needed: every -// MEDIA_SERVICE instance, CarrierNode included, reads the same settings table directly (see -// mountMappings), the same way effectiveMediaRoots already resolves CarrierNode's own roots. -func (s *Server) carrierNodeMountRoots(ctx context.Context, project, mountType string) []string { - mappings := s.mountMappings(ctx) - projectValue, ok := mappings[project] - if !ok { - for key, value := range mappings { - if strings.EqualFold(key, project) { - projectValue, ok = value, true - break - } - } - } - if !ok { - return nil - } - functions, ok := projectValue.(map[string]any) - if !ok { - return nil - } - value, ok := functions[mountType] - if !ok { - for key, candidate := range functions { - if strings.EqualFold(key, mountType) { - value, ok = candidate, true - break - } - } - } - if !ok { - return nil - } - return normalizeMappingPaths(value) -} - -// carrierNodeListMount lists the files directly under every root configured for -// {project, type} (non-recursive - each root is typically a flat upload/output directory). -func (s *Server) carrierNodeListMount(w http.ResponseWriter, r *http.Request) { - project := chi.URLParam(r, "project") - mountType := chi.URLParam(r, "type") - roots := s.carrierNodeMountRoots(r.Context(), project, mountType) - if len(roots) == 0 { - writeError(w, http.StatusNotFound, "no mount configured for this project/type") - return - } - entries := make([]map[string]any, 0) - for _, root := range roots { - items, err := os.ReadDir(root) - if err != nil { - continue - } - for _, item := range items { - if item.IsDir() { - continue - } - info, err := item.Info() - if err != nil { - continue - } - entries = append(entries, map[string]any{"name": item.Name(), "size": info.Size(), "modifiedAt": info.ModTime()}) - } - } - writeJSON(w, http.StatusOK, map[string]any{"success": true, "project": project, "type": mountType, "files": entries}) -} - -// carrierNodeMountFile downloads one file by relative path from {project, type}'s mount. -func (s *Server) carrierNodeMountFile(w http.ResponseWriter, r *http.Request) { - roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) - if len(roots) == 0 { - writeError(w, http.StatusNotFound, "no mount configured for this project/type") - return - } - full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - s.serveFile(w, r, full) -} - -// carrierNodeMountUpload stores the request body as a file under {project, type}'s first -// configured root. Like carrierNodeStreamUpload (which this delegates to), the destination -// filename is flattened to its base name - no subdirectories. -func (s *Server) carrierNodeMountUpload(w http.ResponseWriter, r *http.Request) { - roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) - if len(roots) == 0 { - writeError(w, http.StatusNotFound, "no mount configured for this project/type") - return - } - s.carrierNodeStreamUpload(w, r, roots[0], chi.URLParam(r, "*")) -} - -// carrierNodeMountDelete removes one file by relative path from {project, type}'s mount. -func (s *Server) carrierNodeMountDelete(w http.ResponseWriter, r *http.Request) { - roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) - if len(roots) == 0 { - writeError(w, http.StatusNotFound, "no mount configured for this project/type") - return - } - full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - if err := os.Remove(full); err != nil { - writeError(w, http.StatusInternalServerError, "file could not be removed") - return - } - writeJSON(w, http.StatusOK, map[string]any{"success": true}) -} - -func (s *Server) carrierNodeStats(w http.ResponseWriter, r *http.Request) { - files := s.walkFiles(r.Context(), "") - roots := s.effectiveMediaRoots(r.Context()) - byType := map[string]int{"image": 0, "video": 0, "audio": 0, "other": 0} - for _, file := range files { - byType[fileType(file.Rel)]++ - } - stats := map[string]any{"count": len(files), "total": len(files), "active": len(roots), "files": byType} - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "stats": stats, "bandwidth": map[string]any{"bytesOut": 0, "requests": 0}, "count": len(files), "total": len(files), "active": len(roots), "files": byType, "roots": roots}) -} - -func (s *Server) carrierNodeMounts(w http.ResponseWriter, r *http.Request) { - roots := s.effectiveMediaRoots(r.Context()) - writeJSON(w, http.StatusOK, map[string]any{"mappings": s.mountMappings(r.Context()), "roots": roots, "count": len(roots)}) -} - -type fileEntry struct { - Rel string `json:"rel"` - Path string `json:"path"` - Type string `json:"type"` - Size int64 `json:"size"` - Mtime int64 `json:"mtime"` -} - -func (s *Server) carrierNodeRecentFiles(w http.ResponseWriter, r *http.Request) { - s.writeCarrierNodeFiles(w, r, true) -} -func (s *Server) carrierNodeFiles(w http.ResponseWriter, r *http.Request) { - s.writeCarrierNodeFiles(w, r, false) -} - -func (s *Server) carrierNodeFileCount(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "count": len(s.walkFiles(r.Context(), r.URL.Query().Get("path")))}) -} - -func (s *Server) writeCarrierNodeFiles(w http.ResponseWriter, r *http.Request, recent bool) { - files := s.walkFiles(r.Context(), r.URL.Query().Get("path")) - if recent { - sort.Slice(files, func(i, j int) bool { return files[i].Mtime > files[j].Mtime }) - } - // Internal callers (e.g. ContentScanner discovery) need to list an entire real-sized library - // in one pass; the public 1000-item cap stays in place for anyone without the shared secret. - maxLimit := 1000 - if s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret { - maxLimit = 1000000 - } - limit := optionalInt(r.URL.Query().Get("limit"), 100, 1, maxLimit) - if len(files) > limit { - files = files[:limit] - } - writeJSON(w, http.StatusOK, map[string]any{"files": files, "items": files, "total": len(files)}) -} - -func (s *Server) carrierNodeFolders(w http.ResponseWriter, r *http.Request) { - seen := map[string]bool{} - for _, file := range s.walkFiles(r.Context(), r.URL.Query().Get("path")) { - seen[filepath.Dir(file.Rel)] = true - } - folders := make([]string, 0, len(seen)) - for folder := range seen { - folders = append(folders, folder) - } - sort.Strings(folders) - writeJSON(w, http.StatusOK, map[string]any{"folders": folders}) -} - -func (s *Server) carrierNodeBrowse(w http.ResponseWriter, r *http.Request) { s.carrierNodeFiles(w, r) } - -func (s *Server) carrierNodeWatch(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - _, _ = io.WriteString(w, "event: ready\ndata: {\"ok\":true}\n\n") - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() - } - <-r.Context().Done() -} - -func (s *Server) carrierNodeReloadMounts(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) carrierNodeDownloads(w http.ResponseWriter, r *http.Request) { - limit := optionalInt(r.URL.Query().Get("limit"), 500, 1, 1000) - rows, err := s.db.Query(r.Context(), `SELECT file_name, file_path, media_type, source_url, file_size_bytes, created_at FROM downloaded_media WHERE file_name IS NOT NULL ORDER BY created_at DESC LIMIT $1`, limit) - if err != nil { - writeError(w, http.StatusInternalServerError, "downloads unavailable") - return - } - defer rows.Close() - files := make([]map[string]any, 0) - for rows.Next() { - var name, path, mediaType, sourceURL string - var size int64 - var created time.Time - if rows.Scan(&name, &path, &mediaType, &sourceURL, &size, &created) != nil { - continue - } - files = append(files, map[string]any{"name": name, "path": path, "type": mediaType, "sourceUrl": sourceURL, "size": size, "mtime": created}) - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "files": files}) -} - -// walkRootTimeout bounds how long a single root's filesystem walk can run before walkFiles gives -// up on it. effectiveMediaRoots now includes every media-library path configured in -// ProjectConfigurator's Projects workspace across every project, not just the operator's own -// verified MEDIA_ROOTS - a -// typo'd path or a mount that isn't actually reachable from this container (an unresponsive -// network share, say) would otherwise be able to hang every caller of walkFiles (discovery, -// /api/stats, browsing) indefinitely, since a blocked stat/readdir syscall can't be interrupted by -// checking ctx.Err() alone. The walk itself still runs to completion in its own goroutine if it's -// genuinely just slow (a huge directory tree) - only the caller stops waiting on it. -const walkRootTimeout = 15 * time.Second - -func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry { - result := make([]fileEntry, 0) - for _, root := range s.effectiveMediaRoots(ctx) { - root := root - base := root - if relative != "" && safeRelative(relative) { - base = filepath.Join(root, filepath.FromSlash(relative)) - } - done := make(chan []fileEntry, 1) - go func() { - found := make([]fileEntry, 0) - _ = filepath.WalkDir(base, func(full string, entry os.DirEntry, err error) error { - if err != nil || entry == nil || entry.IsDir() || ctx.Err() != nil { - return nil - } - info, err := entry.Info() - if err != nil { - return nil - } - rel, err := filepath.Rel(root, full) - if err != nil || !safeRelative(filepath.ToSlash(rel)) { - return nil - } - found = append(found, fileEntry{Rel: filepath.ToSlash(rel), Path: filepath.ToSlash(rel), Type: fileType(rel), Size: info.Size(), Mtime: info.ModTime().UnixMilli()}) - return nil - }) - done <- found - }() - select { - case found := <-done: - result = append(result, found...) - case <-time.After(walkRootTimeout): - log.Printf("carriernode: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout) - case <-ctx.Done(): - return result - } - } - return result -} - -func (s *Server) carrierNodeUpload(w http.ResponseWriter, r *http.Request) { - if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") { - s.carrierNodeRawUpload(w, r) - return - } - if s.cfg.MaxUploadBytes > 0 { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) - } - if err := r.ParseMultipartForm(8 << 20); err != nil { - writeError(w, http.StatusBadRequest, "invalid upload") - return - } - file, header, err := r.FormFile("file") - if err != nil { - writeError(w, http.StatusBadRequest, "file is required") - return - } - defer file.Close() - name := filepath.Base(header.Filename) - if name == "." || name == "" || !safeRelative(name) { - writeError(w, http.StatusBadRequest, "invalid filename") - return - } - if err := os.MkdirAll(s.cfg.DownloadsRoot, 0o750); err != nil { - writeError(w, http.StatusInternalServerError, "upload directory unavailable") - return - } - target := filepath.Join(s.cfg.DownloadsRoot, name) - out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) - if err != nil { - writeError(w, http.StatusInternalServerError, "upload could not be stored") - return - } - defer out.Close() - if _, err := io.Copy(out, file); err != nil { - writeError(w, http.StatusInternalServerError, "upload could not be stored") - return - } - writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "filename": name, "path": name}) -} - -func (s *Server) carrierNodeDeleteDownload(w http.ResponseWriter, r *http.Request) { - name := chi.URLParam(r, "filename") - if !safeRelative(name) { - writeError(w, http.StatusBadRequest, "invalid filename") - return - } - full, err := s.resolveUnderRoots(name, []string{s.cfg.DownloadsRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - if err := os.Remove(full); err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) carrierNodeStore(w http.ResponseWriter, r *http.Request) { - var input map[string]any - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - filePath, _ := input["filePath"].(string) - fullPath, err := s.resolveStoreFile(filePath) - if err != nil { - writeError(w, http.StatusBadRequest, "filePath must reference a file in a configured mount") - return - } - info, err := os.Stat(fullPath) - if err != nil || info.IsDir() { - writeError(w, http.StatusNotFound, "file not found on disk") - return - } - mediaKey := s.mediaKeyForPath(fullPath) - mediaType := inferMediaType(fullPath) - var mediaID int64 - if err := s.db.QueryRow(r.Context(), `INSERT INTO media (media_key, media_type, source, file_path, original_filename, size_bytes, modified_at, active) VALUES ($1,$2,'MediaDownloader',$3,$4,$5,$6,TRUE) ON CONFLICT (media_key) DO UPDATE SET media_type=EXCLUDED.media_type, source=EXCLUDED.source, file_path=EXCLUDED.file_path, size_bytes=EXCLUDED.size_bytes, modified_at=EXCLUDED.modified_at, active=TRUE RETURNING id`, mediaKey, mediaType, mediaKey, filepath.Base(fullPath), info.Size(), info.ModTime()).Scan(&mediaID); err != nil { - writeError(w, http.StatusInternalServerError, "media catalog update failed") - return - } - sourceURL, _ := input["sourceUrl"].(string) - tool, _ := input["tool"].(string) - if strings.TrimSpace(tool) == "" { - tool = "yt-dlp" - } - status, _ := input["status"].(string) - if strings.TrimSpace(status) == "" { - status = "completed" - } - _, _ = s.db.Exec(r.Context(), `INSERT INTO downloaded_media (media_id, source_url, tool, status, file_path, file_name, file_size_bytes, media_type) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, mediaID, sourceURL, tool, status, fullPath, filepath.Base(fullPath), info.Size(), mediaType) - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaKey": mediaKey, "mediaId": mediaID}) -} - -// resolveStoreFile is CarrierNode's own local-filesystem lookup for /api/store, which catalogs a -// file CraftStudio already pushed into one of CarrierNode's mounts (InputRoot, MediaRoots, -// DownloadsRoot, OutputRoot) - unlike everything else in this file, it's called with a path that -// isn't necessarily under MediaRoots, so it can't just use resolveMediaPath. -func (s *Server) resolveStoreFile(value string) (string, error) { - value = strings.TrimSpace(value) - if value == "" || strings.ContainsRune(value, 0) { - return "", os.ErrNotExist - } - roots := append([]string{s.cfg.InputRoot}, s.cfg.MediaRoots...) - roots = append(roots, s.cfg.DownloadsRoot, s.cfg.OutputRoot) - for _, root := range roots { - rootAbs, err := filepath.Abs(root) - if err != nil { - continue - } - candidate := filepath.FromSlash(value) - if !filepath.IsAbs(candidate) { - candidate = filepath.Join(rootAbs, candidate) - } - candidate, err = filepath.Abs(candidate) - if err != nil || !withinRoot(rootAbs, candidate) { - continue - } - info, err := os.Stat(candidate) - if err != nil || info.IsDir() { - continue - } - if !sameRealRoot(rootAbs, candidate) { - continue - } - return candidate, nil - } - return "", os.ErrNotExist -} - -func (s *Server) carrierNodeRawUpload(w http.ResponseWriter, r *http.Request) { - name := filepath.Base(strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("filename"), r.URL.Query().Get("file_name")))) - if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) { - writeError(w, http.StatusBadRequest, "valid filename query parameter is required") - return - } - targetRoot := s.cfg.DownloadsRoot - if strings.Contains(r.URL.Path, "upload-mounted") && len(s.cfg.MediaRoots) > 0 { - targetRoot = s.cfg.MediaRoots[0] - } - if err := os.MkdirAll(targetRoot, 0o750); err != nil { - writeError(w, http.StatusInternalServerError, "upload directory unavailable") - return - } - target := filepath.Join(targetRoot, name) - if !withinRoot(targetRoot, target) { - writeError(w, http.StatusBadRequest, "invalid upload path") - return - } - if s.cfg.MaxUploadBytes > 0 { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) - } - out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) - if err != nil { - writeError(w, http.StatusInternalServerError, "upload could not be stored") - return - } - _, copyErr := io.Copy(out, r.Body) - closeErr := out.Close() - if copyErr != nil || closeErr != nil { - _ = os.Remove(target) - writeError(w, http.StatusRequestEntityTooLarge, "upload could not be stored") - return - } - info, _ := os.Stat(target) - if info != nil && supportedMediaPath(target) { - s.indexMediaFile(r.Context(), s.mediaKeyForPath(target), info.Size(), info.ModTime(), "upload-"+time.Now().UTC().Format("20060102T150405.000000000Z")) - } - writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "fileName": name, "filename": name, "path": name, "size": infoSize(info)}) -} - -func (s *Server) mediaKeyForPath(fullPath string) string { - for _, root := range append(append([]string{}, s.cfg.MediaRoots...), s.cfg.DownloadsRoot, s.cfg.OutputRoot) { - rootAbs, err := filepath.Abs(root) - if err == nil { - if relative, relErr := filepath.Rel(rootAbs, fullPath); relErr == nil && safeRelative(filepath.ToSlash(relative)) { - return filepath.ToSlash(relative) - } - } - } - return filepath.Base(fullPath) -} - -func infoSize(info os.FileInfo) int64 { - if info == nil { - return 0 - } - return info.Size() -} - -func (s *Server) carrierNodeMedia(w http.ResponseWriter, r *http.Request) { - relative := chi.URLParam(r, "*") - if relative == "" { - relative = strings.TrimPrefix(r.URL.Path, "/media/") - } - full, err := s.resolveAnyMediaPath(r.Context(), relative) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - s.serveFile(w, r, full) -} - -func (s *Server) carrierNodeDownloadMedia(w http.ResponseWriter, r *http.Request) { - relative := strings.TrimPrefix(r.URL.Path, "/media/downloads/") - full, err := s.resolveUnderRoots(relative, []string{s.cfg.DownloadsRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "download not found") - return - } - s.serveFile(w, r, full) -} - -func (s *Server) carrierNodeGeneratedMedia(w http.ResponseWriter, r *http.Request) { - relative := strings.TrimPrefix(r.URL.Path, "/mount/generated/") - full, err := s.resolveUnderRoots(relative, []string{s.cfg.OutputRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "generated media not found") - return - } - s.serveFile(w, r, full) -} - -func (s *Server) carrierNodeThumbnail(w http.ResponseWriter, r *http.Request) { - relative := chi.URLParam(r, "*") - if relative == "" { - relative = strings.TrimPrefix(r.URL.Path, "/thumbnails/") - } - full, err := s.resolveThumbnailPath(relative) - if err != nil { - writeError(w, http.StatusNotFound, "thumbnail not found") - return - } - s.serveFile(w, r, full) -} - -func (s *Server) carrierNodeInputMedia(w http.ResponseWriter, r *http.Request) { - relative := strings.TrimPrefix(r.URL.Path, "/mount/inputs/") - full, err := s.resolveUnderRoots(relative, []string{s.cfg.InputRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "input file not found") - return - } - s.serveFile(w, r, full) -} - -func (s *Server) carrierNodeCopyMedia(w http.ResponseWriter, r *http.Request) { - relative := strings.TrimPrefix(r.URL.Path, "/mount/copies/") - full, err := s.resolveUnderRoots(relative, []string{s.cfg.CopyRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "copy file not found") - return - } - s.serveFile(w, r, full) -} - -// carrierNodeStreamUpload writes a raw request body into root/name, used by every internal -// push-result endpoint (thumbnails, outputs, inputs, copies). name is always reduced to its -// base component - callers never need nested directories, and this keeps every write flat and -// trivially contained within root (mirrors carrierNodeRawUpload's existing filename handling). -func (s *Server) carrierNodeStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) { - name = filepath.Base(strings.TrimSpace(name)) - if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) { - writeError(w, http.StatusBadRequest, "invalid filename") - return - } - if err := os.MkdirAll(root, 0o750); err != nil { - writeError(w, http.StatusInternalServerError, "storage directory unavailable") - return - } - target := filepath.Join(root, name) - if !withinRoot(root, target) { - writeError(w, http.StatusBadRequest, "invalid filename") - return - } - if s.cfg.MaxUploadBytes > 0 { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) - } - out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) - if err != nil { - writeError(w, http.StatusInternalServerError, "file could not be stored") - return - } - written, copyErr := io.Copy(out, r.Body) - closeErr := out.Close() - if copyErr != nil || closeErr != nil { - _ = os.Remove(target) - writeError(w, http.StatusRequestEntityTooLarge, "file could not be stored") - return - } - writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "name": name, "size": written}) -} - -func (s *Server) carrierNodeThumbnailUpload(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - if !safeRelative(id) || strings.ContainsAny(id, `/\`) { - writeError(w, http.StatusBadRequest, "invalid thumbnail id") - return - } - s.carrierNodeStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg") -} - -func (s *Server) carrierNodeThumbnailDelete(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - if !safeRelative(id) || strings.ContainsAny(id, `/\`) { - writeError(w, http.StatusBadRequest, "invalid thumbnail id") - return - } - if full, err := s.resolveThumbnailPath(id + ".jpg"); err == nil { - _ = os.Remove(full) - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) carrierNodeOutputUpload(w http.ResponseWriter, r *http.Request) { - s.carrierNodeStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name")) -} - -func (s *Server) carrierNodeInputUpload(w http.ResponseWriter, r *http.Request) { - s.carrierNodeStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name")) -} - -func (s *Server) carrierNodeCopyUpload(w http.ResponseWriter, r *http.Request) { - s.carrierNodeStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name")) -} - -func (s *Server) carrierNodeProbeFile(w http.ResponseWriter, r *http.Request) { - full, err := s.resolveAnyMediaPath(r.Context(), r.URL.Query().Get("path")) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - result, err := s.probeWithFFprobe(r.Context(), full) - if err != nil { - writeError(w, http.StatusUnprocessableEntity, "probe failed") - return - } - writeJSON(w, http.StatusOK, result) -} - -func (s *Server) mountKioskRoutes(r chi.Router) { - r.Get("/kiosk/status", s.kioskStatus) - r.Get("/config", s.kioskConfig) - r.HandleFunc("/images/*", s.kioskImage) -} - -func (s *Server) kioskConfig(w http.ResponseWriter, r *http.Request) { - intSetting := func(key string, fallback int64) int64 { - value := s.settingValue(r.Context(), key, "") - if parsed, err := strconv.ParseInt(value, 10, 64); err == nil { - return parsed - } - return fallback - } - writeJSON(w, http.StatusOK, map[string]any{ - "defaultDisplayDuration": intSetting("default_display_duration", 5000), "defaultProgressVisibility": s.settingValue(r.Context(), "kiosk_progress_visibility", "hover"), - "defaultQueueVisibility": s.settingValue(r.Context(), "kiosk_queue_visibility", "hover"), "defaultDurationVisibility": s.settingValue(r.Context(), "kiosk_duration_visibility", "hover"), - "defaultIconVisibility": s.settingValue(r.Context(), "kiosk_icon_visibility", "hover"), "defaultStatsPosition": s.settingValue(r.Context(), "kiosk_stats_position", "bottom-left"), - "defaultQueueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"), "defaultPreloadCount": intSetting("default_preload_count", 1), - "defaultServerDisplayDuration": intSetting("server_display_duration", 5000), "currentQueueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"), "currentServerDisplayDuration": intSetting("server_display_duration", 5000), - }) -} - -func (s *Server) kioskStatus(w http.ResponseWriter, r *http.Request) { - s.kioskMu.Lock() - latest := s.kioskLatest - s.kioskMu.Unlock() - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "latestImage": latest, "queueLength": 0}) -} - -func (s *Server) mountKioskSocket(r chi.Router) { - r.Get("/ws", s.kioskWebsocket) -} - -func (s *Server) fileType(value string) string { return fileType(value) } - -func fileType(value string) string { - switch strings.ToLower(filepath.Ext(value)) { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg": - return "image" - case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac": - return "audio" - case ".mp4", ".mkv", ".mov", ".avi", ".webm", ".wmv": - return "video" - default: - return "other" - } -} - -// trailingInstanceSuffix strips a "_2", "_3", ... instance suffix, mirroring -// ConfigWorkspace.svelte's getBaseProject - the same "AuthGuard" / "AuthGuard_2" / "AuthGuard_3" -// naming convention every multi-instance central/main service in the Projects workspace uses. -var trailingInstanceSuffix = regexp.MustCompile(`_\d+$`) - -func instanceBaseKey(key string) string { - return trailingInstanceSuffix.ReplaceAllString(key, "") -} - -func sensitiveSetting(key string) bool { - switch strings.ToLower(key) { - case "session_secret", "internal_service_secret", "smtp_pass": - return true - default: - return false - } -} - -func normalizeServiceURL(value string) (string, error) { - parsed, err := url.Parse(strings.TrimSpace(value)) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" { - return "", errors.New("a valid http(s) URL is required") - } - if parsed.User != nil { - return "", errors.New("URL credentials are not allowed") - } - parsed.Path = strings.TrimRight(parsed.Path, "/") - return parsed.String(), nil -} - -func normalizeMappingPaths(value any) []string { - result := []string{} - switch raw := value.(type) { - case string: - if raw != "" { - result = append(result, raw) - } - case []any: - for _, item := range raw { - if text, ok := item.(string); ok && text != "" { - result = append(result, text) - } - } - case []string: - result = append(result, raw...) - } - return result -} - -func ptrBool(value bool) *bool { return &value } diff --git a/shared/media-backend/internal/server/analyzer.go b/shared/media-backend/internal/server/analyzer.go deleted file mode 100644 index 4e77659..0000000 --- a/shared/media-backend/internal/server/analyzer.go +++ /dev/null @@ -1,2182 +0,0 @@ -package server - -import ( - "bytes" - "context" - "crypto/rand" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "os" - "os/exec" - "path/filepath" - "strings" - "sync" - "time" - - "github.com/go-chi/chi/v5" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" -) - -func (s *Server) mountAnalyzerRoutes(r chi.Router) { - r.Get("/status", s.analyzerStatus) - r.Get("/stats", s.analyzerStats) - r.Get("/history", s.analyzerHistory) - r.Get("/extract/count", s.analyzerExtractCount) - r.Get("/generate/status", s.analyzerGenerateStatus) - r.Get("/events", s.analyzerEvents) - r.Get("/media", s.listMedia) - r.Get("/thumb", s.analyzerThumb) - r.Get("/model-config", s.modelConfig) - r.With(s.auth.RequireIfLoginRequired).Post("/model-config", s.saveModelConfig) - r.With(s.auth.RequireIfLoginRequired).Post("/model-config/order", s.saveModelOrder) - r.Get("/pipeline-config", s.pipelineConfig) - r.With(s.auth.RequireIfLoginRequired).Post("/pipeline-config", s.savePipelineConfig) - r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/{mediaType}/clear", s.clearMediaTypePipeline) - r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/clear", s.clearPipelineSelection) - r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/{mediaType}/retry-errors/{stage}", func(w http.ResponseWriter, req *http.Request) { - s.retryPipelineErrors(w, req, strings.ToLower(chi.URLParam(req, "mediaType")), strings.ToLower(chi.URLParam(req, "stage"))) - }) - r.Get("/pipeline/{mediaType}/errors/{stage}", func(w http.ResponseWriter, req *http.Request) { - s.pipelineStageErrors(w, req, strings.ToLower(chi.URLParam(req, "mediaType")), strings.ToLower(chi.URLParam(req, "stage"))) - }) - r.Get("/automation-schedules", s.analyzerSchedules) - r.With(s.auth.RequireIfLoginRequired).Post("/automation-schedules", s.createAnalyzerSchedule) - r.With(s.auth.RequireIfLoginRequired).Post("/automation-schedules/{id}/run", s.runAnalyzerSchedule) - r.With(s.auth.RequireIfLoginRequired).Delete("/automation-schedules/{id}", s.deleteAnalyzerSchedule) - r.Get("/conversion-settings", s.conversionSettings) - r.With(s.auth.RequireIfLoginRequired).Post("/conversion-settings", s.saveConversionSettings) - - r.With(s.auth.RequireIfLoginRequired).Post("/extract/discover", s.analyzerDiscover) - r.With(s.auth.RequireIfLoginRequired).Post("/metadata/start", s.analyzerMetadataStart) - r.With(s.auth.RequireIfLoginRequired).Post("/cleanup/start", s.analyzerCleanupStart) - r.With(s.auth.RequireIfLoginRequired).Post("/scan/stop", s.analyzerScanStop) - for _, action := range []string{"extract/start", "extract/queued/start", "retry-errors/start", "reprocess-all/start", "convert/start", "convert/start-group", "convert/start-discovered", "watcher/enable", "watcher/disable", "extract/stop", "extract/pause", "extract/resume"} { - actionPath := action - r.With(s.auth.RequireIfLoginRequired).Post("/"+actionPath, func(w http.ResponseWriter, req *http.Request) { s.analyzerAction(w, req, actionPath) }) - } - r.With(s.auth.RequireIfLoginRequired).Post("/generate/start", s.analyzerGenerateStart) - r.With(s.auth.RequireIfLoginRequired).Post("/generate/stop", s.analyzerGenerateStop) - r.Get("/analyze/status", s.analyzerAnalyzeStatus) - r.With(s.auth.RequireIfLoginRequired).Post("/analyze/start", s.analyzerAnalyzeStart) - r.With(s.auth.RequireIfLoginRequired).Post("/analyze/stop", s.analyzerAnalyzeStop) - r.With(s.auth.RequireIfLoginRequired).Post("/analyze/queued/start", s.analyzerAnalyzeStart) - r.With(s.auth.RequireIfLoginRequired).Post("/redo-analysis/start", s.analyzerAnalyzeStart) -} - -// analyzerStatus reports the analyzer's overall live state for the dashboard, schedules, and -// discover pages. media_worker_jobs rows never actually sit in "processing" - scanMediaFiles -// indexes each file synchronously straight to "done" - so job-table counts alone can't tell the -// UI a discovery walk, thumbnail pass, AI analysis run, or database clear is active. The in-memory -// scan/thumbnail/analysis/clear state (also used by analyzerPipelineBreakdown) is the only honest -// source for that, so it takes priority here and the job counts are just a fallback for outside -// consumers of "queue". -func (s *Server) analyzerStatus(w http.ResponseWriter, r *http.Request) { - // One query (four counts via FILTER) instead of four, run concurrently with the paused-setting - // lookup instead of after it - two round trips total instead of five, one after another. - var queued, processing, done, failed int64 - var paused bool - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - _ = s.db.QueryRow(r.Context(), ` - SELECT - COUNT(*) FILTER (WHERE status = 'queued'), - COUNT(*) FILTER (WHERE status = 'processing'), - COUNT(*) FILTER (WHERE status IN ('done', 'completed')), - COUNT(*) FILTER (WHERE status IN ('error', 'failed')) - FROM media_worker_jobs`).Scan(&queued, &processing, &done, &failed) - }() - go func() { - defer wg.Done() - paused = s.settingBool(r.Context(), "analyzer_paused", false) - }() - wg.Wait() - - s.scanMu.Lock() - scan := s.scan - s.scanMu.Unlock() - s.thumbnailMu.Lock() - thumbnail := s.thumbnail - s.thumbnailMu.Unlock() - s.analysisMu.Lock() - analysis := s.analysis - s.analysisMu.Unlock() - s.clearMu.Lock() - clear := s.clear - s.clearMu.Unlock() - - state, worker, current, currentType := "idle", "", "", "" - total, completed, jobFailed := 0, int(done), int(failed) - switch { - case clear.Running: - state, worker, current, currentType = "clearing", "Database cleanup", clear.Current, clear.CurrentType - total, completed, jobFailed = clear.Total, clear.Completed, clear.Failed - case scan.Running: - switch scan.Mode { - case "metadata": - state, worker = "extracting", "Metadata extraction" - case "cleanup": - state, worker = "cleaning", "Cleanup" - default: - state, worker = "discovering", "Discovery" - } - current, currentType = scan.CurrentFile, scan.CurrentType - completed = int(scan.FilesIndexed) - total = int(scan.Total) // only metadata/cleanup pre-fetch their row list; discover leaves this 0 (unknown) - // FilesIndexed counts every item touched this run, success or failure, so it alone already - // reaches Total when done - the default jobFailed above is a stale, unrelated, all-time - // count from the job-table query at the top of this function, not this run's failures. Left - // in, completed+failed could exceed Total and make the progress bar look wrong/stuck. - jobFailed = 0 - case thumbnail.Running: - state, worker, current, currentType = "generating", "Thumbnail generation", thumbnail.Current, thumbnail.CurrentType - total, completed, jobFailed = thumbnail.Total, thumbnail.Completed, thumbnail.Failed - case analysis.Running: - state, worker, current, currentType = "analyzing", "AI analysis", analysis.Current, analysis.CurrentType - total, completed, jobFailed = analysis.Total, analysis.Completed, analysis.Failed - case paused: - state = "paused" - case processing > 0: - state, worker = "processing", "Extraction" - } - running := clear.Running || scan.Running || thumbnail.Running || analysis.Running || processing > 0 - // scan/clear have no dedicated status endpoint of their own (thumbnail/analysis do, via - // generate/status and analyze/status) - this is the only place their LastError ever reaches - // the UI, so a discover/metadata/cleanup run that fails fast (e.g. CarrierNode unreachable) - // is reported here instead of just looking like it silently reverted to idle. - lastError := firstNonEmpty(scan.LastError, clear.LastError) - - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, "running": running, "paused": paused, "state": state, - "worker": worker, "current": current, "currentType": currentType, - "total": total, "completed": completed, "failed": jobFailed, - "lastError": lastError, - "updatedAt": time.Now().UTC(), - "queue": map[string]any{"queued": queued, "processing": processing, "done": done, "failed": failed}, - "extractionProgress": map[string]any{ - "queued": queued, "processing": processing, "completed": done, "failed": failed, "paused": paused, - }, - }) -} - -func (s *Server) analyzerStats(w http.ResponseWriter, r *http.Request) { - result := map[string]any{} - // Three round trips (media counts, job total, breakdown) run concurrently instead of one after - // another - the media counts used to be five separate single-purpose queries on top of that, - // now folded into the one below via FILTER. Loading this page used to mean seven-plus - // sequential DB round trips; it's now effectively the cost of the single slowest query. - var wg sync.WaitGroup - var pipeline map[string]analyzerPipelineMedia - var jobTotal int64 - - wg.Add(1) - go func() { - defer wg.Done() - var media, images, videos, audio, funscripts int64 - err := s.db.QueryRow(r.Context(), ` - SELECT - COUNT(*) FILTER (WHERE active = TRUE), - COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'image'), - COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'video'), - COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'audio'), - COUNT(*) FILTER (WHERE active = TRUE AND has_funscript = TRUE) - FROM media`).Scan(&media, &images, &videos, &audio, &funscripts) - if err != nil { - return - } - result["media"] = media - result["images"] = images - result["videos"] = videos - result["audio"] = audio - result["funscripts"] = funscripts - }() - - wg.Add(1) - go func() { - defer wg.Done() - _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_worker_jobs`).Scan(&jobTotal) - }() - - wg.Add(1) - go func() { - defer wg.Done() - pipeline = s.analyzerPipelineBreakdown(r.Context()) - }() - - wg.Wait() - result["total"] = jobTotal - for _, key := range []string{"media", "images", "videos", "audio", "funscripts"} { - if _, ok := result[key]; !ok { - result[key] = int64(0) - } - } - - queued, processing, completed, errors := summarizePipelineBreakdown(pipeline) - // Top-level totals are the sum of the exact same per-stage, per-media-type buckets the - // pipeline breakdown card renders below them (see summarizePipelineBreakdown), rather than a - // separate media_worker_jobs-only query - that query only ever reflects the "discover" stage - // (and media_worker_jobs rows go straight to "done" on discovery, never "processing"), so it - // silently ignored every file still queued/processing/erroring in metadata, thumbnails, or AI - // analysis and could never agree with what the breakdown showed underneath it. - result["queued"] = queued - result["processing"] = processing - result["completed"] = completed - result["errors"] = errors - result["failed"] = errors - result["pipeline"] = pipeline - writeJSON(w, http.StatusOK, result) -} - -// summarizePipelineBreakdown sums queued/processing/completed/errors across every stage and media -// type the pipeline breakdown actually shows, mirroring AnalyzerPipelineBreakdown.svelte's -// stagesFor() filtering: thumbnails only ever run for images/videos, and funscript has no AI -// analysis stage, so those combinations (which the breakdown map still carries, always zero-ish -// but not meaningfully so - see the thumbnail/analysis queries) are excluded here exactly as they -// are from the rendered table, keeping the dashboard totals and the breakdown card in agreement. -func summarizePipelineBreakdown(breakdown map[string]analyzerPipelineMedia) (queued, processing, completed, errors int64) { - for _, stage := range []string{"discover", "extract", "generate", "analyze"} { - for _, mediaType := range []string{"image", "video", "audio", "funscript"} { - if stage == "generate" && mediaType != "image" && mediaType != "video" { - continue - } - if stage == "analyze" && mediaType == "funscript" { - continue - } - counts, ok := breakdown[stage][mediaType] - if !ok { - continue - } - queued += counts["queued"] - processing += counts["processing"] - completed += counts["completed"] - errors += counts["errors"] - } - } - return -} - -type analyzerPipelineCounts map[string]int64 -type analyzerPipelineMedia map[string]analyzerPipelineCounts - -func newAnalyzerPipelineBreakdown() map[string]analyzerPipelineMedia { - breakdown := make(map[string]analyzerPipelineMedia) - for _, stage := range []string{"discover", "convert", "extract", "generate", "analyze"} { - breakdown[stage] = make(analyzerPipelineMedia) - for _, mediaType := range []string{"image", "video", "audio", "funscript"} { - breakdown[stage][mediaType] = analyzerPipelineCounts{"queued": 0, "processing": 0, "completed": 0, "errors": 0, "active": 0} - } - } - return breakdown -} - -// analyzerPipelineBreakdown runs six independent queries against three different tables. They used -// to run one after another - six sequential DB round trips just to load the dashboard - so they -// now run concurrently and each only takes the mutex to apply its own (already-fetched) rows into -// the shared breakdown map. Total latency drops from the sum of all six queries to roughly the -// slowest single one. -func (s *Server) analyzerPipelineBreakdown(ctx context.Context) map[string]analyzerPipelineMedia { - breakdown := newAnalyzerPipelineBreakdown() - var mu sync.Mutex - var wg sync.WaitGroup - - wg.Add(1) - go func() { - defer wg.Done() - mediaRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(media_type, '')), COUNT(*), COUNT(*) FILTER (WHERE has_funscript = TRUE) - FROM media - WHERE active = TRUE - GROUP BY LOWER(COALESCE(media_type, ''))`) - if err != nil { - return - } - type mediaTotals struct { - mediaType string - total, funscripts int64 - } - results := make([]mediaTotals, 0) - for mediaRows.Next() { - var row mediaTotals - if mediaRows.Scan(&row.mediaType, &row.total, &row.funscripts) == nil { - results = append(results, row) - } - } - mediaRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - if counts, ok := breakdown["discover"][row.mediaType]; ok { - counts["completed"] = row.total - } - breakdown["discover"]["funscript"]["completed"] += row.funscripts - } - }() - - // Drives the "discover" bucket only - the legacy status column tracks the overall discovery - // row, not any one stage, so it's kept separate from the per-stage queries below. - wg.Add(1) - go func() { - defer wg.Done() - jobRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, '')), COUNT(*) - FROM media_worker_jobs - GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, ''))`) - if err != nil { - return - } - type jobTotals struct { - mediaType, status string - total int64 - } - results := make([]jobTotals, 0) - for jobRows.Next() { - var row jobTotals - if jobRows.Scan(&row.mediaType, &row.status, &row.total) == nil { - results = append(results, row) - } - } - jobRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - discoverCounts, ok := breakdown["discover"][row.mediaType] - if !ok { - continue - } - switch row.status { - case "queued": - discoverCounts["queued"] += row.total - case "error", "failed": - discoverCounts["errors"] += row.total - } - } - }() - - wg.Add(1) - go func() { - defer wg.Done() - metadataRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(metadata_status, '')), COUNT(*) - FROM media_worker_jobs - GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(metadata_status, ''))`) - if err != nil { - return - } - type metadataTotals struct { - mediaType, status string - total int64 - } - results := make([]metadataTotals, 0) - for metadataRows.Next() { - var row metadataTotals - if metadataRows.Scan(&row.mediaType, &row.status, &row.total) == nil { - results = append(results, row) - } - } - metadataRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - counts, ok := breakdown["extract"][row.mediaType] - if !ok { - continue - } - switch row.status { - case "queued": - counts["queued"] += row.total - case "completed": - counts["completed"] += row.total - case "error": - counts["errors"] += row.total - } - } - }() - - wg.Add(1) - go func() { - defer wg.Done() - funscriptRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(status, '')), COUNT(*) - FROM media_worker_jobs - WHERE has_funscript = TRUE - GROUP BY LOWER(COALESCE(status, ''))`) - if err != nil { - return - } - type funscriptTotals struct { - status string - total int64 - } - results := make([]funscriptTotals, 0) - for funscriptRows.Next() { - var row funscriptTotals - if funscriptRows.Scan(&row.status, &row.total) == nil { - results = append(results, row) - } - } - funscriptRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - counts := breakdown["extract"]["funscript"] - switch row.status { - case "queued": - counts["queued"] += row.total - breakdown["discover"]["funscript"]["queued"] += row.total - case "done", "completed": - counts["completed"] += row.total - case "error", "failed": - counts["errors"] += row.total - breakdown["discover"]["funscript"]["errors"] += row.total - } - } - }() - - wg.Add(1) - go func() { - defer wg.Done() - thumbnailRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(m.media_type, '')), - COUNT(*) FILTER (WHERE t.id IS NULL AND COALESCE(j.thumbnail_status, 'queued') <> 'error'), - COUNT(*) FILTER (WHERE t.id IS NOT NULL), - COUNT(*) FILTER (WHERE t.id IS NULL AND j.thumbnail_status = 'error') - FROM media m - LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - LEFT JOIN media_worker_jobs j ON j.file_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - WHERE m.active = TRUE - GROUP BY LOWER(COALESCE(m.media_type, ''))`) - if err != nil { - return - } - type thumbnailTotals struct { - mediaType string - missing, generated, errored int64 - } - results := make([]thumbnailTotals, 0) - for thumbnailRows.Next() { - var row thumbnailTotals - if thumbnailRows.Scan(&row.mediaType, &row.missing, &row.generated, &row.errored) == nil { - results = append(results, row) - } - } - thumbnailRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - if counts, ok := breakdown["generate"][row.mediaType]; ok { - counts["queued"] = row.missing - counts["completed"] = row.generated - counts["errors"] = row.errored - } - } - }() - - wg.Add(1) - go func() { - defer wg.Done() - analysisRows, err := s.db.Query(ctx, ` - SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, '')), COUNT(*) - FROM media_analysis_tasks - GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, ''))`) - if err != nil { - return - } - type analysisTotals struct { - mediaType, status string - total int64 - } - results := make([]analysisTotals, 0) - for analysisRows.Next() { - var row analysisTotals - if analysisRows.Scan(&row.mediaType, &row.status, &row.total) == nil { - results = append(results, row) - } - } - analysisRows.Close() - - mu.Lock() - defer mu.Unlock() - for _, row := range results { - counts, ok := breakdown["analyze"][row.mediaType] - if !ok { - continue - } - switch row.status { - case "queued": - counts["queued"] += row.total - case "processing": - counts["processing"] += row.total - case "completed": - counts["completed"] += row.total - case "error": - counts["errors"] += row.total - } - } - }() - - wg.Wait() - - s.scanMu.Lock() - scanning, scanType := s.scan.Running, s.scan.CurrentType - s.scanMu.Unlock() - if scanning { - for _, stage := range []string{"discover", "extract"} { - if counts, ok := breakdown[stage][scanType]; ok { - markActive(counts) - } - } - // Sidecar detection runs inline for every file the scan visits, not just videos/audios, - // so the funscript stage counts as active for the whole scan rather than one media type. - markActive(breakdown["extract"]["funscript"]) - } - - s.thumbnailMu.Lock() - generating, generatingType := s.thumbnail.Running, s.thumbnail.CurrentType - s.thumbnailMu.Unlock() - if generating { - if counts, ok := breakdown["generate"][generatingType]; ok { - markActive(counts) - } - } - - s.analysisMu.Lock() - analyzing, analyzingType := s.analysis.Running, s.analysis.CurrentType - s.analysisMu.Unlock() - if analyzing { - if counts, ok := breakdown["analyze"][analyzingType]; ok { - markActive(counts) - } - } - - return breakdown -} - -// markActive flags a stage/media-type bucket as currently being worked on, moving one unit from -// queued into processing when there's a pending item to attribute the active work to. -func markActive(counts analyzerPipelineCounts) { - counts["active"] = 1 - if counts["queued"] > 0 { - counts["queued"]-- - } - counts["processing"] = 1 -} - -// analyzerHistory supports the shared pagination + media type/status filtering the processing -// history card offers everywhere except the per-media-type tabs (which pass a fixed mediaType and -// hide the type filter instead of exposing it). "funscript" isn't a real media_type value - it's -// the has_funscript flag on a video/audio row - so it's translated to that condition instead of an -// equality check, matching how discovery/metadata already treat it. total comes back via a window -// function so listing a page never costs a second round trip for the count. -func (s *Server) analyzerHistory(w http.ResponseWriter, r *http.Request) { - limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 200) - offset := optionalInt(r.URL.Query().Get("offset"), 0, 0, 1_000_000_000) - mediaType := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("mediaType"))) - status := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("status"))) - - conditions := make([]string, 0, 2) - args := make([]any, 0, 4) - switch mediaType { - case "", "all": - case "funscript": - conditions = append(conditions, "has_funscript = TRUE") - default: - args = append(args, mediaType) - conditions = append(conditions, fmt.Sprintf("LOWER(COALESCE(media_type, '')) = $%d", len(args))) - } - switch status { - case "", "all": - case "done": - conditions = append(conditions, "LOWER(COALESCE(status, '')) IN ('done', 'completed')") - case "error": - conditions = append(conditions, "LOWER(COALESCE(status, '')) IN ('error', 'failed')") - default: - args = append(args, status) - conditions = append(conditions, fmt.Sprintf("LOWER(COALESCE(status, '')) = $%d", len(args))) - } - where := "TRUE" - if len(conditions) > 0 { - where = strings.Join(conditions, " AND ") - } - args = append(args, limit, offset) - - query := fmt.Sprintf(` - SELECT id, file_path, file_name, media_type, status, progress, queued_at, started_at, finished_at, COALESCE(error_message, ''), has_funscript, COUNT(*) OVER() - FROM media_worker_jobs - WHERE %s - ORDER BY queued_at DESC - LIMIT $%d OFFSET $%d`, where, len(args)-1, len(args)) - - rows, err := s.db.Query(r.Context(), query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "analyzer history unavailable") - return - } - defer rows.Close() - items := make([]map[string]any, 0) - var total int64 - for rows.Next() { - var id int64 - var filePath, fileName, mediaType, status, message string - var progress int - var queued time.Time - var started, finished *time.Time - var hasFunscript bool - if rows.Scan(&id, &filePath, &fileName, &mediaType, &status, &progress, &queued, &started, &finished, &message, &hasFunscript, &total) != nil { - continue - } - items = append(items, map[string]any{"id": id, "file_path": filePath, "file_name": fileName, "media_type": mediaType, "status": status, "progress": progress, "queued_at": queued, "started_at": started, "finished_at": finished, "error": message, "has_funscript": hasFunscript}) - } - writeJSON(w, http.StatusOK, map[string]any{"items": items, "history": items, "jobs": items, "total": total, "limit": limit, "offset": offset}) -} - -func (s *Server) analyzerExtractCount(w http.ResponseWriter, r *http.Request) { - var queued, processing int64 - if err := s.db.QueryRow(r.Context(), ` - SELECT - COUNT(*) FILTER (WHERE status = 'queued'), - COUNT(*) FILTER (WHERE status = 'processing') - FROM media_worker_jobs`).Scan(&queued, &processing); err != nil { - writeError(w, http.StatusInternalServerError, "queue count unavailable") - return - } - - var images, videos, audios, funscripts int64 - if err := s.db.QueryRow(r.Context(), ` - SELECT - COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'image'), - COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'video'), - COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'audio'), - COUNT(*) FILTER (WHERE has_funscript = TRUE) - FROM media - WHERE active = TRUE`).Scan(&images, &videos, &audios, &funscripts); err != nil { - writeError(w, http.StatusInternalServerError, "media count unavailable") - return - } - - writeJSON(w, http.StatusOK, map[string]any{ - "count": queued + processing, - "queued": queued, - "processing": processing, - "counts": map[string]any{ - "image": images, - "video": videos, - "audio": audios, - "funscript": funscripts, - "queued": queued, - }, - }) -} - -type thumbnailCandidate struct { - mediaKey string - filePath string - mediaType string -} - -func (s *Server) analyzerGenerateStatus(w http.ResponseWriter, r *http.Request) { - counts, err := s.thumbnailCounts(r.Context()) - if err != nil { - writeError(w, http.StatusInternalServerError, "thumbnail status unavailable") - return - } - - s.thumbnailMu.Lock() - state := s.thumbnail - s.thumbnailMu.Unlock() - - status := map[string]any{ - "running": state.Running, - "state": firstNonEmpty(state.State, "idle"), - "total": state.Total, - "completed": state.Completed, - "failed": state.Failed, - "current": state.Current, - "startedAt": state.StartedAt, - "finishedAt": state.FinishedAt, - "lastError": state.LastError, - } - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, - "status": status, - "counts": counts, - }) -} - -func (s *Server) analyzerGenerateStart(w http.ResponseWriter, r *http.Request) { - selected := parseMediaTypesPayload(r, false) - s.thumbnailMu.Lock() - if s.thumbnail.Running { - s.thumbnailMu.Unlock() - writeError(w, http.StatusConflict, "thumbnail generation is already running") - return - } - ctx, cancel := context.WithCancel(context.Background()) - now := time.Now().UTC() - s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now} - s.thumbnailCancel = cancel - s.thumbnailMu.Unlock() - - go s.generateThumbnails(ctx, selected) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"}) -} - -func (s *Server) analyzerGenerateStop(w http.ResponseWriter, r *http.Request) { - s.thumbnailMu.Lock() - cancel := s.thumbnailCancel - running := s.thumbnail.Running - s.thumbnailMu.Unlock() - if !running || cancel == nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"}) - return - } - log.Printf("analyzer: thumbnail generation stop requested") - cancel() - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"}) -} - -func (s *Server) thumbnailCounts(ctx context.Context) (map[string]int64, error) { - var total, missing, generated int64 - err := s.db.QueryRow(ctx, ` - SELECT - COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video')), - COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video') AND t.id IS NULL), - COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video') AND t.id IS NOT NULL) - FROM media m - LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - WHERE m.active = TRUE`).Scan(&total, &missing, &generated) - if err != nil { - return nil, err - } - return map[string]int64{"total": total, "missing": missing, "generated": generated}, nil -} - -// thumbnailCandidates lists files still missing a thumbnail. selectedTypes restricts the result to -// those media types (empty/nil means every eligible type) - thumbnails only ever exist for images -// and videos, so a selection of just "audio"/"funscript" legitimately yields zero candidates. -func (s *Server) thumbnailCandidates(ctx context.Context, selectedTypes map[string]bool) ([]thumbnailCandidate, error) { - query := ` - SELECT m.media_key, COALESCE(NULLIF(m.file_path, ''), m.media_key), LOWER(COALESCE(m.media_type, 'unknown')) - FROM media m - LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - WHERE m.active = TRUE - AND LOWER(COALESCE(m.media_type, '')) IN ('image', 'video') - AND t.id IS NULL` - args := []any{} - if len(selectedTypes) > 0 { - types := mediaTypesList(selectedTypes) - query += ` AND LOWER(COALESCE(m.media_type, '')) = ANY($1)` - args = append(args, types) - } - query += ` ORDER BY m.id ASC` - - rows, err := s.db.Query(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - - candidates := make([]thumbnailCandidate, 0) - for rows.Next() { - var candidate thumbnailCandidate - if err := rows.Scan(&candidate.mediaKey, &candidate.filePath, &candidate.mediaType); err != nil { - return nil, err - } - candidates = append(candidates, candidate) - } - if err := rows.Err(); err != nil { - return nil, err - } - return candidates, nil -} - -func (s *Server) generateThumbnails(ctx context.Context, selectedTypes map[string]bool) { - candidates, err := s.thumbnailCandidates(ctx, selectedTypes) - if err != nil { - if ctx.Err() != nil { - s.finishThumbnailGeneration(nil) - } else { - s.finishThumbnailGeneration(err) - } - return - } - - // Filtered here rather than in the SQL so the pipeline config (which can change between - // runs) is read fresh every time this actually executes, not just at query-build time. - enabled := make([]thumbnailCandidate, 0, len(candidates)) - for _, candidate := range candidates { - if s.pipelineStageEnabled(ctx, candidate.mediaType, "thumbnails") { - enabled = append(enabled, candidate) - } - } - s.runThumbnailCandidates(ctx, enabled) -} - -// thumbnailCandidatesWithErrors is the same shape as thumbnailCandidates but scoped to one media -// type and only the files whose last attempt actually failed - used by the per-stage retry-errors -// action rather than a full "Run pipeline" pass. -func (s *Server) thumbnailCandidatesWithErrors(ctx context.Context, mediaType string) ([]thumbnailCandidate, error) { - rows, err := s.db.Query(ctx, ` - SELECT m.media_key, COALESCE(NULLIF(m.file_path, ''), m.media_key), LOWER(COALESCE(m.media_type, 'unknown')) - FROM media m - JOIN media_worker_jobs j ON j.file_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - WHERE m.active = TRUE - AND LOWER(COALESCE(m.media_type, '')) = $1 - AND t.id IS NULL - AND j.thumbnail_status = 'error' - ORDER BY m.id ASC`, mediaType) - if err != nil { - return nil, err - } - defer rows.Close() - - candidates := make([]thumbnailCandidate, 0) - for rows.Next() { - var candidate thumbnailCandidate - if err := rows.Scan(&candidate.mediaKey, &candidate.filePath, &candidate.mediaType); err != nil { - return nil, err - } - candidates = append(candidates, candidate) - } - if err := rows.Err(); err != nil { - return nil, err - } - return candidates, nil -} - -func (s *Server) runThumbnailCandidates(ctx context.Context, candidates []thumbnailCandidate) { - log.Printf("analyzer: thumbnail generation started: %d candidates", len(candidates)) - s.thumbnailMu.Lock() - s.thumbnail.Total = len(candidates) - s.thumbnailMu.Unlock() - - for _, candidate := range candidates { - if ctx.Err() != nil { - s.finishThumbnailGeneration(nil) - return - } - - s.thumbnailMu.Lock() - s.thumbnail.Current = candidate.filePath - s.thumbnail.CurrentType = candidate.mediaType - s.thumbnailMu.Unlock() - - _, err := s.createThumbnail(ctx, candidate) - if ctx.Err() == nil { - if err != nil { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status='error', thumbnail_error=$2 WHERE file_path=$1`, candidate.filePath, err.Error()) - } else { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status='completed', thumbnail_error=NULL WHERE file_path=$1`, candidate.filePath) - } - } - s.thumbnailMu.Lock() - if err != nil { - if ctx.Err() == nil { - s.thumbnail.Failed++ - s.thumbnail.LastError = err.Error() - } - } else { - s.thumbnail.Completed++ - } - s.thumbnailMu.Unlock() - } - s.finishThumbnailGeneration(nil) -} - -func (s *Server) finishThumbnailGeneration(runErr error) { - now := time.Now().UTC() - s.thumbnailMu.Lock() - defer s.thumbnailMu.Unlock() - s.thumbnail.Running = false - s.thumbnailCancel = nil - s.thumbnail.Current = "" - s.thumbnail.CurrentType = "" - s.thumbnail.FinishedAt = &now - if runErr != nil { - s.thumbnail.State = "error" - s.thumbnail.LastError = runErr.Error() - } else if s.thumbnail.Completed+s.thumbnail.Failed < s.thumbnail.Total { - s.thumbnail.State = "stopped" - } else if s.thumbnail.Failed > 0 { - s.thumbnail.State = "completed_with_errors" - } else { - s.thumbnail.State = "completed" - s.thumbnail.LastError = "" - } - log.Printf("analyzer: thumbnail generation finished: %d/%d done, %d failed, state=%s", s.thumbnail.Completed, s.thumbnail.Total, s.thumbnail.Failed, s.thumbnail.State) - if s.thumbnail.LastError != "" { - log.Printf("analyzer: thumbnail generation last error: %s", s.thumbnail.LastError) - } -} - -func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandidate) (string, error) { - sourcePath := filepath.ToSlash(candidate.filePath) - if !supportedMediaPath(sourcePath) { - return "", fmt.Errorf("unsupported media type for %s", sourcePath) - } - - sourceScratch, cleanupSource, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath)) - if err != nil { - return "", fmt.Errorf("fetch %s: %w", sourcePath, err) - } - defer cleanupSource() - - thumbnailID, err := newThumbnailID() - if err != nil { - return "", err - } - temporary, err := os.CreateTemp("", ".thumbnail-*.jpg") - if err != nil { - return "", fmt.Errorf("create thumbnail temporary file: %w", err) - } - temporaryPath := temporary.Name() - if err := temporary.Close(); err != nil { - _ = os.Remove(temporaryPath) - return "", err - } - defer os.Remove(temporaryPath) - - args := []string{"-hide_banner", "-loglevel", "error", "-y"} - if candidate.mediaType == "video" { - args = append(args, "-ss", "0") - } - args = append(args, "-i", sourceScratch) - args = append(args, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath) - - fileContext, cancel := context.WithTimeout(ctx, 2*time.Minute) - defer cancel() - command := exec.CommandContext(fileContext, s.cfg.FFmpeg, args...) - var stderr bytes.Buffer - command.Stderr = &stderr - if err := command.Run(); err != nil { - detail := strings.TrimSpace(stderr.String()) - if len(detail) > 300 { - detail = detail[len(detail)-300:] - } - if detail != "" { - return "", fmt.Errorf("ffmpeg: %s", detail) - } - return "", err - } - info, err := os.Stat(temporaryPath) - if err != nil || info.Size() == 0 { - return "", fmt.Errorf("ffmpeg produced no thumbnail") - } - size, err := s.carrierNodePushThumbnail(ctx, thumbnailID, temporaryPath) - if err != nil { - return "", fmt.Errorf("store thumbnail: %w", err) - } - insertTag, err := s.db.Exec(ctx, ` - INSERT INTO thumbnails (id, source_path, file_size_bytes) - VALUES ($1, $2, $3) - ON CONFLICT (source_path) DO NOTHING`, thumbnailID, sourcePath, size) - if err != nil { - _ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID) - return "", fmt.Errorf("save thumbnail record: %w", err) - } - if insertTag.RowsAffected() == 0 { - _ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID) - return "", nil - } - return thumbnailID, nil -} - -func newThumbnailID() (string, error) { - var value [16]byte - if _, err := rand.Read(value[:]); err != nil { - return "", err - } - value[6] = (value[6] & 0x0f) | 0x40 - value[8] = (value[8] & 0x3f) | 0x80 - return fmt.Sprintf("%x-%x-%x-%x-%x", value[0:4], value[4:6], value[6:8], value[8:10], value[10:16]), nil -} - -func (s *Server) analyzerEvents(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - _, _ = fmt.Fprintf(w, "event: status\ndata: %s\n\n", string(mustJSON(map[string]any{"ok": true}))) - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() - } -} - -func (s *Server) analyzerThumb(w http.ResponseWriter, r *http.Request) { - id := strings.TrimSpace(r.URL.Query().Get("id")) - if !safeRelative(id) || len(id) > 100 { - writeError(w, http.StatusBadRequest, "invalid thumbnail id") - return - } - s.proxyCarrierNode(w, r, "/thumbnails/"+id+".jpg") -} - -func (s *Server) analyzerAction(w http.ResponseWriter, r *http.Request, action string) { - if action == "extract/pause" { - log.Printf("analyzer: extraction paused") - _ = s.saveSetting(r.Context(), "analyzer_paused", "true") - } - if action == "extract/resume" { - log.Printf("analyzer: extraction resumed") - _ = s.saveSetting(r.Context(), "analyzer_paused", "false") - } - if action == "extract/stop" { - log.Printf("analyzer: extraction stop requested (cancelling queued/processing jobs)") - _, _ = s.db.Exec(r.Context(), `UPDATE media_worker_jobs SET status='cancelled', finished_at=NOW() WHERE status IN ('queued','processing')`) - } - if strings.HasSuffix(action, "start") || action == "reprocess-all/start" { - // Same Running-set-before-dispatch ordering as analyzerDiscover, and for the same reason: - // setting it inside scanMediaFiles itself left a window where this response (and the - // client's own immediate status poll right after) could land before the goroutine got - // scheduled, reading back "idle" for an action that had, in fact, just started. - now := time.Now().UTC() - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - writeError(w, http.StatusConflict, "a discovery or metadata run is already active") - return - } - s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now} - s.scanMu.Unlock() - go s.scanMediaFiles(nil) - } - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": action, "started": true}) -} - -// parseMediaTypesPayload decodes {"types": [...]} the same way for every analyzer action that can -// be scoped to a subset of media types. An empty/missing list (including the plain no-body POST -// every existing caller already sends), an "all" entry, or a list that resolves to nothing all -// mean "no filter" - callers treat an empty map as "everything", matching the pre-existing -// discover behavior. mapFunscriptToVideo controls what a "funscript" entry resolves to: discovery -// and metadata refresh walk/probe video files and check each one for its sidecar, so it maps to -// "video" there; thumbnails and AI analysis have no such indirection, so it's kept literal there -// (a funscript-only selection for those correctly yields no candidates). -func parseMediaTypesPayload(r *http.Request, mapFunscriptToVideo bool) map[string]bool { - var payload struct { - Types []string `json:"types"` - } - _ = decodeRequestJSON(r, &payload) - return normalizeMediaTypes(payload.Types, mapFunscriptToVideo) -} - -// normalizeMediaTypes is parseMediaTypesPayload's actual logic, split out so a schedule's stored -// settings (already decoded from JSONB, not sitting in a live *http.Request body) can go through -// the exact same rules a live discover/metadata/generate/analyze request would. -func normalizeMediaTypes(raw []string, mapFunscriptToVideo bool) map[string]bool { - selected := map[string]bool{} - for _, item := range raw { - switch strings.ToLower(strings.TrimSpace(item)) { - case "image", "video", "audio": - selected[strings.ToLower(strings.TrimSpace(item))] = true - case "funscript": - if mapFunscriptToVideo { - selected["video"] = true - } else { - selected["funscript"] = true - } - case "all": - return map[string]bool{} - } - } - return selected -} - -func mediaTypesList(selected map[string]bool) []string { - return analyzerSelectionList(selected, analyzerMediaTypeOrder) -} - -// analyzerTypesLabel renders a media-type selection for a log line - "all" for an empty selection -// (no filter) rather than the empty-list "[]" mediaTypesList would otherwise print. -func analyzerTypesLabel(selected map[string]bool) string { - if len(selected) == 0 { - return "all" - } - return strings.Join(mediaTypesList(selected), ",") -} - -func analyzerSelectionList(selected map[string]bool, order []string) []string { - values := make([]string, 0, len(selected)) - for _, value := range order { - if selected[value] { - values = append(values, value) - } - } - return values -} - -// analyzerDiscover kicks off a scan, optionally restricted to a subset of media types. An empty -// or missing "types" list (including the plain no-body POST every existing caller already sends) -// means "discover everything", matching the previous unconditional behavior. -// -// The Running flag is set here, synchronously, before the goroutine is even dispatched - not -// inside scanMediaFiles itself. thumbnails/analysis already worked this way (see -// analyzerGenerateStart/analyzerAnalyzeStart); this one didn't, which left a real window where the -// HTTP response had already gone out (so the client's own immediate status poll could land) before -// the goroutine got scheduled and flipped s.scan.Running - long enough, especially with the -// paused-setting DB lookup that used to run first inside scanMediaFiles, for "Start discover" to -// read back "idle" right after starting. -func (s *Server) analyzerDiscover(w http.ResponseWriter, r *http.Request) { - selected := parseMediaTypesPayload(r, true) - - now := time.Now().UTC() - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - writeError(w, http.StatusConflict, "a discovery or metadata run is already active") - return - } - s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now} - s.scanMu.Unlock() - - go s.scanMediaFiles(selected) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "extract/discover", "started": true}) -} - -// analyzerMetadataStart refreshes ffprobe metadata (and the funscript sidecar flag) for every -// already-known active media row matching the selected types, without walking the filesystem for -// brand-new files the way discovery does. It shares discovery's scan slot/state since both are the -// same kind of synchronous per-file walk and can't sensibly run at the same time. Running is set -// here for the same reason as analyzerDiscover above - before the goroutine starts, not inside it. -func (s *Server) analyzerMetadataStart(w http.ResponseWriter, r *http.Request) { - selected := parseMediaTypesPayload(r, true) - - now := time.Now().UTC() - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - writeError(w, http.StatusConflict, "a discovery or metadata run is already active") - return - } - s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now} - s.scanMu.Unlock() - - go s.refreshMetadataForTypes(selected) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "metadata/start", "started": true}) -} - -// analyzerCleanupStart removes active media rows (and their worker-job, thumbnail, and AI-analysis -// records) whose underlying file no longer resolves under any configured media root - the actual -// "stale entry" work discovery/metadata never do, since a filesystem walk only ever visits files -// that still exist and so can never notice one that's been deleted. Shares discovery's scan slot -// for the same reason analyzerMetadataStart does: both are a synchronous per-file walk. -func (s *Server) analyzerCleanupStart(w http.ResponseWriter, r *http.Request) { - now := time.Now().UTC() - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - writeError(w, http.StatusConflict, "a discovery or metadata run is already active") - return - } - s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now} - s.scanMu.Unlock() - - go s.cleanupStaleMedia() - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "cleanup/start", "started": true}) -} - -// analyzerScanStop cancels whichever scan-based run (discover/metadata/cleanup) is currently -// active - they share one scan slot/cancel func since only one can ever run at a time (see -// analyzerDiscover/analyzerMetadataStart/analyzerCleanupStart). Mirrors analyzerGenerateStop and -// analyzerAnalyzeStop's cancel-func pattern. -func (s *Server) analyzerScanStop(w http.ResponseWriter, r *http.Request) { - s.scanMu.Lock() - cancel := s.scanCancel - running := s.scan.Running - s.scanMu.Unlock() - if !running || cancel == nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"}) - return - } - log.Printf("analyzer: scan stop requested") - cancel() - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"}) -} - -// cleanupStaleMedia does the actual sweep. s.scan is already set to Running by the caller -// (analyzerCleanupStart) before this goroutine was even dispatched - this only clears it when done. -func (s *Server) cleanupStaleMedia() { - log.Printf("analyzer: cleanup sweep started") - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) - defer cancel() - s.scanMu.Lock() - s.scanCancel = cancel - s.scanMu.Unlock() - removed := 0 - var runErr error - defer func() { - s.scanMu.Lock() - checked := s.scan.FilesIndexed - lastError := "" - if runErr != nil { - lastError = runErr.Error() - } - s.scan = scanState{LastError: lastError} - s.scanCancel = nil - s.scanMu.Unlock() - log.Printf("analyzer: cleanup sweep finished: %d checked, %d marked stale", checked, removed) - }() - - rows, err := s.db.Query(ctx, `SELECT media_key, LOWER(COALESCE(media_type, '')), COALESCE(NULLIF(file_path, ''), media_key) FROM media WHERE active = TRUE`) - if err != nil { - log.Printf("analyzer: cleanup sweep: failed to load media rows: %v", err) - runErr = fmt.Errorf("failed to load media rows: %w", err) - return - } - type mediaItem struct{ key, mediaType, filePath string } - items := make([]mediaItem, 0) - for rows.Next() { - var item mediaItem - if rows.Scan(&item.key, &item.mediaType, &item.filePath) == nil { - items = append(items, item) - } - } - rows.Close() - - s.scanMu.Lock() - s.scan.Total = int64(len(items)) - s.scanMu.Unlock() - - for _, item := range items { - if ctx.Err() != nil { - return - } - s.scanMu.Lock() - s.scan.CurrentType = item.mediaType - s.scan.CurrentFile = item.filePath - s.scan.FilesIndexed++ - s.scanMu.Unlock() - - if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists { - continue // file still exists on disk - nothing stale about this one - } - removed++ - - _, _ = s.db.Exec(ctx, `UPDATE media SET active = FALSE WHERE media_key = $1`, item.key) - - var thumbnailID string - if s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, item.filePath).Scan(&thumbnailID) == nil { - _ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID) - _, _ = s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = $1`, thumbnailID) - } - _, _ = s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE file_path = $1`, item.filePath) - _, _ = s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE media_key = $1`, item.key) - } -} - -// scanMediaFiles does the actual walk. s.scan is already set to Running by the caller -// (analyzerDiscover) before this goroutine was even dispatched - this only clears it when done. -func (s *Server) scanMediaFiles(selectedTypes map[string]bool) { - log.Printf("analyzer: discovery scan started (types=%s)", analyzerTypesLabel(selectedTypes)) - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) - defer cancel() - s.scanMu.Lock() - s.scanCancel = cancel - s.scanMu.Unlock() - var runErr error - defer func() { - s.scanMu.Lock() - indexed := s.scan.FilesIndexed - lastError := "" - if runErr != nil { - lastError = runErr.Error() - } - s.scan = scanState{LastError: lastError} - s.scanCancel = nil - s.scanMu.Unlock() - log.Printf("analyzer: discovery scan finished: %d files indexed", indexed) - }() - - batch := time.Now().UTC().Format("20060102T150405.000000000Z") - files, err := s.carrierNodeListFiles(ctx, "", false, 0) - if err != nil { - log.Printf("analyzer: discovery scan: failed to list files: %v", err) - runErr = fmt.Errorf("could not reach CarrierNode to list files: %w", err) - return - } - // CarrierNode reachable but reporting an empty library is otherwise indistinguishable from - // a successful no-op run - every existing file re-indexes (and increments FilesIndexed) on - // every scan, so a real library can never legitimately finish at zero. Flag it instead of - // letting "discovery started" silently revert to idle with nothing to show for it. - if len(files) == 0 { - log.Printf("analyzer: discovery scan: CarrierNode reported zero files") - runErr = fmt.Errorf("CarrierNode reported no files under its configured media root(s) - check the Projects settings in ProjectConfigurator") - return - } - for _, file := range files { - if ctx.Err() != nil { - return - } - if !supportedMediaPath(file.Rel) { - continue - } - if len(selectedTypes) > 0 && !selectedTypes[inferMediaType(file.Rel)] { - continue - } - s.indexMediaFile(ctx, file.Rel, file.Size, time.UnixMilli(file.Mtime).UTC(), batch) - } -} - -func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, modified time.Time, batch string) { - if !safeRelative(key) { - return - } - key = filepath.ToSlash(key) - mediaType := inferMediaType(key) - - s.scanMu.Lock() - s.scan.CurrentType = mediaType - s.scan.CurrentFile = key - s.scan.FilesIndexed++ - s.scanMu.Unlock() - - // ffprobe reads images too (just dimensions, no duration), so metadata extraction now - // covers every type - previously images silently never got width/height populated at all. - metadataAttempted := (mediaType == "video" || mediaType == "audio" || mediaType == "image") && s.pipelineStageEnabled(ctx, mediaType, "metadata") - var duration any - var width, height int - var probeErr error - var hasFunscript bool - // CarrierNode has the storage mounted and can probe/stat locally; every other service goes - // through CarrierNode's HTTP API instead of touching MediaRoots itself (see carriernode_client.go). - if s.cfg.Service == config.CarrierNode { - fullPath, resolveErr := s.resolveAnyMediaPath(ctx, key) - if metadataAttempted && resolveErr == nil { - var probe map[string]any - probe, probeErr = s.probeWithFFprobe(ctx, fullPath) - if probe != nil { - duration = probe["durationMs"] - width = probeInt(probe, "width") - height = probeInt(probe, "height") - } - } - hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && resolveErr == nil && hasFunscriptSidecar(fullPath) - } else { - if metadataAttempted { - var probe carrierNodeProbeResult - probe, probeErr = s.carrierNodeProbe(ctx, key) - duration = nullableInt64(probe.DurationMs) - width, height = probe.Width, probe.Height - } - hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && s.funscriptSidecarExists(ctx, key) - } - _, _ = s.db.Exec(ctx, `INSERT INTO media (media_key, media_type, source, file_path, original_filename, size_bytes, duration_ms, width, height, modified_at, has_funscript, active) VALUES ($1,$2,'Filesystem',$3,$4,$5,$6,$7,$8,$9,$10,TRUE) ON CONFLICT (media_key) DO UPDATE SET file_path=EXCLUDED.file_path, original_filename=EXCLUDED.original_filename, size_bytes=EXCLUDED.size_bytes, duration_ms=COALESCE(EXCLUDED.duration_ms, media.duration_ms), width=COALESCE(EXCLUDED.width, media.width), height=COALESCE(EXCLUDED.height, media.height), modified_at=EXCLUDED.modified_at, has_funscript=EXCLUDED.has_funscript, active=TRUE`, key, mediaType, key, filepath.Base(key), size, duration, nullableInt(width), nullableInt(height), modified, hasFunscript) - _, _ = s.db.Exec(ctx, `INSERT INTO media_worker_jobs (media_key, file_path, file_name, media_type, status, progress, file_size_bytes, scan_batch_id, finished_at, has_funscript) VALUES ($1,$2,$3,$4,'done',100,$5,$6,NOW(),$7) ON CONFLICT (file_path) DO UPDATE SET file_name=EXCLUDED.file_name, media_type=EXCLUDED.media_type, file_size_bytes=EXCLUDED.file_size_bytes, scan_batch_id=EXCLUDED.scan_batch_id, has_funscript=EXCLUDED.has_funscript, status=CASE WHEN media_worker_jobs.status IN ('error','failed') THEN 'queued' ELSE media_worker_jobs.status END`, key, key, filepath.Base(key), mediaType, size, batch, hasFunscript) - - // Only touch metadata_status/metadata_error when metadata extraction actually ran for this - // file this pass - when the stage is disabled (or unsupported for this media type) the - // previous outcome is left untouched rather than being reset to a misleading value. - if metadataAttempted { - if probeErr != nil { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, key, probeErr.Error()) - } else { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, key) - } - } -} - -// refreshMetadataForTypes re-probes ffprobe metadata (and the funscript sidecar flag) for every -// already-known active media row matching selectedTypes (empty means every type), without walking -// the filesystem for brand-new files - that's discovery's job. It's the standalone "Metadata" -// pipeline action: useful for re-reading dimensions/duration (say, after a codec-aware ffprobe -// upgrade) without re-triggering a full rediscovery walk. -// refreshMetadataForTypes does the actual refresh. s.scan is already set to Running by the caller -// (analyzerMetadataStart) before this goroutine was even dispatched - this only clears it when done. -func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) { - log.Printf("analyzer: metadata refresh started (types=%s)", analyzerTypesLabel(selectedTypes)) - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) - defer cancel() - s.scanMu.Lock() - s.scanCancel = cancel - s.scanMu.Unlock() - var runErr error - defer func() { - s.scanMu.Lock() - indexed := s.scan.FilesIndexed - lastError := "" - if runErr != nil { - lastError = runErr.Error() - } - s.scan = scanState{LastError: lastError} - s.scanCancel = nil - s.scanMu.Unlock() - log.Printf("analyzer: metadata refresh finished: %d files processed", indexed) - }() - - query := `SELECT COALESCE(NULLIF(file_path, ''), media_key), LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE` - args := []any{} - if len(selectedTypes) > 0 { - query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)` - args = append(args, mediaTypesList(selectedTypes)) - } - rows, err := s.db.Query(ctx, query, args...) - if err != nil { - log.Printf("analyzer: metadata refresh: failed to load media rows: %v", err) - runErr = fmt.Errorf("failed to load media rows: %w", err) - return - } - type mediaItem struct{ filePath, mediaType string } - items := make([]mediaItem, 0) - for rows.Next() { - var item mediaItem - if rows.Scan(&item.filePath, &item.mediaType) == nil { - items = append(items, item) - } - } - rows.Close() - - s.scanMu.Lock() - s.scan.Total = int64(len(items)) - s.scanMu.Unlock() - - for _, item := range items { - if ctx.Err() != nil { - return - } - s.scanMu.Lock() - s.scan.CurrentType = item.mediaType - s.scan.CurrentFile = item.filePath - s.scan.FilesIndexed++ - s.scanMu.Unlock() - - if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists { - continue - } - - if s.pipelineStageEnabled(ctx, "funscript", "metadata") { - hasFunscript := s.funscriptSidecarExists(ctx, item.filePath) - _, _ = s.db.Exec(ctx, `UPDATE media SET has_funscript=$2 WHERE file_path=$1`, item.filePath, hasFunscript) - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET has_funscript=$2 WHERE file_path=$1`, item.filePath, hasFunscript) - } - - if item.mediaType != "video" && item.mediaType != "audio" && item.mediaType != "image" { - continue - } - if !s.pipelineStageEnabled(ctx, item.mediaType, "metadata") { - continue - } - probe, probeErr := s.carrierNodeProbe(ctx, item.filePath) - if probeErr != nil { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, item.filePath, probeErr.Error()) - continue - } - duration := nullableInt64(probe.DurationMs) - width, height := probe.Width, probe.Height - _, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path=$1`, item.filePath, duration, nullableInt(width), nullableInt(height)) - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, item.filePath) - } -} - -func nullableInt(value int) any { - if value <= 0 { - return nil - } - return value -} - -func nullableInt64(value int64) any { - if value <= 0 { - return nil - } - return value -} - -func hasFunscriptSidecar(filePath string) bool { - base := strings.TrimSuffix(filePath, filepath.Ext(filePath)) - for _, candidate := range []string{base + ".funscript", base + ".json"} { - info, err := os.Stat(candidate) - if err == nil && !info.IsDir() { - return true - } - } - return false -} - -// funscriptSidecarExists is hasFunscriptSidecar for callers without local filesystem access -// (ContentScanner) - it checks for the sidecar on CarrierNode instead of statting a local path. -func (s *Server) funscriptSidecarExists(ctx context.Context, key string) bool { - base := strings.TrimSuffix(key, filepath.Ext(key)) - for _, candidate := range []string{base + ".funscript", base + ".json"} { - if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(candidate)); err == nil && exists { - return true - } - } - return false -} - -func (s *Server) probeWithFFprobe(ctx context.Context, filePath string) (map[string]any, error) { - probeCtx, cancel := context.WithTimeout(ctx, 15*time.Second) - defer cancel() - command := exec.CommandContext(probeCtx, s.cfg.FFprobe, "-v", "error", "-show_entries", "format=duration:stream=width,height", "-of", "json", filePath) - var output, stderr bytes.Buffer - command.Stdout = &output - command.Stderr = &stderr - if err := command.Run(); err != nil { - detail := strings.TrimSpace(stderr.String()) - if len(detail) > 300 { - detail = detail[len(detail)-300:] - } - if detail != "" { - return nil, fmt.Errorf("ffprobe: %s", detail) - } - return nil, err - } - var payload struct { - Format struct { - Duration string `json:"duration"` - } `json:"format"` - Streams []struct { - Width int `json:"width"` - Height int `json:"height"` - } `json:"streams"` - } - if err := json.Unmarshal(output.Bytes(), &payload); err != nil { - return nil, fmt.Errorf("parse ffprobe output: %w", err) - } - result := map[string]any{} - if duration, err := time.ParseDuration(payload.Format.Duration + "s"); err == nil { - result["durationMs"] = duration.Milliseconds() - } - for _, stream := range payload.Streams { - if stream.Width > 0 || stream.Height > 0 { - result["width"], result["height"] = stream.Width, stream.Height - break - } - } - return result, nil -} - -func probeInt(values map[string]any, key string) int { - if value, ok := values[key].(int); ok { - return value - } - return 0 -} - -func (s *Server) modelConfig(w http.ResponseWriter, r *http.Request) { - value := s.settingValue(r.Context(), "analyzer_model_config", "{}") - var parsed any - if json.Unmarshal([]byte(value), &parsed) != nil { - parsed = map[string]any{} - } - writeJSON(w, http.StatusOK, map[string]any{"config": parsed, "options": analyzerModelOptions()}) -} - -func (s *Server) saveModelConfig(w http.ResponseWriter, r *http.Request) { - var payload map[string]any - if err := decodeRequestJSON(r, &payload); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if value, ok := payload["config"]; ok { - payload = map[string]any{"config": value} - } - if err := s.saveSetting(r.Context(), "analyzer_model_config", string(mustJSON(payload))); err != nil { - writeError(w, http.StatusInternalServerError, "model configuration could not be saved") - return - } - log.Printf("analyzer: model configuration saved") - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "config": payload}) -} - -func (s *Server) saveModelOrder(w http.ResponseWriter, r *http.Request) { - var payload map[string]any - if err := decodeRequestJSON(r, &payload); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if err := s.saveSetting(r.Context(), "analyzer_category_order", string(mustJSON(payload))); err != nil { - writeError(w, http.StatusInternalServerError, "model order could not be saved") - return - } - log.Printf("analyzer: model category order saved") - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -type pipelineStageConfig struct { - Thumbnails bool `json:"thumbnails"` - Metadata bool `json:"metadata"` -} - -// Every media type defaults to fully enabled so existing installs (which predate this setting -// entirely) keep behaving exactly as they did before it existed. Thumbnails are only ever -// generated for images and videos (see thumbnailCandidates), so audio and funscript default to -// disabled there rather than advertising a toggle that can't do anything. -func defaultPipelineConfig() map[string]pipelineStageConfig { - return map[string]pipelineStageConfig{ - "image": {Thumbnails: true, Metadata: true}, - "video": {Thumbnails: true, Metadata: true}, - "audio": {Thumbnails: false, Metadata: true}, - "funscript": {Thumbnails: false, Metadata: true}, - } -} - -func loadPipelineConfig(value string) map[string]pipelineStageConfig { - config := defaultPipelineConfig() - if value == "" { - return config - } - var stored map[string]pipelineStageConfig - if json.Unmarshal([]byte(value), &stored) != nil { - return config - } - for mediaType, stage := range stored { - if _, ok := config[mediaType]; ok { - config[mediaType] = stage - } - } - return config -} - -func (s *Server) pipelineConfig(w http.ResponseWriter, r *http.Request) { - config := loadPipelineConfig(s.settingValue(r.Context(), "analyzer_pipeline_config", "")) - writeJSON(w, http.StatusOK, map[string]any{"config": config}) -} - -func (s *Server) savePipelineConfig(w http.ResponseWriter, r *http.Request) { - var payload map[string]any - if err := decodeRequestJSON(r, &payload); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - raw := payload["config"] - if raw == nil { - raw = payload - } - encoded, err := json.Marshal(raw) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid pipeline configuration") - return - } - var partial map[string]pipelineStageConfig - if json.Unmarshal(encoded, &partial) != nil { - writeError(w, http.StatusBadRequest, "invalid pipeline configuration") - return - } - - // Merges onto whatever's already stored (not just today's request) so saving one media - // type's tab - which only ever sends that one type's section - can never clobber the - // other three types' settings back to their defaults. - config := loadPipelineConfig(s.settingValue(r.Context(), "analyzer_pipeline_config", "")) - for mediaType, stage := range partial { - if _, ok := config[mediaType]; ok { - config[mediaType] = stage - } - } - if err := s.saveSetting(r.Context(), "analyzer_pipeline_config", string(mustJSON(config))); err != nil { - writeError(w, http.StatusInternalServerError, "pipeline configuration could not be saved") - return - } - log.Printf("analyzer: pipeline configuration saved") - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "config": config}) -} - -// clearMediaTypePipeline resets one media type's processed state so the next discover/generate -// run redoes it from scratch - it doesn't kick off that run itself, mirroring how "clear" and -// "reprocess" are two separate stages the frontend chains together (clear, then the same -// discover+generate calls the existing "Run pipeline" button already uses). -func (s *Server) clearMediaTypePipeline(w http.ResponseWriter, r *http.Request) { - mediaType := strings.ToLower(chi.URLParam(r, "mediaType")) - if !map[string]bool{"image": true, "video": true, "audio": true, "funscript": true}[mediaType] { - writeError(w, http.StatusBadRequest, "unknown media type") - return - } - - types := map[string]bool{mediaType: true} - stages := map[string]bool{"metadata": true, "thumbnails": true, "analyze": true} - if err := s.startDatabaseClear(clearStageTotal(types, stages)); err != nil { - writeError(w, http.StatusConflict, err.Error()) - return - } - log.Printf("analyzer: database clear started (mediaType=%s, clear & reprocess)", mediaType) - clearCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) - defer cancel() - err := s.clearPipelineData(clearCtx, types, stages) - if err == nil { - // The per-type endpoint is the legacy "clear & reprocess" flow. Keep its historical - // behavior of putting the discovery job back into the queue before the follow-up scan; - // the dashboard endpoint intentionally leaves this discovery status untouched when only - // metadata, thumbnails, or analysis was selected. - _, err = s.db.Exec(clearCtx, `UPDATE media_worker_jobs SET status = 'queued', progress = 0, finished_at = NULL, error_message = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType) - if err != nil { - err = fmt.Errorf("reset %s worker status: %w", mediaType, err) - } - } - s.finishDatabaseClear(err) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return - } - - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType}) -} - -// deleteThumbnailsForType removes both the thumbnail files on disk and their DB rows for every -// media row of one type - shared by the per-type "Clear & reprocess" button above and the -// dashboard's stage-scoped "Clear database" button below, so there's one place that knows how a -// thumbnail actually gets deleted. -func (s *Server) deleteThumbnailsForType(ctx context.Context, mediaType string) error { - rows, err := s.db.Query(ctx, ` - SELECT DISTINCT t.id - FROM thumbnails t - JOIN media m ON t.media_id = m.id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) - WHERE LOWER(COALESCE(m.media_type, '')) = $1`, mediaType) - if err != nil { - return fmt.Errorf("list %s thumbnails: %w", mediaType, err) - } - ids := make([]string, 0) - for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { - rows.Close() - return fmt.Errorf("scan %s thumbnail: %w", mediaType, err) - } - ids = append(ids, id) - } - if err := rows.Err(); err != nil { - rows.Close() - return fmt.Errorf("read %s thumbnails: %w", mediaType, err) - } - rows.Close() - for _, id := range ids { - _ = s.carrierNodeDeleteThumbnail(ctx, id) - } - if len(ids) > 0 { - if _, err := s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = ANY($1::uuid[])`, ids); err != nil { - return fmt.Errorf("delete %s thumbnail records: %w", mediaType, err) - } - } - return nil -} - -// clearFunscriptFlag resets the has_funscript sidecar flag - funscripts aren't their own media -// rows, so clearing them only touches that flag, leaving the parent video/audio file's own -// metadata and thumbnail untouched. -func (s *Server) clearFunscriptFlag(ctx context.Context) error { - if _, err := s.db.Exec(ctx, `UPDATE media SET has_funscript = FALSE WHERE has_funscript = TRUE`); err != nil { - return fmt.Errorf("clear funscript media flags: %w", err) - } - if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET has_funscript = FALSE, status = 'queued', progress = 0, finished_at = NULL, error_message = NULL WHERE has_funscript = TRUE`); err != nil { - return fmt.Errorf("clear funscript job flags: %w", err) - } - return nil -} - -// clearPipelineSelection is the dashboard's "Clear database" action: unlike clearMediaTypePipeline -// (which always clears everything for one type), this clears exactly the selected stages for -// exactly the selected media types - e.g. "reset only thumbnails for images and videos" without -// touching their metadata or AI analysis results. Clearing "discover" is the most destructive -// option: since every other stage's data hangs off the media row itself, forgetting discovery means -// deleting that row entirely (thumbnails, worker job, analysis tasks included) - the file is -// picked back up fresh on the next discovery run. -func (s *Server) clearPipelineSelection(w http.ResponseWriter, r *http.Request) { - var payload struct { - Types []string `json:"types"` - Stages []string `json:"stages"` - } - if err := decodeRequestJSON(r, &payload); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - types := normalizeMediaTypes(payload.Types, false) - if len(types) == 0 { - types = map[string]bool{"image": true, "video": true, "audio": true, "funscript": true} - } - stages := map[string]bool{} - for _, raw := range payload.Stages { - switch strings.ToLower(strings.TrimSpace(raw)) { - case "discover", "metadata", "thumbnails", "analyze": - stages[strings.ToLower(strings.TrimSpace(raw))] = true - } - } - if len(stages) == 0 { - writeError(w, http.StatusBadRequest, "select at least one stage to clear") - return - } - - if err := s.startDatabaseClear(clearStageTotal(types, stages)); err != nil { - writeError(w, http.StatusConflict, err.Error()) - return - } - log.Printf("analyzer: database clear started (types=%s, stages=%s)", analyzerTypesLabel(types), strings.Join(analyzerSelectionList(stages, []string{"discover", "metadata", "thumbnails", "analyze"}), ",")) - clearCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour) - defer cancel() - err := s.clearPipelineData(clearCtx, types, stages) - s.finishDatabaseClear(err) - if err != nil { - writeError(w, http.StatusInternalServerError, err.Error()) - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, "types": mediaTypesList(types), "stages": analyzerSelectionList(stages, []string{"discover", "metadata", "thumbnails", "analyze"}), - "progress": map[string]any{"total": clearStageTotal(types, stages), "completed": clearStageTotal(types, stages)}, - }) -} - -var analyzerMediaTypeOrder = []string{"image", "video", "audio", "funscript"} - -// clearStageTotal counts the concrete reset operations represented in the live status progress -// bar. Discovery subsumes all other resets for a media type because removing its row removes all -// derived pipeline data with it. Funscript is a sidecar flag rather than a standalone media row, -// and therefore only has meaningful discover/metadata work. -func clearStageTotal(types map[string]bool, stages map[string]bool) int { - total := 0 - for _, mediaType := range analyzerMediaTypeOrder { - if !types[mediaType] { - continue - } - if stages["discover"] { - total++ - continue - } - if mediaType == "funscript" { - if stages["metadata"] { - total++ - } - continue - } - for _, stage := range []string{"metadata", "thumbnails", "analyze"} { - if stages[stage] { - total++ - } - } - } - return total -} - -func (s *Server) startDatabaseClear(total int) error { - s.clearMu.Lock() - defer s.clearMu.Unlock() - if s.clear.Running { - return fmt.Errorf("a database clear is already running") - } - s.scanMu.Lock() - scanning := s.scan.Running - s.scanMu.Unlock() - s.thumbnailMu.Lock() - generating := s.thumbnail.Running - s.thumbnailMu.Unlock() - s.analysisMu.Lock() - analyzing := s.analysis.Running - s.analysisMu.Unlock() - if scanning || generating || analyzing { - return fmt.Errorf("analyzer work is already running") - } - now := time.Now().UTC() - s.clear = databaseClearState{Running: true, State: "clearing", Total: total, StartedAt: &now} - return nil -} - -func (s *Server) setDatabaseClearCurrent(mediaType, stage string) { - s.clearMu.Lock() - s.clear.CurrentType = mediaType - s.clear.Current = fmt.Sprintf("%s (%s)", stage, mediaType) - s.clearMu.Unlock() -} - -func (s *Server) completeDatabaseClearStage() { - s.clearMu.Lock() - s.clear.Completed++ - s.clearMu.Unlock() -} - -func (s *Server) finishDatabaseClear(clearErr error) { - now := time.Now().UTC() - s.clearMu.Lock() - defer s.clearMu.Unlock() - s.clear.Running = false - s.clear.Current = "" - s.clear.CurrentType = "" - s.clear.FinishedAt = &now - if clearErr != nil { - s.clear.Failed++ - s.clear.State = "error" - s.clear.LastError = clearErr.Error() - log.Printf("analyzer: database clear failed: %v", clearErr) - } else { - s.clear.State = "completed" - s.clear.LastError = "" - log.Printf("analyzer: database clear finished: %d/%d stages completed", s.clear.Completed, s.clear.Total) - } -} - -func (s *Server) clearPipelineStage(mediaType, stage string, action func() error) error { - s.setDatabaseClearCurrent(mediaType, stage) - if err := action(); err != nil { - return err - } - s.completeDatabaseClearStage() - return nil -} - -// clearPipelineData performs the durable reset for the selected media types and stages. Every -// database operation is checked so a failed statement cannot be reported to the UI as a -// successful clear, and each logical stage updates the live status progress state. -func (s *Server) clearPipelineData(ctx context.Context, types map[string]bool, stages map[string]bool) error { - for _, mediaType := range analyzerMediaTypeOrder { - if !types[mediaType] { - continue - } - if stages["discover"] { - err := s.clearPipelineStage(mediaType, "discover", func() error { - if err := s.deleteThumbnailsForType(ctx, mediaType); err != nil { - return err - } - if mediaType == "funscript" { - return s.clearFunscriptFlag(ctx) - } - if err := s.deleteMediaArtifactsForType(ctx, mediaType); err != nil { - return err - } - if _, err := s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("delete %s analysis tasks: %w", mediaType, err) - } - if _, err := s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("delete %s worker jobs: %w", mediaType, err) - } - if _, err := s.db.Exec(ctx, `DELETE FROM media WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("delete %s media rows: %w", mediaType, err) - } - return nil - }) - if err != nil { - return fmt.Errorf("clear %s discovery: %w", mediaType, err) - } - continue - } - - if mediaType == "funscript" { - if stages["metadata"] { - if err := s.clearPipelineStage(mediaType, "metadata", func() error { return s.clearFunscriptFlag(ctx) }); err != nil { - return fmt.Errorf("clear funscript metadata: %w", err) - } - } - continue - } - - if stages["metadata"] { - err := s.clearPipelineStage(mediaType, "metadata", func() error { - if _, err := s.db.Exec(ctx, `UPDATE media SET duration_ms = NULL, width = NULL, height = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("clear %s metadata: %w", mediaType, err) - } - if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status = 'queued', metadata_error = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("reset %s metadata status: %w", mediaType, err) - } - return nil - }) - if err != nil { - return err - } - } - if stages["thumbnails"] { - err := s.clearPipelineStage(mediaType, "thumbnails", func() error { - if err := s.deleteThumbnailsForType(ctx, mediaType); err != nil { - return err - } - if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status = 'queued', thumbnail_error = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("reset %s thumbnail status: %w", mediaType, err) - } - return nil - }) - if err != nil { - return err - } - } - if stages["analyze"] { - err := s.clearPipelineStage(mediaType, "analyze", func() error { - if _, err := s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("delete %s analysis tasks: %w", mediaType, err) - } - if _, err := s.db.Exec(ctx, `DELETE FROM media_tags WHERE user_id IS NULL AND media_key IN (SELECT media_key FROM media WHERE LOWER(COALESCE(media_type, '')) = $1)`, mediaType); err != nil { - return fmt.Errorf("delete %s AI tags: %w", mediaType, err) - } - if _, err := s.db.Exec(ctx, `UPDATE media SET metadata = metadata - ARRAY['age', 'gender', 'nsfwLabel', 'nsfwScore', 'quality']::text[] WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil { - return fmt.Errorf("clear %s AI metadata: %w", mediaType, err) - } - return nil - }) - if err != nil { - return err - } - } - } - return nil -} - -// Deleting a discovery row must also remove records keyed only by media_key. Several legacy -// tables allow media_id to be NULL, so relying on foreign-key cascades alone leaves orphaned -// tags/history behind after a clear. -func (s *Server) deleteMediaArtifactsForType(ctx context.Context, mediaType string) error { - for _, table := range []string{"media_tag_votes", "media_tags", "media_stats", "media_view_sessions", "media_metrics", "playlist_items"} { - query := fmt.Sprintf(`DELETE FROM %s WHERE media_key IN (SELECT media_key FROM media WHERE LOWER(COALESCE(media_type, '')) = $1)`, table) - if _, err := s.db.Exec(ctx, query, mediaType); err != nil { - return fmt.Errorf("delete %s records: %w", table, err) - } - } - return nil -} - -// Read fresh on every scan/generation run (rather than cached) so a save takes effect on the -// very next run without requiring a server restart. -func (s *Server) pipelineStageEnabled(ctx context.Context, mediaType, stage string) bool { - config := loadPipelineConfig(s.settingValue(ctx, "analyzer_pipeline_config", "")) - section, ok := config[mediaType] - if !ok { - return true - } - switch stage { - case "thumbnails": - return section.Thumbnails - case "metadata": - return section.Metadata - default: - return true - } -} - -// analyzerScheduleTools are the only actions runAnalyzerScheduledRun (see analyzer_schedule.go) -// knows how to execute - one per real pipeline stage, matching the dashboard's own action list. -var analyzerScheduleTools = map[string]bool{ - "discover": true, - "metadata": true, - "thumbnails": true, - "analyze": true, - "cleanup": true, -} - -func (s *Server) analyzerSchedules(w http.ResponseWriter, r *http.Request) { - s.workflowSchedules(w, r) -} - -// createAnalyzerSchedule validates the tool against the five real analyzer actions before -// delegating to the shared workflow_schedules insert - createWorkflowSchedule accepts any tool -// string as-is (it's also used by the Tools app for converter/downloader/generator schedules), so -// this is what stops an analyzer schedule from being created for an action nothing can ever run. -func (s *Server) createAnalyzerSchedule(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - var probe struct { - Tool string `json:"tool"` - } - _ = json.Unmarshal(body, &probe) - if !analyzerScheduleTools[strings.ToLower(strings.TrimSpace(probe.Tool))] { - writeError(w, http.StatusBadRequest, "unsupported schedule action") - return - } - log.Printf("analyzer: automation schedule created (tool=%s)", probe.Tool) - r.Body = io.NopCloser(bytes.NewReader(body)) - s.createWorkflowSchedule(w, r) -} - -// runAnalyzerSchedule is the manual "Run now" trigger, dispatching through the exact same -// scan/thumbnail/analysis busy-state guards the dashboard buttons use (see -// startAnalyzerScheduledRun) rather than the generic converter/downloader/generator job queue -// runWorkflowSchedule uses - that queue's executeWorkflow has no case for any analyzer action. -func (s *Server) runAnalyzerSchedule(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - var tool string - var settings []byte - if err := s.db.QueryRow(r.Context(), `SELECT tool, settings FROM workflow_schedules WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName).Scan(&tool, &settings); err != nil { - writeError(w, http.StatusNotFound, "schedule not found") - return - } - var parsedSettings struct { - Types []string `json:"types"` - } - _ = json.Unmarshal(settings, &parsedSettings) - types := normalizeMediaTypes(parsedSettings.Types, true) - - started, err := s.startAnalyzerScheduledRun(tool, types) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - if !started { - writeError(w, http.StatusConflict, "that stage is already running") - return - } - log.Printf("analyzer: automation schedule %s run manually (tool=%s)", id, tool) - _, _ = s.db.Exec(r.Context(), ` - UPDATE workflow_schedules - SET last_run_at = NOW(), last_status = 'started', next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW() - WHERE id = $1`, id) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "started": true}) -} - -func (s *Server) deleteAnalyzerSchedule(w http.ResponseWriter, r *http.Request) { - log.Printf("analyzer: automation schedule %s deleted", chi.URLParam(r, "id")) - s.deleteWorkflowSchedule(w, r) -} - -func (s *Server) conversionSettings(w http.ResponseWriter, r *http.Request) { - value := s.settingValue(r.Context(), "conversion_settings", "{}") - var parsed any - _ = json.Unmarshal([]byte(value), &parsed) - writeJSON(w, http.StatusOK, map[string]any{"settings": parsed}) -} - -func (s *Server) saveConversionSettings(w http.ResponseWriter, r *http.Request) { - var payload map[string]any - if err := decodeRequestJSON(r, &payload); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if err := s.saveSetting(r.Context(), "conversion_settings", string(mustJSON(payload))); err != nil { - writeError(w, http.StatusInternalServerError, "conversion settings could not be saved") - return - } - log.Printf("analyzer: conversion settings saved") - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func supportedMediaPath(value string) bool { - switch strings.ToLower(filepath.Ext(value)) { - case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg", ".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".mpg", ".mpeg", ".ts", ".flv", ".wmv", ".3gp", ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", ".wma": - return true - default: - return false - } -} - -func analyzerModelOptions() map[string]any { - return map[string]any{ - "image": []string{"nsfwjs", "wdtagger", "faceapi", "onnxage", "florence2", "laplacian"}, - "video": []string{"nsfwjs", "wdtagger", "florence2"}, - "audio": []string{"whisper", "clap", "florence2"}, - // No model in this codebase analyzes funscript motion data yet - "Disabled" is the - // only real option, exposed for symmetry with the other three media types. - "funscript": []string{}, - } -} - -func (s *Server) settingValue(ctx context.Context, key, fallback string) string { - var value string - if err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" { - return fallback - } - return value -} - -func (s *Server) settingBool(ctx context.Context, key string, fallback bool) bool { - value := strings.ToLower(strings.TrimSpace(s.settingValue(ctx, key, ""))) - if value == "" { - return fallback - } - return value == "1" || value == "true" || value == "yes" || value == "on" -} - -func (s *Server) saveSetting(ctx context.Context, key, value string) error { - _, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value) - return err -} diff --git a/shared/media-backend/internal/server/analyzer_ai.go b/shared/media-backend/internal/server/analyzer_ai.go deleted file mode 100644 index bf779c4..0000000 --- a/shared/media-backend/internal/server/analyzer_ai.go +++ /dev/null @@ -1,710 +0,0 @@ -package server - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "image" - _ "image/gif" - _ "image/jpeg" - _ "image/png" - "io" - "log" - "net/http" - "os" - "os/exec" - "path/filepath" - "strings" - "time" -) - -// analysisState tracks the currently-running AI analysis pass, mirroring thumbnailGenerationState. -type analysisState struct { - Running bool - State string - Total int - Completed int - Failed int - Current string - CurrentType string - StartedAt *time.Time - FinishedAt *time.Time - LastError string -} - -// analyzerTasksByMediaType mirrors WebUI/src/lib/features/MediaTypePipeline.svelte's stagesForType - -// the set of AI tasks that exist for each media type. -var analyzerTasksByMediaType = map[string][]string{ - "image": {"tags", "title", "description", "age", "gender", "nsfw"}, - "video": {"tags"}, - "audio": {"tags"}, - "funscript": {}, -} - -func (s *Server) analyzerAnalyzeStatus(w http.ResponseWriter, r *http.Request) { - s.analysisMu.Lock() - state := s.analysis - s.analysisMu.Unlock() - writeJSON(w, http.StatusOK, map[string]any{ - "ok": true, - "status": map[string]any{ - "running": state.Running, - "state": firstNonEmpty(state.State, "idle"), - "total": state.Total, - "completed": state.Completed, - "failed": state.Failed, - "current": state.Current, - "startedAt": state.StartedAt, - "finishedAt": state.FinishedAt, - "lastError": state.LastError, - }, - }) -} - -func (s *Server) analyzerAnalyzeStart(w http.ResponseWriter, r *http.Request) { - selected := parseMediaTypesPayload(r, false) - s.analysisMu.Lock() - if s.analysis.Running { - s.analysisMu.Unlock() - writeError(w, http.StatusConflict, "AI analysis is already running") - return - } - ctx, cancel := context.WithCancel(context.Background()) - now := time.Now().UTC() - s.analysis = analysisState{Running: true, State: "running", StartedAt: &now} - s.analysisCancel = cancel - s.analysisMu.Unlock() - - go s.runAiAnalysis(ctx, mediaTypesList(selected)) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"}) -} - -func (s *Server) analyzerAnalyzeStop(w http.ResponseWriter, r *http.Request) { - s.analysisMu.Lock() - cancel := s.analysisCancel - running := s.analysis.Running - s.analysisMu.Unlock() - if !running || cancel == nil { - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"}) - return - } - log.Printf("analyzer: AI analysis stop requested") - cancel() - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"}) -} - -// runAiAnalysis queues any AI task that isn't already completed under the currently-configured -// model, then works through everything queued. mediaTypeFilters scopes both stages to a subset of -// media types (empty means every type) - used both by the dashboard's media-type selector and by -// the per-media-type retry-errors action (which passes a single-element list) so a scoped run -// never kicks off a full-library pass. -func (s *Server) runAiAnalysis(ctx context.Context, mediaTypeFilters []string) { - if err := s.syncAnalysisTasks(ctx, mediaTypeFilters); err != nil && ctx.Err() == nil { - log.Printf("analyzer: AI analysis: failed to sync tasks: %v", err) - s.finishAnalysis(err) - return - } - s.processAnalysisTasks(ctx, mediaTypeFilters) -} - -type modelStageConfig struct { - Primary string - Enabled bool -} - -// parseModelStageConfig mirrors MediaTypePipeline.svelte's own leniency: older saves stored the -// model as a bare string rather than {primary, fallback, enabled}. -func parseModelStageConfig(raw json.RawMessage) modelStageConfig { - var asString string - if json.Unmarshal(raw, &asString) == nil { - if asString == "" || asString == "disabled" { - return modelStageConfig{} - } - return modelStageConfig{Primary: asString, Enabled: true} - } - var asObject struct { - Primary string `json:"primary"` - Enabled bool `json:"enabled"` - } - if json.Unmarshal(raw, &asObject) == nil { - return modelStageConfig{Primary: asObject.Primary, Enabled: asObject.Enabled} - } - return modelStageConfig{} -} - -// enabledAnalysisTasks reads the analyzer_model_config setting (the same one the model-config -// endpoints already read/write) and returns, per media type, the task->model pairs the user has -// actually turned on. -func (s *Server) enabledAnalysisTasks(ctx context.Context, mediaTypeFilters []string) map[string]map[string]string { - value := s.settingValue(ctx, "analyzer_model_config", "{}") - var wrapper struct { - Config map[string]map[string]json.RawMessage `json:"config"` - } - if json.Unmarshal([]byte(value), &wrapper) != nil { - return nil - } - filterSet := make(map[string]bool, len(mediaTypeFilters)) - for _, mediaType := range mediaTypeFilters { - filterSet[mediaType] = true - } - result := make(map[string]map[string]string) - for mediaType, tasks := range analyzerTasksByMediaType { - if len(filterSet) > 0 && !filterSet[mediaType] { - continue - } - section, ok := wrapper.Config[mediaType] - if !ok { - continue - } - enabled := make(map[string]string) - for _, task := range tasks { - raw, ok := section[task] - if !ok { - continue - } - stage := parseModelStageConfig(raw) - if stage.Enabled && stage.Primary != "" && stage.Primary != "disabled" { - enabled[task] = stage.Primary - } - } - if len(enabled) > 0 { - result[mediaType] = enabled - } - } - return result -} - -// syncAnalysisTasks upserts one media_analysis_tasks row per (active media file, enabled task). -// A file whose task previously errored, or whose configured model has since changed, is put back -// on the queue - mirroring how thumbnails/metadata already retry automatically on every run -// rather than requiring the dedicated retry-errors action. -func (s *Server) syncAnalysisTasks(ctx context.Context, mediaTypeFilters []string) error { - tasksByType := s.enabledAnalysisTasks(ctx, mediaTypeFilters) - if len(tasksByType) == 0 { - return nil - } - - query := `SELECT media_key, LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE` - args := []any{} - if len(mediaTypeFilters) > 0 { - query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)` - args = append(args, mediaTypeFilters) - } - rows, err := s.db.Query(ctx, query, args...) - if err != nil { - return err - } - type mediaItem struct{ key, mediaType string } - items := make([]mediaItem, 0) - for rows.Next() { - var item mediaItem - if rows.Scan(&item.key, &item.mediaType) == nil { - items = append(items, item) - } - } - rows.Close() - if err := rows.Err(); err != nil { - return err - } - - for _, item := range items { - tasks, ok := tasksByType[item.mediaType] - if !ok { - continue - } - for task, model := range tasks { - if ctx.Err() != nil { - return nil - } - _, _ = s.db.Exec(ctx, ` - INSERT INTO media_analysis_tasks (media_key, media_type, task, model, status) - VALUES ($1,$2,$3,$4,'queued') - ON CONFLICT (media_key, task) DO UPDATE SET - model = EXCLUDED.model, - status = 'queued', - error_message = NULL, - updated_at = NOW() - WHERE media_analysis_tasks.status = 'error' - OR (media_analysis_tasks.status = 'completed' AND media_analysis_tasks.model <> EXCLUDED.model)`, - item.key, item.mediaType, task, model) - } - } - return nil -} - -type pendingAnalysisTask struct { - id int64 - mediaKey, mediaType string - task, model, filePath string -} - -func (s *Server) processAnalysisTasks(ctx context.Context, mediaTypeFilters []string) { - query := ` - SELECT t.id, t.media_key, t.media_type, t.task, t.model, COALESCE(NULLIF(m.file_path, ''), m.media_key) - FROM media_analysis_tasks t - JOIN media m ON m.media_key = t.media_key - WHERE t.status = 'queued' AND m.active = TRUE` - args := []any{} - if len(mediaTypeFilters) > 0 { - query += ` AND t.media_type = ANY($1)` - args = append(args, mediaTypeFilters) - } - query += ` ORDER BY t.id ASC` - - rows, err := s.db.Query(ctx, query, args...) - if err != nil { - if ctx.Err() != nil { - s.finishAnalysis(nil) - } else { - log.Printf("analyzer: AI analysis: failed to load queued tasks: %v", err) - s.finishAnalysis(err) - } - return - } - items := make([]pendingAnalysisTask, 0) - for rows.Next() { - var item pendingAnalysisTask - if rows.Scan(&item.id, &item.mediaKey, &item.mediaType, &item.task, &item.model, &item.filePath) == nil { - items = append(items, item) - } - } - rows.Close() - - log.Printf("analyzer: AI analysis started: %d tasks queued", len(items)) - - s.analysisMu.Lock() - s.analysis.Total = len(items) - s.analysisMu.Unlock() - - for _, item := range items { - if ctx.Err() != nil { - s.finishAnalysis(nil) - return - } - - s.analysisMu.Lock() - s.analysis.Current = item.filePath - s.analysis.CurrentType = item.mediaType - s.analysisMu.Unlock() - - _, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='processing', started_at=NOW() WHERE id=$1`, item.id) - - result, runErr := s.runAnalysisTask(ctx, item) - - s.analysisMu.Lock() - if runErr != nil { - s.analysis.Failed++ - s.analysis.LastError = runErr.Error() - } else { - s.analysis.Completed++ - } - s.analysisMu.Unlock() - - if runErr != nil { - _, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='error', error_message=$2, finished_at=NOW() WHERE id=$1`, item.id, runErr.Error()) - continue - } - _, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='completed', error_message=NULL, result=$2, finished_at=NOW() WHERE id=$1`, item.id, mustJSON(result)) - s.applyAnalysisResult(ctx, item.mediaKey, result) - } - s.finishAnalysis(nil) -} - -func (s *Server) finishAnalysis(runErr error) { - now := time.Now().UTC() - s.analysisMu.Lock() - defer s.analysisMu.Unlock() - s.analysis.Running = false - s.analysisCancel = nil - s.analysis.Current = "" - s.analysis.CurrentType = "" - s.analysis.FinishedAt = &now - if runErr != nil { - s.analysis.State = "error" - s.analysis.LastError = runErr.Error() - } else if s.analysis.Completed+s.analysis.Failed < s.analysis.Total { - s.analysis.State = "stopped" - } else if s.analysis.Failed > 0 { - s.analysis.State = "completed_with_errors" - } else { - s.analysis.State = "completed" - s.analysis.LastError = "" - } - log.Printf("analyzer: AI analysis finished: %d/%d done, %d failed, state=%s", s.analysis.Completed, s.analysis.Total, s.analysis.Failed, s.analysis.State) - if s.analysis.LastError != "" { - log.Printf("analyzer: AI analysis last error: %s", s.analysis.LastError) - } -} - -// runAnalysisTask dispatches one (file, task, model) unit of work. Every model produces a fixed -// output shape regardless of which task slot it was assigned to in the UI (the model dropdown -// isn't filtered per task), so storage in applyAnalysisResult is driven by what a model actually -// returns, not by the task key it ran under. -func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask) (map[string]any, error) { - sourcePath := filepath.ToSlash(item.filePath) - - // Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather - // than always fetching the whole video across the wire to CarrierNode just to grab one frame. - if item.mediaType == "video" && item.model != "laplacian" { - framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath) - if err != nil { - return nil, err - } - if cleanup != nil { - defer cleanup() - } - return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath) - } - - scratchPath, cleanup, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath)) - if err != nil { - return nil, fmt.Errorf("fetch %s: %w", item.filePath, err) - } - defer cleanup() - - if item.model == "laplacian" { - if item.mediaType != "image" { - return nil, fmt.Errorf("laplacian quality scoring only supports images") - } - variance, err := computeLaplacianVariance(scratchPath) - if err != nil { - return nil, err - } - return map[string]any{"quality": map[string]any{"laplacianVariance": variance}}, nil - } - - return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, scratchPath) -} - -// videoAnalysisFrame reuses an already-generated thumbnail as the representative frame for -// image-shaped models when one exists, fetching the source video and extracting a temporary -// frame otherwise so AI analysis doesn't depend on the thumbnails stage being enabled. Both paths -// return a scratch file the AnalyzerModels sidecar (co-located in this container - see -// callAnalyzerModelsService) can read directly. -func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) { - var thumbnailID string - if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil { - if scratchPath, cleanup, fetchErr := s.fetchCarrierNodeToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil { - return scratchPath, cleanup, nil - } - } - - videoScratch, cleanupVideo, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath)) - if err != nil { - return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err) - } - defer cleanupVideo() - - temporary, err := os.CreateTemp("", "analysis-frame-*.jpg") - if err != nil { - return "", nil, fmt.Errorf("create temporary frame: %w", err) - } - temporaryPath := temporary.Name() - if err := temporary.Close(); err != nil { - _ = os.Remove(temporaryPath) - return "", nil, err - } - - frameCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) - defer cancel() - args := []string{"-hide_banner", "-loglevel", "error", "-y", "-ss", "0", "-i", videoScratch, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath} - command := exec.CommandContext(frameCtx, s.cfg.FFmpeg, args...) - var stderr bytes.Buffer - command.Stderr = &stderr - if err := command.Run(); err != nil { - _ = os.Remove(temporaryPath) - detail := strings.TrimSpace(stderr.String()) - if len(detail) > 300 { - detail = detail[len(detail)-300:] - } - if detail != "" { - return "", nil, fmt.Errorf("ffmpeg: %s", detail) - } - return "", nil, err - } - return temporaryPath, func() { _ = os.Remove(temporaryPath) }, nil -} - -type analysisSidecarRequest struct { - Task string `json:"task"` - Model string `json:"model"` - Path string `json:"path"` -} - -// callAnalyzerModelsService calls the AnalyzerModels sidecar (a separate process in the same -// container, not baked into this binary - see ANALYZER_MODELS_URL and ContentScanner/Dockerfile), -// the same way executeGeneration already calls out to ComfyUI for image generation. Video frames -// are analyzed through the image endpoint since by the time this runs the video has already been -// reduced to a still frame. -func (s *Server) callAnalyzerModelsService(ctx context.Context, mediaType, task, model, path string) (map[string]any, error) { - endpoint, ok := map[string]string{"image": "/analyze/image", "video": "/analyze/image", "audio": "/analyze/audio"}[mediaType] - if !ok { - return nil, fmt.Errorf("unsupported media type for AI analysis: %s", mediaType) - } - body, err := json.Marshal(analysisSidecarRequest{Task: task, Model: model, Path: path}) - if err != nil { - return nil, err - } - // Some models (florence2 especially) run several seconds per file on CPU - generous timeout - // so a slow model doesn't get mistaken for a hung one. - requestCtx, cancel := context.WithTimeout(ctx, 5*time.Minute) - defer cancel() - request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, s.cfg.AnalyzerModelsURL+endpoint, bytes.NewReader(body)) - if err != nil { - return nil, err - } - request.Header.Set("Content-Type", "application/json") - response, err := http.DefaultClient.Do(request) - if err != nil { - return nil, fmt.Errorf("analyzer models service request failed: %w", err) - } - defer response.Body.Close() - var payload struct { - Result map[string]any `json:"result"` - // FastAPI's HTTPException serializes as {"detail": "..."} , not {"error": "..."}. - Detail string `json:"detail"` - } - if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil { - return nil, fmt.Errorf("invalid analyzer models response: %w", err) - } - if response.StatusCode >= 300 { - if payload.Detail == "" { - payload.Detail = response.Status - } - return nil, fmt.Errorf("analyzer models service: %s", payload.Detail) - } - return payload.Result, nil -} - -// applyAnalysisResult writes a completed task's output into the tables the rest of the app -// actually reads, not just the analyzer's own history - tags into media_tags (user_id NULL marks -// them as AI-attributed), title/description onto media (never overwriting a value that's already -// set, whether user-edited or from an earlier analysis run), everything else into media.metadata. -func (s *Server) applyAnalysisResult(ctx context.Context, mediaKey string, result map[string]any) { - if result == nil { - return - } - if tagsRaw, ok := result["tags"].([]any); ok { - for _, tagValue := range tagsRaw { - tag, ok := tagValue.(string) - tag = strings.ToLower(strings.TrimSpace(tag)) - if !ok || tag == "" { - continue - } - _, _ = s.db.Exec(ctx, ` - INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, NULL) - ON CONFLICT (media_key, tag) WHERE user_id IS NULL DO NOTHING`, mediaKey, tag) - } - } - - title, _ := result["title"].(string) - description, _ := result["description"].(string) - if strings.TrimSpace(title) != "" || strings.TrimSpace(description) != "" { - _, _ = s.db.Exec(ctx, ` - UPDATE media SET - title = COALESCE(NULLIF(media.title, ''), NULLIF($2, '')), - description = COALESCE(NULLIF(media.description, ''), NULLIF($3, '')) - WHERE media_key = $1`, mediaKey, title, description) - } - - extra := map[string]any{} - for _, key := range []string{"age", "gender", "nsfwLabel", "nsfwScore", "quality"} { - if value, ok := result[key]; ok { - extra[key] = value - } - } - if len(extra) > 0 { - _, _ = s.db.Exec(ctx, `UPDATE media SET metadata = metadata || $2::jsonb WHERE media_key = $1`, mediaKey, mustJSON(extra)) - } -} - -// computeLaplacianVariance measures image sharpness/blur without any external model: convert to -// grayscale, convolve with the standard 4-neighbor Laplacian kernel, and take the variance of the -// result - a low variance means a flat/blurry image, a high variance means a lot of sharp edges. -// Only the image formats Go's standard library can decode (JPEG/PNG/GIF) are supported; anything -// else surfaces as a normal per-file error rather than silently skipping. -func computeLaplacianVariance(fullPath string) (float64, error) { - file, err := os.Open(fullPath) - if err != nil { - return 0, err - } - defer file.Close() - - img, _, err := image.Decode(file) - if err != nil { - return 0, fmt.Errorf("decode image: %w", err) - } - bounds := img.Bounds() - width, height := bounds.Dx(), bounds.Dy() - if width < 3 || height < 3 { - return 0, fmt.Errorf("image too small for quality analysis") - } - - gray := make([]float64, width*height) - for y := 0; y < height; y++ { - for x := 0; x < width; x++ { - r, g, b, _ := img.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA() - gray[y*width+x] = 0.299*float64(r>>8) + 0.587*float64(g>>8) + 0.114*float64(b>>8) - } - } - at := func(x, y int) float64 { - if x < 0 { - x = 0 - } else if x >= width { - x = width - 1 - } - if y < 0 { - y = 0 - } else if y >= height { - y = height - 1 - } - return gray[y*width+x] - } - - var sum, sumSquares float64 - count := float64(width * height) - for y := 0; y < height; y++ { - for x := 0; x < width; x++ { - laplacian := at(x-1, y) + at(x+1, y) + at(x, y-1) + at(x, y+1) - 4*at(x, y) - sum += laplacian - sumSquares += laplacian * laplacian - } - } - mean := sum / count - return sumSquares/count - mean*mean, nil -} - -// retryPipelineErrors resets one media type's failed items for one stage back onto the queue and -// immediately re-runs that stage for just that type, rather than requiring a full "Run pipeline". -func (s *Server) retryPipelineErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) { - ctx := r.Context() - log.Printf("analyzer: retry errors requested (mediaType=%s, stage=%s)", mediaType, stage) - switch stage { - case "metadata": - go s.retryMetadataErrors(mediaType) - case "thumbnails": - go s.retryThumbnailErrors(mediaType) - case "analyze": - go s.runAiAnalysis(context.Background(), []string{mediaType}) - default: - writeError(w, http.StatusBadRequest, "unknown pipeline stage") - return - } - _ = ctx - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "started": true}) -} - -// mediaTypeErrorCondition returns a media_worker_jobs WHERE fragment for one media type, and the -// single arg it needs (if any) - the same "funscript" special-case analyzerHistory and -// parseMediaTypesPayload use, since it isn't a real media_type value on that table, just the -// has_funscript flag on a video/audio row. -func mediaTypeErrorCondition(mediaType string) (string, []any) { - if mediaType == "funscript" { - return "has_funscript = TRUE", nil - } - return "LOWER(COALESCE(media_type, '')) = $1", []any{mediaType} -} - -type pipelineStageError struct { - FilePath string `json:"filePath"` - Error string `json:"error"` -} - -// pipelineStageErrors returns the most recent error messages recorded for one media type's one -// pipeline stage, so the "Show errors" button next to Retry (see PipelineFlowDiagram.svelte) can -// display what's actually failing instead of just the count already shown in the breakdown. -func (s *Server) pipelineStageErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) { - ctx := r.Context() - limit := optionalInt(r.URL.Query().Get("limit"), 20, 1, 100) - items := make([]pipelineStageError, 0) - - var query string - var args []any - switch stage { - case "metadata": - condition, condArgs := mediaTypeErrorCondition(mediaType) - query = fmt.Sprintf(`SELECT file_path, COALESCE(metadata_error, '') FROM media_worker_jobs - WHERE metadata_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1) - args = append(condArgs, limit) - case "thumbnails": - condition, condArgs := mediaTypeErrorCondition(mediaType) - query = fmt.Sprintf(`SELECT file_path, COALESCE(thumbnail_error, '') FROM media_worker_jobs - WHERE thumbnail_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1) - args = append(condArgs, limit) - case "analyze": - query = `SELECT media_key, COALESCE(error_message, '') FROM media_analysis_tasks - WHERE status = 'error' AND LOWER(media_type) = $1 ORDER BY finished_at DESC NULLS LAST LIMIT $2` - args = []any{mediaType, limit} - default: - writeError(w, http.StatusBadRequest, "unknown pipeline stage") - return - } - - rows, err := s.db.Query(ctx, query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "pipeline errors unavailable") - return - } - defer rows.Close() - for rows.Next() { - var item pipelineStageError - if rows.Scan(&item.FilePath, &item.Error) == nil && item.Error != "" { - items = append(items, item) - } - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "errors": items}) -} - -func (s *Server) retryMetadataErrors(mediaType string) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) - defer cancel() - rows, err := s.db.Query(ctx, ` - SELECT file_path FROM media_worker_jobs - WHERE LOWER(COALESCE(media_type, '')) = $1 AND metadata_status = 'error'`, mediaType) - if err != nil { - return - } - filePaths := make([]string, 0) - for rows.Next() { - var filePath string - if rows.Scan(&filePath) == nil { - filePaths = append(filePaths, filePath) - } - } - rows.Close() - - for _, filePath := range filePaths { - if ctx.Err() != nil { - return - } - if probe, probeErr := s.carrierNodeProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil { - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error()) - } else { - duration := nullableInt64(probe.DurationMs) - width, height := probe.Width, probe.Height - _, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path = $1`, filePath, duration, nullableInt(width), nullableInt(height)) - _, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, filePath) - } - } -} - -func (s *Server) retryThumbnailErrors(mediaType string) { - s.thumbnailMu.Lock() - if s.thumbnail.Running { - s.thumbnailMu.Unlock() - return - } - ctx, cancel := context.WithCancel(context.Background()) - now := time.Now().UTC() - s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now} - s.thumbnailCancel = cancel - s.thumbnailMu.Unlock() - - candidates, err := s.thumbnailCandidatesWithErrors(ctx, mediaType) - if err != nil { - s.finishThumbnailGeneration(err) - return - } - s.runThumbnailCandidates(ctx, candidates) -} diff --git a/shared/media-backend/internal/server/analyzer_schedule.go b/shared/media-backend/internal/server/analyzer_schedule.go deleted file mode 100644 index 4e4b7cb..0000000 --- a/shared/media-backend/internal/server/analyzer_schedule.go +++ /dev/null @@ -1,139 +0,0 @@ -package server - -import ( - "context" - "encoding/json" - "fmt" - "log" - "time" -) - -// runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's -// deliberately a simple poll loop rather than a precise cron: schedules only ever run on -// minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler -// than tracking individual timers per schedule. -func (s *Server) runAnalyzerScheduler(ctx context.Context) { - ticker := time.NewTicker(30 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - s.runDueAnalyzerSchedules(ctx) - } - } -} - -func (s *Server) runDueAnalyzerSchedules(ctx context.Context) { - rows, err := s.db.Query(ctx, ` - SELECT id, tool, settings - FROM workflow_schedules - WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName) - if err != nil { - log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err) - return - } - type due struct { - id, tool string - settings []byte - } - items := make([]due, 0) - for rows.Next() { - var item due - if rows.Scan(&item.id, &item.tool, &item.settings) == nil { - items = append(items, item) - } - } - rows.Close() - - for _, item := range items { - if ctx.Err() != nil { - return - } - var parsed struct { - Types []string `json:"types"` - } - _ = json.Unmarshal(item.settings, &parsed) - types := normalizeMediaTypes(parsed.Types, true) - - status := "started" - started, err := s.startAnalyzerScheduledRun(item.tool, types) - switch { - case err != nil: - status = "error: " + err.Error() - case !started: - status = "skipped: busy" - } - log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status) - // Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule - // doesn't get retried on every single tick - it just waits for its normal interval instead. - _, _ = s.db.Exec(ctx, ` - UPDATE workflow_schedules - SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW() - WHERE id = $1`, item.id, status) - } -} - -// startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding -// manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same -// background worker function used everywhere else. "started" is false (not an error) when that -// slot was already busy - the schedule just waits for its next tick rather than queuing up or -// failing loudly, mirroring how the dashboard's own buttons behave under the same condition. -func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) { - now := time.Now().UTC() - switch tool { - case "discover": - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - return false, nil - } - s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now} - s.scanMu.Unlock() - go s.scanMediaFiles(types) - case "metadata": - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - return false, nil - } - s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now} - s.scanMu.Unlock() - go s.refreshMetadataForTypes(types) - case "cleanup": - s.scanMu.Lock() - if s.scan.Running { - s.scanMu.Unlock() - return false, nil - } - s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now} - s.scanMu.Unlock() - go s.cleanupStaleMedia() - case "thumbnails": - s.thumbnailMu.Lock() - if s.thumbnail.Running { - s.thumbnailMu.Unlock() - return false, nil - } - runCtx, cancel := context.WithCancel(context.Background()) - s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now} - s.thumbnailCancel = cancel - s.thumbnailMu.Unlock() - go s.generateThumbnails(runCtx, types) - case "analyze": - s.analysisMu.Lock() - if s.analysis.Running { - s.analysisMu.Unlock() - return false, nil - } - runCtx, cancel := context.WithCancel(context.Background()) - s.analysis = analysisState{Running: true, State: "running", StartedAt: &now} - s.analysisCancel = cancel - s.analysisMu.Unlock() - go s.runAiAnalysis(runCtx, mediaTypesList(types)) - default: - return false, fmt.Errorf("unsupported schedule action: %s", tool) - } - return true, nil -} diff --git a/shared/media-backend/internal/server/carriernode_client.go b/shared/media-backend/internal/server/carriernode_client.go deleted file mode 100644 index 200bdbb..0000000 --- a/shared/media-backend/internal/server/carriernode_client.go +++ /dev/null @@ -1,331 +0,0 @@ -package server - -// CarrierNode client: every non-CarrierNode service serves and stores media by calling CarrierNode's -// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/ -// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. CarrierNode's own handlers keep using those -// roots directly (see media.go, admin_storage.go) - this file is never called from CarrierNode's -// own code path. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" -) - -// carrierNodeHTTPClient has no blanket timeout since it streams large media files; callers bound -// individual calls with a context deadline instead. -var carrierNodeHTTPClient = &http.Client{} - -func (s *Server) carrierNodeClient() *http.Client { - return carrierNodeHTTPClient -} - -// carrierNodeBaseURL is configured in ProjectConfigurator and stored in the settings table (key -// "carriernode_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for -// every project's connection URL) - not a static env var, so a change in ProjectConfigurator -// takes effect on every service's very next request without a restart. CARRIERNODE_URL is only the -// bootstrap fallback before that setting has ever been saved. -func (s *Server) carrierNodeBaseURL(ctx context.Context) string { - return strings.TrimRight(s.settingValue(ctx, "carriernode_url", s.cfg.CarrierNodeURL), "/") -} - -func (s *Server) newCarrierNodeRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { - request, err := http.NewRequestWithContext(ctx, method, s.carrierNodeBaseURL(ctx)+path, body) - if err != nil { - return nil, err - } - if s.cfg.InternalServiceSecret != "" { - request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret) - } - return request, nil -} - -var carrierNodeForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} -var carrierNodeForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} - -// proxyCarrierNode streams a CarrierNode response straight through to the original client, preserving -// range/conditional-request semantics so video scrubbing keeps working without reimplementing -// http.ServeContent on this side. -func (s *Server) proxyCarrierNode(w http.ResponseWriter, r *http.Request, carrierNodePath string) { - request, err := s.newCarrierNodeRequest(r.Context(), r.Method, carrierNodePath, nil) - if err != nil { - writeError(w, http.StatusBadGateway, "media service unavailable") - return - } - for _, header := range carrierNodeForwardRequestHeaders { - if value := r.Header.Get(header); value != "" { - request.Header.Set(header, value) - } - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - writeError(w, http.StatusBadGateway, "media service unavailable") - return - } - defer response.Body.Close() - for _, header := range carrierNodeForwardResponseHeaders { - if value := response.Header.Get(header); value != "" { - w.Header().Set(header, value) - } - } - w.WriteHeader(response.StatusCode) - if r.Method != http.MethodHead { - _, _ = io.Copy(w, response.Body) - } -} - -// probeCarrierNode checks whether a CarrierNode-served path exists without fetching its bytes. -// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx -// problems are surfaced as errors. -func (s *Server) probeCarrierNode(ctx context.Context, carrierNodePath string) (bool, int64, time.Time, error) { - request, err := s.newCarrierNodeRequest(ctx, http.MethodHead, carrierNodePath, nil) - if err != nil { - return false, 0, time.Time{}, err - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return false, 0, time.Time{}, err - } - defer response.Body.Close() - if response.StatusCode == http.StatusNotFound { - return false, 0, time.Time{}, nil - } - if response.StatusCode >= 400 { - return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status) - } - size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64) - modTime, _ := http.ParseTime(response.Header.Get("Last-Modified")) - return true, size, modTime, nil -} - -// fetchCarrierNodeToScratch downloads a CarrierNode-served path into an ephemeral temp file for local -// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the -// returned cleanup once done; it removes the scratch file unconditionally. -func (s *Server) fetchCarrierNodeToScratch(ctx context.Context, carrierNodePath, suffix string) (string, func(), error) { - request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, carrierNodePath, nil) - if err != nil { - return "", nil, err - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return "", nil, err - } - defer response.Body.Close() - if response.StatusCode != http.StatusOK { - return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status) - } - scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix) - if err != nil { - return "", nil, err - } - cleanup := func() { _ = os.Remove(scratch.Name()) } - if _, err := io.Copy(scratch, response.Body); err != nil { - scratch.Close() - cleanup() - return "", nil, err - } - if err := scratch.Close(); err != nil { - cleanup() - return "", nil, err - } - return scratch.Name(), cleanup, nil -} - -// pushToCarrierNode streams a local file as the request body without buffering it in memory. -func (s *Server) pushToCarrierNode(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) { - file, err := os.Open(localPath) - if err != nil { - return nil, err - } - defer file.Close() - request, err := s.newCarrierNodeRequest(ctx, method, carrierNodePath, file) - if err != nil { - return nil, err - } - if info, statErr := file.Stat(); statErr == nil { - request.ContentLength = info.Size() - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return nil, err - } - if response.StatusCode >= 400 { - body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) - response.Body.Close() - return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body)) - } - return response, nil -} - -func carrierNodePushedSize(response *http.Response) int64 { - defer response.Body.Close() - var payload struct { - Size int64 `json:"size"` - } - _ = json.NewDecoder(response.Body).Decode(&payload) - return payload.Size -} - -func (s *Server) carrierNodePushThumbnail(ctx context.Context, id, localPath string) (int64, error) { - response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath) - if err != nil { - return 0, err - } - return carrierNodePushedSize(response), nil -} - -func (s *Server) carrierNodeDeleteThumbnail(ctx context.Context, id string) error { - request, err := s.newCarrierNodeRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) - if err != nil { - return err - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return err - } - defer response.Body.Close() - if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound { - return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status) - } - return nil -} - -func (s *Server) carrierNodePushOutput(ctx context.Context, name, localPath string) (int64, error) { - response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath) - if err != nil { - return 0, err - } - return carrierNodePushedSize(response), nil -} - -func (s *Server) carrierNodePushInput(ctx context.Context, name, localPath string) (int64, error) { - response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath) - if err != nil { - return 0, err - } - return carrierNodePushedSize(response), nil -} - -func (s *Server) carrierNodePushCopy(ctx context.Context, name, localPath string) (int64, error) { - response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath) - if err != nil { - return 0, err - } - return carrierNodePushedSize(response), nil -} - -// carrierNodeUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download -// staged in a scratch dir) into CarrierNode's DownloadsRoot via its existing raw-upload endpoint. -func (s *Server) carrierNodeUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) { - response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath) - if err != nil { - return nil, err - } - defer response.Body.Close() - var payload map[string]any - _ = json.NewDecoder(response.Body).Decode(&payload) - return payload, nil -} - -// carrierNodeStoreDownload catalogs an already-uploaded file into CarrierNode's media/downloaded_media -// tables via its existing /api/store endpoint - callers should stop duplicating that DB write -// locally once they migrate to this. -func (s *Server) carrierNodeStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) { - body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status}) - if err != nil { - return nil, err - } - request, err := s.newCarrierNodeRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body)) - if err != nil { - return nil, err - } - request.Header.Set("Content-Type", "application/json") - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return nil, err - } - defer response.Body.Close() - if response.StatusCode >= 400 { - errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) - return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody)) - } - var payload map[string]any - _ = json.NewDecoder(response.Body).Decode(&payload) - return payload, nil -} - -// carrierNodeListFiles lists files under CarrierNode's MediaRoots via its existing /api/files(/recent) -// endpoints - the replacement for a local filepath.WalkDir over MediaRoots. -func (s *Server) carrierNodeListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) { - endpoint := "/api/files" - if recent { - endpoint = "/api/files/recent" - } - query := url.Values{} - if relative != "" { - query.Set("path", relative) - } - if limit > 0 { - query.Set("limit", strconv.Itoa(limit)) - } - if encoded := query.Encode(); encoded != "" { - endpoint += "?" + encoded - } - request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, endpoint, nil) - if err != nil { - return nil, err - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return nil, err - } - defer response.Body.Close() - if response.StatusCode != http.StatusOK { - return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status) - } - var payload struct { - Files []fileEntry `json:"files"` - } - if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { - return nil, err - } - return payload.Files, nil -} - -type carrierNodeProbeResult struct { - DurationMs int64 `json:"durationMs"` - Width int `json:"width"` - Height int `json:"height"` -} - -// carrierNodeProbe runs ffprobe on CarrierNode against a MediaRoots-relative path and returns just the -// metadata fields - bytes never leave CarrierNode, unlike every other helper in this file. -func (s *Server) carrierNodeProbe(ctx context.Context, relative string) (carrierNodeProbeResult, error) { - query := url.Values{} - query.Set("path", relative) - request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil) - if err != nil { - return carrierNodeProbeResult{}, err - } - response, err := s.carrierNodeClient().Do(request) - if err != nil { - return carrierNodeProbeResult{}, err - } - defer response.Body.Close() - if response.StatusCode != http.StatusOK { - return carrierNodeProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status) - } - var result carrierNodeProbeResult - if err := json.NewDecoder(response.Body).Decode(&result); err != nil { - return carrierNodeProbeResult{}, err - } - return result, nil -} diff --git a/shared/media-backend/internal/server/kiosk.go b/shared/media-backend/internal/server/kiosk.go deleted file mode 100644 index d942f10..0000000 --- a/shared/media-backend/internal/server/kiosk.go +++ /dev/null @@ -1,195 +0,0 @@ -package server - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "sort" - "strconv" - "strings" - "time" - - "github.com/coder/websocket" - "github.com/go-chi/chi/v5" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" -) - -type kioskMessage struct { - Type string `json:"type"` - QueueMode string `json:"queueMode,omitempty"` - DisplayDuration int64 `json:"displayDuration,omitempty"` -} - -func (s *Server) kioskWebsocket(w http.ResponseWriter, r *http.Request) { - options := s.websocketAcceptOptions(r) - conn, err := websocket.Accept(w, r, options) - if err != nil { - return - } - defer conn.Close(websocket.StatusNormalClosure, "") - - updates := make(chan []byte, 16) - s.kioskMu.Lock() - s.kioskClients[updates] = struct{}{} - latest := s.kioskLatest - s.kioskMu.Unlock() - defer func() { - s.kioskMu.Lock() - delete(s.kioskClients, updates) - s.kioskMu.Unlock() - }() - - if latest != "" { - s.kioskSend(updates, map[string]any{"type": "new-image", "path": latest}) - } - s.kioskSend(updates, map[string]any{ - "type": "settings-updated", - "queueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"), - "serverDisplayDuration": kioskDuration(s.settingValue(r.Context(), "server_display_duration", "5000")), - }) - - ctx := r.Context() - writeCtx, cancelWrite := context.WithCancel(ctx) - defer cancelWrite() - go func() { - for { - select { - case <-writeCtx.Done(): - return - case data := <-updates: - if err := conn.Write(writeCtx, websocket.MessageText, data); err != nil { - return - } - } - } - }() - s.startKioskPoll() - for { - messageType, payload, readErr := conn.Read(ctx) - if readErr != nil { - return - } - if messageType != websocket.MessageText { - continue - } - var message kioskMessage - if json.Unmarshal(payload, &message) != nil || message.Type != "update-settings" { - continue - } - if message.QueueMode != "" && (message.QueueMode == "client" || message.QueueMode == "server") { - _ = s.saveSetting(ctx, "kiosk_queue_mode", message.QueueMode) - } - if message.DisplayDuration >= 0 && message.DisplayDuration <= 24*60*60*1000 { - _ = s.saveSetting(ctx, "server_display_duration", formatInt(message.DisplayDuration)) - } - s.kioskBroadcast(map[string]any{ - "type": "settings-updated", - "queueMode": s.settingValue(ctx, "kiosk_queue_mode", "client"), - "serverDisplayDuration": kioskDuration(s.settingValue(ctx, "server_display_duration", "5000")), - }) - } -} - -func (s *Server) startKioskPoll() { - s.kioskMu.Lock() - if s.kioskPolling { - s.kioskMu.Unlock() - return - } - s.kioskPolling = true - s.kioskMu.Unlock() - go s.kioskPoll(context.Background()) -} - -func (s *Server) kioskPoll(ctx context.Context) { - if s.cfg.Service != config.Kiosk { - return - } - ticker := time.NewTicker(3 * time.Second) - defer ticker.Stop() - for { - s.kioskPollOnce(ctx) - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - } -} - -func (s *Server) kioskPollOnce(ctx context.Context) { - files, err := s.carrierNodeListFiles(ctx, "", false, 0) - if err != nil { - return - } - images := make([]fileEntry, 0, len(files)) - for _, file := range files { - if file.Type == "image" { - images = append(images, file) - } - } - if len(images) == 0 { - return - } - sort.Slice(images, func(i, j int) bool { return images[i].Mtime > images[j].Mtime }) - latest := images[0].Rel - s.kioskMu.Lock() - changed := latest != s.kioskLatest - s.kioskLatest = latest - s.kioskMu.Unlock() - if changed { - s.kioskBroadcast(map[string]any{"type": "new-image", "path": latest}) - } -} - -func (s *Server) kioskBroadcast(message any) { - data, err := json.Marshal(message) - if err != nil { - return - } - s.kioskMu.Lock() - defer s.kioskMu.Unlock() - for client := range s.kioskClients { - select { - case client <- data: - default: - } - } -} - -func (s *Server) kioskSend(client chan []byte, message any) { - data, err := json.Marshal(message) - if err != nil { - return - } - select { - case client <- data: - default: - } -} - -func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) { - relative := chi.URLParam(r, "*") - if relative == "" { - relative = strings.TrimPrefix(r.URL.Path, "/api/images/") - } - if !safeRelative(relative) || !isImagePath(relative) { - writeError(w, http.StatusNotFound, "image not found") - return - } - s.proxyCarrierNode(w, r, "/media/"+urlPath(relative)) -} - -func kioskDuration(value string) int64 { - var duration int64 - if _, err := fmt.Sscanf(value, "%d", &duration); err != nil || duration < 0 { - return 5000 - } - return duration -} - -func formatInt(value int64) string { - return strconv.FormatInt(value, 10) -} diff --git a/shared/media-backend/internal/server/path_test.go b/shared/media-backend/internal/server/path_test.go deleted file mode 100644 index d60883a..0000000 --- a/shared/media-backend/internal/server/path_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package server - -import ( - "net" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestSafeRelativeRejectsTraversal(t *testing.T) { - for _, value := range []string{"", ".", "..", "../secret", `..\secret`, `/etc/passwd`, "a/../../b"} { - if safeRelative(value) { - t.Errorf("safeRelative(%q) = true", value) - } - } - for _, value := range []string{"video.mp4", "nested/image.webp", "funscript.json"} { - if !safeRelative(value) { - t.Errorf("safeRelative(%q) = false", value) - } - } -} - -func TestSameRealRootRejectsSymlinkEscape(t *testing.T) { - root := t.TempDir() - inside := filepath.Join(root, "inside.txt") - if err := os.WriteFile(inside, []byte("ok"), 0o600); err != nil { - t.Fatal(err) - } - if !sameRealRoot(root, inside) { - t.Fatal("sameRealRoot rejected a file inside the root") - } - outside := t.TempDir() - outsideFile := filepath.Join(outside, "outside.txt") - if err := os.WriteFile(outsideFile, []byte("secret"), 0o600); err != nil { - t.Fatal(err) - } - link := filepath.Join(root, "link.txt") - if err := os.Symlink(outsideFile, link); err != nil { - t.Skipf("symlink unavailable: %v", err) - } - if sameRealRoot(root, link) { - t.Fatal("sameRealRoot accepted a symlink outside the root") - } -} - -func TestConversionArgsDoNotAcceptArbitraryEncoderFlags(t *testing.T) { - args := strings.Join(conversionArgs("input.mp4", "output.mp4", "mp4", "-filter_complex malicious"), " ") - if strings.Contains(args, "malicious") || !strings.Contains(args, "libx264") { - t.Fatalf("conversion args = %q", args) - } -} - -func TestHasFunscriptSidecar(t *testing.T) { - root := t.TempDir() - mediaPath := filepath.Join(root, "clip.mp4") - if os.WriteFile(mediaPath, []byte("media"), 0o600) != nil { - t.Fatal("could not create media fixture") - } - if hasFunscriptSidecar(mediaPath) { - t.Fatal("media without a sidecar was marked as having a funscript") - } - if os.WriteFile(filepath.Join(root, "clip.funscript"), []byte("{}"), 0o600) != nil { - t.Fatal("could not create funscript fixture") - } - if !hasFunscriptSidecar(mediaPath) { - t.Fatal("funscript sidecar was not detected") - } -} - -func TestDownloadURLValidation(t *testing.T) { - for _, value := range []string{"file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/", "https://user:pass@example.com/x"} { - if err := validateDownloadURL(value); err == nil { - t.Errorf("validateDownloadURL(%q) succeeded", value) - } - } - if err := validateDownloadURL("https://example.com/video"); err != nil { - t.Fatalf("public URL rejected: %v", err) - } - if !isPrivateIP(net.ParseIP("127.0.0.1")) { - t.Fatal("loopback was not classified as private") - } -} diff --git a/shared/media-backend/internal/server/server.go b/shared/media-backend/internal/server/server.go deleted file mode 100644 index c19f647..0000000 --- a/shared/media-backend/internal/server/server.go +++ /dev/null @@ -1,432 +0,0 @@ -package server - -import ( - "context" - "encoding/json" - "fmt" - "io/fs" - "log" - "net/http" - "os" - "path" - "runtime" - "strings" - "sync" - "time" - - "github.com/go-chi/chi/v5" - chimiddleware "github.com/go-chi/chi/v5/middleware" - "github.com/jackc/pgx/v5/pgxpool" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth" - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" -) - -type Server struct { - cfg *config.Config - db *pgxpool.Pool - auth *auth.Service - startedAt time.Time - mediaMu sync.RWMutex - media map[string]MediaRecord - jobsMu sync.RWMutex - jobs map[string]*WorkflowJob - workflowSem chan struct{} - sync *syncHub - thumbnailMu sync.Mutex - thumbnail thumbnailGenerationState - thumbnailCancel context.CancelFunc - clearMu sync.Mutex - clear databaseClearState - scanMu sync.Mutex - scan scanState - scanCancel context.CancelFunc - analysisMu sync.Mutex - analysis analysisState - analysisCancel context.CancelFunc - kioskMu sync.Mutex - kioskClients map[chan []byte]struct{} - kioskLatest string - kioskPolling bool -} - -type MediaRecord struct { - ID int64 - MediaKey string - MediaType string - Title *string - Description *string - FilePath string - OriginalName string - Source string - Width *int - Height *int - DurationMs *int64 - SizeBytes *int64 - IsVR bool - HasFunscript bool - Speed *float32 - ModifiedAt time.Time -} - -type WorkflowJob struct { - ID string `json:"id"` - Service string `json:"service"` - Tool string `json:"tool"` - Status string `json:"status"` - Progress int `json:"progress"` - Request map[string]any `json:"request,omitempty"` - Result map[string]any `json:"result,omitempty"` - Error string `json:"error,omitempty"` - CreatedAt time.Time `json:"createdAt"` - StartedAt *time.Time `json:"startedAt,omitempty"` - FinishedAt *time.Time `json:"finishedAt,omitempty"` -} - -type thumbnailGenerationState struct { - Running bool - State string - Total int - Completed int - Failed int - Current string - CurrentType string - StartedAt *time.Time - FinishedAt *time.Time - LastError string -} - -// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the -// same live status endpoint as the analyzer workers. The reset itself is deliberately kept -// synchronous from the HTTP caller's perspective, but large libraries still need an honest state -// while their thumbnail files and database rows are being removed. -type databaseClearState struct { - Running bool - State string - Total int - Completed int - Failed int - Current string - CurrentType string - StartedAt *time.Time - FinishedAt *time.Time - LastError string -} - -// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show -// which media type is actively being indexed right now - scanMediaFiles has no separate queue, -// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as -// it's found, so "active" here is the closest honest signal to a live "processing" state. -type scanState struct { - Running bool - Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep) - CurrentType string - CurrentFile string - FilesIndexed int64 - // Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before - // looping. discover has no total (a live filesystem walk doesn't know its own size in advance) - // and leaves this at zero, which the UI treats as "not available". - Total int64 - StartedAt *time.Time - // LastError survives the end-of-run reset (unlike every other field here) so a run that - // failed fast - e.g. CarrierNode unreachable - doesn't just look like it silently reverted - // to idle; analyzerStatus reports it until the next run overwrites or clears it. - LastError string -} - -func New(cfg *config.Config, db *pgxpool.Pool) *Server { - return &Server{ - cfg: cfg, - db: db, - auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies, cfg.AuthGuardURL), - startedAt: time.Now(), - media: make(map[string]MediaRecord), - jobs: make(map[string]*WorkflowJob), - workflowSem: make(chan struct{}, 2), - sync: newSyncHub(), - thumbnail: thumbnailGenerationState{State: "idle"}, - analysis: analysisState{State: "idle"}, - kioskClients: make(map[chan []byte]struct{}), - } -} - -func (s *Server) Handler() http.Handler { - router := chi.NewRouter() - router.Use(chimiddleware.RequestID) - router.Use(chimiddleware.Recoverer) - router.Use(s.securityHeadersMiddleware) - router.Use(s.cors) - - router.Get("/healthz", s.health) - router.Get("/health", s.health) - router.Get("/ready", s.ready) - router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack) - router.Get("/__cache-policy", s.cachePolicy) - - router.Route("/auth", func(r chi.Router) { - r.Post("/signup", s.auth.Signup) - r.Post("/login", s.auth.Login) - r.Post("/logout", s.auth.Logout) - r.Get("/me", s.auth.Me) - r.With(s.auth.Require).Put("/me", s.auth.UpdateMe) - r.Get("/status", s.auth.Status) - r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded) - }) - router.Route("/api/auth", func(r chi.Router) { - manager := r.With(s.auth.RequireUserManager) - manager.Get("/access", s.auth.AccessSettings) - manager.Put("/access", s.auth.UpdateAccessSettings) - manager.Get("/users", s.auth.ManagedUsers) - manager.Post("/users", s.auth.ManagedCreateUser) - manager.Put("/users/{id}", s.auth.ManagedUpdateUser) - manager.Patch("/users/{id}", s.auth.ManagedUpdateUser) - manager.Delete("/users/{id}", s.auth.ManagedDeleteUser) - }) - router.Route("/api", func(r chi.Router) { - s.mountServiceRoutes(r) - }) - - if s.cfg.Service == config.Kiosk { - s.mountKioskSocket(router) - } - if s.cfg.Service != config.Kiosk { - router.HandleFunc("/ws", s.syncWebsocket) - } - if s.cfg.Service == config.CarrierNode { - internal := s.internalServiceAuth - router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.carrierNodeDownloadMedia))) - router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.carrierNodeGeneratedMedia))) - router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.carrierNodeInputMedia))) - router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.carrierNodeCopyMedia))) - router.Handle("/media/*", internal(http.HandlerFunc(s.carrierNodeMedia))) - router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.carrierNodeThumbnail))) - } - - router.NotFound(s.staticHandler) - return router -} - -func (s *Server) mountServiceRoutes(r chi.Router) { - s.mountSharedRoutes(r) - switch s.cfg.Service { - case config.Viewer: - s.mountViewerRoutes(r) - case config.CraftStudio: - s.mountToolsRoutes(r) - case config.ContentScanner: - s.mountAnalyzerRoutes(r) - case config.ConfigService: - s.mountConfigRoutes(r) - case config.Moderator: - s.mountModeratorRoutes(r) - case config.Kiosk: - s.mountKioskRoutes(r) - case config.CarrierNode: - s.mountCarrierNodeRoutes(r) - } -} - -func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("X-Content-Type-Options", "nosniff") - w.Header().Set("X-Frame-Options", "DENY") - w.Header().Set("Referrer-Policy", "same-origin") - w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") - w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:") - next.ServeHTTP(w, r) - }) -} - -func (s *Server) cors(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - origin := r.Header.Get("Origin") - if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) { - w.Header().Set("Access-Control-Allow-Origin", origin) - w.Header().Set("Access-Control-Allow-Credentials", "true") - w.Header().Add("Vary", "Origin") - } - if r.Method == http.MethodOptions { - w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth") - w.WriteHeader(http.StatusNoContent) - return - } - next.ServeHTTP(w, r) - }) -} - -func (s *Server) health(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())}) -} - -func (s *Server) ready(w http.ResponseWriter, r *http.Request) { - if s.db == nil { - writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"}) - return - } - ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) - defer cancel() - if err := s.db.Ping(ctx); err != nil { - writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"}) - return - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName}) -} - -func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) { - appVersion := os.Getenv("APP_VERSION") - if appVersion == "" { - appVersion = "go-rewrite" - } - writeJSON(w, http.StatusOK, map[string]any{ - "appVersion": appVersion, - "stack": []map[string]string{ - {"label": "Runtime", "value": runtime.Version()}, - {"label": "HTTP", "value": "net/http + chi"}, - {"label": "Database", "value": "PostgreSQL + pgx"}, - {"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"}, - }, - }) -} - -func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}}) -} - -func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) { - root := os.DirFS(s.cfg.WebRoot) - if _, err := fs.Stat(root, "."); err != nil { - writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"}) - return - } - requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/") - if requested == "." || requested == "" { - requested = "index.html" - } - if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() { - http.FileServer(http.FS(root)).ServeHTTP(w, r) - return - } - if path.Ext(requested) != "" { - http.NotFound(w, r) - return - } - index, err := fs.ReadFile(root, "index.html") - if err != nil { - http.NotFound(w, r) - return - } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - _, _ = w.Write(index) -} - -func (s *Server) listenAndServe(ctx context.Context) error { - server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second} - go func() { - <-ctx.Done() - shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - _ = server.Shutdown(shutdownCtx) - }() - log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port) - if s.cfg.TLSCertFile != "" { - return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile) - } - return server.ListenAndServe() -} - -func (s *Server) Run(ctx context.Context) error { - go s.resumeWorkflowJobs(ctx) - if s.cfg.Service == config.ContentScanner { - go s.runAnalyzerScheduler(ctx) - } - if s.cfg.Service == config.ConfigService { - go s.runSettingsSyncScheduler(ctx) - } - return s.listenAndServe(ctx) -} - -func writeJSON(w http.ResponseWriter, status int, value any) { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(value) -} - -func writeError(w http.ResponseWriter, status int, message string) { - writeJSON(w, status, map[string]string{"error": message, "message": message}) -} - -func stringValue(value *string) string { - if value == nil { - return "" - } - return *value -} - -func intValue(value *int) any { - if value == nil { - return nil - } - return *value -} - -func int64Value(value *int64) any { - if value == nil { - return nil - } - return *value -} - -func floatValue(value *float32) any { - if value == nil { - return nil - } - return *value -} - -func boolQuery(value string) *bool { - switch strings.ToLower(strings.TrimSpace(value)) { - case "1", "true", "yes", "on": - result := true - return &result - case "0", "false", "no", "off": - result := false - return &result - default: - return nil - } -} - -func (s *Server) internalServiceAuth(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret { - writeError(w, http.StatusUnauthorized, "internal service authentication required") - return - } - next.ServeHTTP(w, r) - }) -} - -func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) { - next.ServeHTTP(w, r) - return - } - writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required") - }) -} - -func optionalInt(value string, fallback, minimum, maximum int) int { - var parsed int - if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil { - return fallback - } - if parsed < minimum { - return minimum - } - if parsed > maximum { - return maximum - } - return parsed -} diff --git a/shared/media-backend/internal/server/workflows.go b/shared/media-backend/internal/server/workflows.go deleted file mode 100644 index 3992f24..0000000 --- a/shared/media-backend/internal/server/workflows.go +++ /dev/null @@ -1,1005 +0,0 @@ -package server - -import ( - "bytes" - "context" - "crypto/rand" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/url" - "os" - "os/exec" - "path/filepath" - "sort" - "strings" - "time" - - "github.com/go-chi/chi/v5" - - "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth" -) - -func (s *Server) mountToolsRoutes(r chi.Router) { - r.Get("/generator/label", func(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]string{"label": "Generator"}) - }) - r.Get("/downloader/label", func(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]string{"label": "Downloader"}) - }) - r.Get("/converter/label", func(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]string{"label": "Converter"}) - }) - r.Get("/workflows/list", s.workflowList) - r.Get("/input/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/inputs/") }) - r.Get("/copy/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/copies/") }) - r.Get("/output/*", func(w http.ResponseWriter, req *http.Request) { s.toolFile(w, req, "/mount/generated/") }) - r.With(s.auth.RequireIfLoginRequired).Post("/upload", s.toolUpload) - r.Get("/converter/formats", s.converterFormats) - r.Get("/converter/breakdown", s.converterBreakdown) - r.Get("/converter/settings", s.converterSettings) - r.With(s.auth.RequireIfLoginRequired).Put("/converter/settings", s.saveConverterSettings) - r.Get("/jobs", s.workflowJobs) - r.Get("/queue", s.workflowQueue) - r.Get("/jobs/{id}", s.workflowJob) - r.With(s.auth.RequireIfLoginRequired).Post("/jobs/{tool}/start", s.startWorkflowJob) - r.With(s.auth.RequireIfLoginRequired).Delete("/jobs/{id}", s.deleteWorkflowJob) - r.Get("/schedules", s.workflowSchedules) - r.With(s.auth.RequireIfLoginRequired).Post("/schedules/{id}/run", s.runWorkflowSchedule) - r.With(s.auth.RequireIfLoginRequired).Post("/schedules", s.createWorkflowSchedule) - r.With(s.auth.RequireIfLoginRequired).Delete("/schedules/{id}", s.deleteWorkflowSchedule) - - r.Get("/generator/schedules", s.workflowSchedules) - r.Get("/downloader/schedules", s.workflowSchedules) - r.Get("/converter/schedules", s.workflowSchedules) - r.With(s.auth.RequireIfLoginRequired).Post("/generator/upload-copy", s.uploadCopy) - r.With(s.auth.RequireIfLoginRequired).Post("/downloader/single", s.startSingleDownload) - r.Get("/downloader/queue", s.workflowJobs) - r.Get("/library/unified", s.unifiedLibrary) - r.Get("/generator/workflows/meta", s.workflowMeta) - r.Get("/generator/my-generations", s.myGenerations) - r.With(s.auth.RequireIfLoginRequired).Post("/converter/start", s.startWorkflowJob) - r.With(s.auth.RequireIfLoginRequired).Post("/converter/start-group", s.startWorkflowJob) - r.With(s.auth.RequireIfLoginRequired).Post("/converter/start-discovered", s.startWorkflowJob) - r.Get("/converter/jobs", s.workflowJobs) - r.Get("/converter/jobs/{id}", s.workflowJob) - r.With(s.auth.RequireIfLoginRequired).Get("/converter/download/{id}", s.downloadWorkflowResult) - -} - -func (s *Server) converterFormats(w http.ResponseWriter, _ *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"formats": []map[string]any{ - {"id": "mp4", "label": "MP4", "extension": ".mp4", "video": true, "audio": true}, - {"id": "webm", "label": "WebM", "extension": ".webm", "video": true, "audio": true}, - {"id": "mkv", "label": "Matroska", "extension": ".mkv", "video": true, "audio": true}, - {"id": "mp3", "label": "MP3", "extension": ".mp3", "video": false, "audio": true}, - }}) -} - -func (s *Server) converterBreakdown(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"items": []any{}, "total": 0}) -} - -func (s *Server) converterSettings(w http.ResponseWriter, r *http.Request) { - settings := map[string]string{} - rows, err := s.db.Query(r.Context(), `SELECT key, value FROM settings WHERE key LIKE 'converter_%' OR key LIKE 'mediatools_%' ORDER BY key`) - if err == nil { - defer rows.Close() - for rows.Next() { - var key, value string - if rows.Scan(&key, &value) == nil { - settings[key] = value - } - } - } - writeJSON(w, http.StatusOK, map[string]any{"settings": settings}) -} - -func (s *Server) saveConverterSettings(w http.ResponseWriter, r *http.Request) { - var settings map[string]any - if err := decodeRequestJSON(r, &settings); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - for key, value := range settings { - if !strings.HasPrefix(key, "converter_") && !strings.HasPrefix(key, "mediatools_") { - continue - } - encoded, _ := json.Marshal(value) - _, _ = s.db.Exec(r.Context(), `INSERT INTO settings (key, value, updated_at) VALUES ($1, $2, NOW()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, key, strings.Trim(string(encoded), `"`)) - } - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) -} - -func (s *Server) workflowJobs(w http.ResponseWriter, r *http.Request) { - tool := strings.TrimSpace(r.URL.Query().Get("tool")) - query := `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE service = $1` - args := []any{s.cfg.ServiceName} - if tool != "" { - query += " AND tool = $2" - args = append(args, tool) - } - query += " ORDER BY created_at DESC LIMIT 100" - rows, err := s.db.Query(r.Context(), query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "workflow jobs unavailable") - return - } - defer rows.Close() - jobs := make([]WorkflowJob, 0) - for rows.Next() { - job, err := scanWorkflowJob(rows) - if err == nil { - jobs = append(jobs, job) - } - } - writeJSON(w, http.StatusOK, map[string]any{"jobs": jobs, "items": jobs}) -} - -func (s *Server) workflowQueue(w http.ResponseWriter, r *http.Request) { - tool := strings.TrimSpace(r.URL.Query().Get("tool")) - query := `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE service = $1 AND status IN ('queued', 'processing')` - args := []any{s.cfg.ServiceName} - if tool != "" { - query += " AND tool = $2" - args = append(args, tool) - } - query += " ORDER BY created_at ASC LIMIT 100" - rows, err := s.db.Query(r.Context(), query, args...) - if err != nil { - writeError(w, http.StatusInternalServerError, "workflow queue unavailable") - return - } - defer rows.Close() - jobs := make([]WorkflowJob, 0) - for rows.Next() { - if job, scanErr := scanWorkflowJob(rows); scanErr == nil { - jobs = append(jobs, job) - } - } - writeJSON(w, http.StatusOK, map[string]any{"queue": jobs, "jobs": jobs, "items": jobs}) -} - -func (s *Server) workflowJob(w http.ResponseWriter, r *http.Request) { - job, err := s.findWorkflowJob(r.Context(), chi.URLParam(r, "id")) - if err != nil { - writeError(w, http.StatusNotFound, "job not found") - return - } - writeJSON(w, http.StatusOK, job) -} - -func (s *Server) startWorkflowJob(w http.ResponseWriter, r *http.Request) { - tool := strings.TrimSpace(chi.URLParam(r, "tool")) - if tool == "" { - tool = inferToolFromPath(r.URL.Path) - } - var request map[string]any - if r.Body != nil && r.ContentLength != 0 { - if err := decodeRequestJSON(r, &request); err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.EOF) { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - } - if request == nil { - request = map[string]any{} - } - job, err := s.createWorkflowJob(r.Context(), tool, request) - if err != nil { - writeError(w, http.StatusInternalServerError, "job could not be queued") - return - } - s.enqueueWorkflowJob(job.ID) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job, "id": job.ID}) -} - -func (s *Server) startSingleDownload(w http.ResponseWriter, r *http.Request) { - var request map[string]any - if err := decodeRequestJSON(r, &request); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - rawURL, _ := request["url"].(string) - if err := validateDownloadURL(rawURL); err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - job, err := s.createWorkflowJob(r.Context(), "downloader", request) - if err != nil { - writeError(w, http.StatusInternalServerError, "download could not be queued") - return - } - s.enqueueWorkflowJob(job.ID) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job, "queueId": job.ID}) -} - -func (s *Server) createWorkflowJob(ctx context.Context, tool string, request map[string]any) (*WorkflowJob, error) { - jobID, err := randomID() - if err != nil { - return nil, err - } - requestJSON, err := json.Marshal(request) - if err != nil { - return nil, err - } - var userID any - if user := auth.UserFromContext(ctx); user != nil { - userID = user.ID - } - _, err = s.db.Exec(ctx, `INSERT INTO workflow_jobs (id, service, tool, request, user_id) VALUES ($1, $2, $3, $4, $5)`, jobID, s.cfg.ServiceName, tool, requestJSON, userID) - if err != nil { - return nil, err - } - job := &WorkflowJob{ID: jobID, Service: s.cfg.ServiceName, Tool: tool, Status: "queued", Request: request, Result: map[string]any{}, CreatedAt: time.Now()} - s.jobsMu.Lock() - s.jobs[job.ID] = job - s.jobsMu.Unlock() - return job, nil -} - -func (s *Server) enqueueWorkflowJob(id string) { - go func() { - s.workflowSem <- struct{}{} - defer func() { <-s.workflowSem }() - s.processWorkflowJob(id) - }() -} - -func (s *Server) processWorkflowJob(id string) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) - defer cancel() - job, err := s.findWorkflowJob(ctx, id) - if err != nil { - return - } - started := time.Now() - _, _ = s.db.Exec(ctx, `UPDATE workflow_jobs SET status='processing', progress=5, started_at=$2, error_message=NULL WHERE id=$1`, id, started) - - result, executionErr := s.executeWorkflow(ctx, job) - status := "completed" - progress := 100 - message := "" - if executionErr != nil { - status = "failed" - progress = 0 - message = executionErr.Error() - if result == nil { - result = map[string]any{} - } - } - finished := time.Now() - _, _ = s.db.Exec(ctx, `UPDATE workflow_jobs SET status=$2, progress=$3, result=$4, error_message=NULLIF($5, ''), finished_at=$6 WHERE id=$1`, id, status, progress, mustJSON(result), message, finished) - if job, err := s.findWorkflowJob(ctx, id); err == nil { - s.jobsMu.Lock() - s.jobs[id] = &job - s.jobsMu.Unlock() - } -} - -func (s *Server) executeWorkflow(ctx context.Context, job WorkflowJob) (map[string]any, error) { - switch strings.ToLower(job.Tool) { - case "converter": - return s.executeConversion(ctx, job) - case "downloader": - return s.executeDownload(ctx, job) - case "generator": - return s.executeGeneration(ctx, job) - default: - return nil, fmt.Errorf("unsupported workflow tool: %s", job.Tool) - } -} - -func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[string]any, error) { - sourceName := firstString(job.Request, "sourcePath", "input", "path") - if sourceName == "" { - return nil, fmt.Errorf("converter input path is required") - } - source, cleanupSource, err := s.fetchWorkflowFileFromCarrierNode(ctx, sourceName) - if err != nil { - return nil, fmt.Errorf("converter input is not an allowed file: %w", err) - } - defer cleanupSource() - target := strings.ToLower(strings.TrimPrefix(firstString(job.Request, "targetFormat", "format", "extension"), ".")) - if target == "" { - target = strings.TrimPrefix(strings.ToLower(filepath.Ext(sourceName)), ".") - } - if !supportedConversionFormat(target) { - return nil, fmt.Errorf("unsupported converter target format: %s", target) - } - base := safeOutputBase(filepath.Base(sourceName)) - outputName := fmt.Sprintf("%s-%s.%s", base, shortID(job.ID), target) - temporary, err := os.CreateTemp("", ".convert-*."+target) - if err != nil { - return nil, fmt.Errorf("converter scratch file unavailable: %w", err) - } - outputPath := temporary.Name() - if err := temporary.Close(); err != nil { - _ = os.Remove(outputPath) - return nil, err - } - defer os.Remove(outputPath) - args := conversionArgs(source, outputPath, target, firstString(job.Request, "encoding", "encodingProfile")) - var output bytes.Buffer - command := exec.CommandContext(ctx, s.cfg.FFmpeg, args...) - command.Stdout = &output - command.Stderr = &output - if err := command.Run(); err != nil { - return nil, fmt.Errorf("ffmpeg conversion failed: %s", tailOutput(output.String(), 600)) - } - info, err := os.Stat(outputPath) - if err != nil || info.IsDir() { - return nil, fmt.Errorf("ffmpeg did not produce an output file") - } - size, err := s.carrierNodePushOutput(ctx, outputName, outputPath) - if err != nil { - return nil, fmt.Errorf("converted output could not be stored: %w", err) - } - return map[string]any{"backend": "go", "outputFile": outputName, "outputSize": size, "sourceFile": filepath.Base(sourceName), "targetFormat": target}, nil -} - -func (s *Server) executeDownload(ctx context.Context, job WorkflowJob) (map[string]any, error) { - sourceURL := firstString(job.Request, "url", "sourceUrl", "sourceURL") - if err := validateDownloadURL(sourceURL); err != nil { - return nil, err - } - if err := ensurePublicDownloadHost(ctx, sourceURL); err != nil { - return nil, err - } - scratchDir, err := os.MkdirTemp("", "yt-dlp-*") - if err != nil { - return nil, fmt.Errorf("download scratch directory unavailable: %w", err) - } - defer os.RemoveAll(scratchDir) - template := filepath.Join(scratchDir, "%(title).200B.%(ext)s") - command := exec.CommandContext(ctx, s.cfg.YTDLP, "--no-playlist", "--no-part", "--newline", "--print", "after_move:filepath", "-o", template, "--", sourceURL) - var output bytes.Buffer - command.Stdout = &output - command.Stderr = &output - if err := command.Run(); err != nil { - return nil, fmt.Errorf("download failed: %s", tailOutput(output.String(), 600)) - } - filePath := newestDownloadedFile(scratchDir, output.String()) - if filePath == "" { - return nil, fmt.Errorf("downloader completed without producing a file") - } - info, err := os.Stat(filePath) - if err != nil || info.IsDir() { - return nil, fmt.Errorf("downloaded file is unavailable") - } - filename := filepath.Base(filePath) - // Pushing through CarrierNode's upload endpoint also catalogs the file into media/media_worker_jobs - // (see carrierNodeRawUpload) - no separate indexMediaFile call needed here. - if _, err := s.carrierNodeUploadDownload(ctx, filePath, filename); err != nil { - return nil, fmt.Errorf("downloaded file could not be stored: %w", err) - } - _, _ = s.db.Exec(ctx, `INSERT INTO downloaded_media (source_url, tool, file_path, file_name, file_size_bytes, status, started_at, finished_at) VALUES ($1,'yt-dlp',$2,$3,$4,'completed',$5,NOW())`, sourceURL, filename, filename, info.Size(), job.CreatedAt) - return map[string]any{"backend": "go", "file": filename, "filename": filename, "size": info.Size(), "sourceUrl": sourceURL}, nil -} - -func (s *Server) executeGeneration(ctx context.Context, job WorkflowJob) (map[string]any, error) { - workflow, ok := job.Request["workflow"].(map[string]any) - if !ok { - workflow, ok = job.Request["prompt"].(map[string]any) - } - if !ok || len(workflow) == 0 { - return nil, fmt.Errorf("generator workflow graph is required") - } - applyGeneratorPrompt(workflow, firstString(job.Request, "promptText")) - body, _ := json.Marshal(map[string]any{"prompt": workflow, "client_id": job.ID}) - request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(s.cfg.ComfyURL, "/")+"/prompt", bytes.NewReader(body)) - if err != nil { - return nil, err - } - request.Header.Set("Content-Type", "application/json") - response, err := http.DefaultClient.Do(request) - if err != nil { - return nil, fmt.Errorf("ComfyUI request failed: %w", err) - } - defer response.Body.Close() - var payload struct { - PromptID string `json:"prompt_id"` - Error string `json:"error"` - } - if err := json.NewDecoder(io.LimitReader(response.Body, 512*1024)).Decode(&payload); err != nil { - return nil, fmt.Errorf("invalid ComfyUI response: %w", err) - } - if response.StatusCode >= 300 || payload.PromptID == "" { - if payload.Error == "" { - payload.Error = response.Status - } - return nil, fmt.Errorf("ComfyUI rejected workflow: %s", payload.Error) - } - return map[string]any{"backend": "go", "promptId": payload.PromptID, "status": "submitted"}, nil -} - -func (s *Server) resumeWorkflowJobs(ctx context.Context) { - rows, err := s.db.Query(ctx, `SELECT id FROM workflow_jobs WHERE service=$1 AND status IN ('queued','processing') ORDER BY created_at`, s.cfg.ServiceName) - if err != nil { - return - } - defer rows.Close() - for rows.Next() { - var id string - if rows.Scan(&id) == nil { - s.enqueueWorkflowJob(id) - } - } -} - -func firstString(values map[string]any, keys ...string) string { - for _, key := range keys { - if value, ok := values[key].(string); ok && strings.TrimSpace(value) != "" { - return strings.TrimSpace(value) - } - } - return "" -} - -// workflowFileCarrierNodePaths mirrors the search order resolveWorkflowFile used to walk locally -// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as CarrierNode-side mount prefixes, since -// CraftStudio no longer has any of those roots mounted on its own filesystem. -var workflowFileCarrierNodePaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"} - -// fetchWorkflowFileFromCarrierNode locates a converter input under any of CarrierNode's mounts and -// downloads it into an ephemeral scratch file for ffmpeg to read; the caller must invoke the -// returned cleanup once done. -func (s *Server) fetchWorkflowFileFromCarrierNode(ctx context.Context, value string) (string, func(), error) { - value = strings.TrimSpace(value) - if !safeRelative(value) { - return "", nil, os.ErrNotExist - } - for _, prefix := range workflowFileCarrierNodePaths { - carrierNodePath := prefix + urlPath(value) - if exists, _, _, err := s.probeCarrierNode(ctx, carrierNodePath); err != nil || !exists { - continue - } - return s.fetchCarrierNodeToScratch(ctx, carrierNodePath, filepath.Ext(value)) - } - return "", nil, os.ErrNotExist -} - -func safeOutputBase(value string) string { - base := strings.TrimSuffix(filepath.Base(value), filepath.Ext(value)) - var builder strings.Builder - for _, character := range base { - if (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || character == '-' || character == '_' { - builder.WriteRune(character) - } else { - builder.WriteByte('_') - } - } - result := strings.Trim(builder.String(), "_.-") - if result == "" { - return "converted" - } - if len(result) > 100 { - return result[:100] - } - return result -} - -func shortID(value string) string { - if len(value) > 8 { - return value[:8] - } - if value == "" { - return "job" - } - return value -} - -func supportedConversionFormat(value string) bool { - switch value { - case "mp4", "mkv", "mov", "webm", "avi", "flv", "wmv", "ts", "3gp", "mpg", "gif", "mp3", "flac", "wav", "aac", "ogg", "opus", "m4a", "jpg", "jpeg", "png", "webp", "bmp", "tiff", "avif": - return true - default: - return false - } -} - -func conversionArgs(source, output, target, encoding string) []string { - args := []string{"-hide_banner", "-loglevel", "error", "-y", "-i", source} - switch target { - case "mp3": - args = append(args, "-vn", "-c:a", "libmp3lame", "-q:a", "2") - case "flac": - args = append(args, "-vn", "-c:a", "flac") - case "wav": - args = append(args, "-vn", "-c:a", "pcm_s16le") - case "aac", "m4a": - args = append(args, "-vn", "-c:a", "aac", "-b:a", "192k") - case "ogg", "opus": - args = append(args, "-vn", "-c:a", "libopus", "-b:a", "160k") - case "jpg", "jpeg", "png", "webp", "bmp", "tiff", "avif": - args = append(args, "-frames:v", "1") - case "webm": - args = append(args, "-c:v", "libvpx-vp9", "-crf", "32", "-b:v", "0", "-c:a", "libopus") - default: - preset, crf := "medium", "23" - switch strings.ToLower(strings.TrimSpace(encoding)) { - case "fast": - preset, crf = "veryfast", "28" - case "quality": - preset, crf = "slow", "18" - } - args = append(args, "-c:v", "libx264", "-preset", preset, "-crf", crf, "-c:a", "aac", "-b:a", "192k") - if target == "mp4" { - args = append(args, "-movflags", "+faststart") - } - } - return append(args, output) -} - -func applyGeneratorPrompt(workflow map[string]any, prompt string) { - prompt = strings.TrimSpace(prompt) - if prompt == "" { - return - } - for _, rawNode := range workflow { - node, ok := rawNode.(map[string]any) - if !ok { - continue - } - classType, _ := node["class_type"].(string) - inputs, ok := node["inputs"].(map[string]any) - if ok && classType == "CLIPTextEncode" { - inputs["text"] = prompt - return - } - } -} - -func tailOutput(value string, limit int) string { - value = strings.TrimSpace(value) - if len(value) <= limit { - return value - } - return value[len(value)-limit:] -} - -func newestDownloadedFile(root, commandOutput string) string { - candidates := make([]string, 0) - for _, line := range strings.Split(commandOutput, "\n") { - line = strings.Trim(strings.TrimSpace(line), "\"") - if line == "" || strings.HasPrefix(line, "[download]") || strings.HasPrefix(line, "WARNING:") { - continue - } - candidate := filepath.FromSlash(line) - if !filepath.IsAbs(candidate) { - candidate = filepath.Join(root, candidate) - } - if info, err := os.Stat(candidate); err == nil && !info.IsDir() && sameRealRoot(root, candidate) { - candidates = append(candidates, candidate) - } - } - entries, _ := os.ReadDir(root) - for _, entry := range entries { - if entry.IsDir() { - continue - } - candidates = append(candidates, filepath.Join(root, entry.Name())) - } - if len(candidates) == 0 { - return "" - } - sort.Slice(candidates, func(i, j int) bool { - left, _ := os.Stat(candidates[i]) - right, _ := os.Stat(candidates[j]) - if left == nil || right == nil { - return false - } - return left.ModTime().After(right.ModTime()) - }) - return candidates[0] -} - -func ensurePublicDownloadHost(ctx context.Context, raw string) error { - parsed, err := url.Parse(raw) - if err != nil { - return err - } - addresses, err := net.DefaultResolver.LookupIPAddr(ctx, parsed.Hostname()) - if err != nil { - return fmt.Errorf("download host could not be resolved") - } - for _, address := range addresses { - if isPrivateIP(address.IP) { - return fmt.Errorf("private and local download hosts are not allowed") - } - } - return nil -} - -func (s *Server) deleteWorkflowJob(w http.ResponseWriter, r *http.Request) { - result, err := s.db.Exec(r.Context(), `DELETE FROM workflow_jobs WHERE id=$1 AND service=$2`, chi.URLParam(r, "id"), s.cfg.ServiceName) - if err != nil || result.RowsAffected() == 0 { - writeError(w, http.StatusNotFound, "job not found") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) workflowSchedules(w http.ResponseWriter, r *http.Request) { - rows, err := s.db.Query(r.Context(), `SELECT id, service, tool, name, interval_minutes, enabled, settings, last_run_at, last_status, next_run_at FROM workflow_schedules WHERE service=$1 ORDER BY created_at DESC`, s.cfg.ServiceName) - if err != nil { - writeError(w, http.StatusInternalServerError, "schedules unavailable") - return - } - defer rows.Close() - schedules := make([]map[string]any, 0) - for rows.Next() { - var id, service, tool, name string - var lastStatus *string - var interval int - var enabled bool - var settings []byte - var lastRun, nextRun *time.Time - if rows.Scan(&id, &service, &tool, &name, &interval, &enabled, &settings, &lastRun, &lastStatus, &nextRun) != nil { - continue - } - var parsed any - _ = json.Unmarshal(settings, &parsed) - schedules = append(schedules, map[string]any{"id": id, "service": service, "tool": tool, "name": name, "intervalMinutes": interval, "enabled": enabled, "settings": parsed, "lastRunAt": lastRun, "lastStatus": lastStatus, "nextRunAt": nextRun}) - } - writeJSON(w, http.StatusOK, map[string]any{"schedules": schedules, "items": schedules}) -} - -func (s *Server) createWorkflowSchedule(w http.ResponseWriter, r *http.Request) { - var input struct { - ID string `json:"id"` - Tool string `json:"tool"` - Name string `json:"name"` - IntervalMinutes int `json:"intervalMinutes"` - Enabled *bool `json:"enabled"` - Settings map[string]any `json:"settings"` - } - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if input.Name == "" { - input.Name = input.Tool + " schedule" - } - if input.Tool == "" { - input.Tool = "workflow" - } - if input.IntervalMinutes <= 0 { - input.IntervalMinutes = 60 - } - id := input.ID - if id == "" { - id, _ = randomID() - } - enabled := true - if input.Enabled != nil { - enabled = *input.Enabled - } - var userID any - if user := auth.UserFromContext(r.Context()); user != nil { - userID = user.ID - } - _, err := s.db.Exec(r.Context(), `INSERT INTO workflow_schedules (id, service, tool, name, interval_minutes, enabled, settings, user_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (id) DO UPDATE SET name=EXCLUDED.name, interval_minutes=EXCLUDED.interval_minutes, enabled=EXCLUDED.enabled, settings=EXCLUDED.settings, updated_at=NOW()`, id, s.cfg.ServiceName, input.Tool, input.Name, input.IntervalMinutes, enabled, mustJSON(input.Settings), userID) - if err != nil { - writeError(w, http.StatusInternalServerError, "schedule could not be saved") - return - } - writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "id": id}) -} - -func (s *Server) runWorkflowSchedule(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - var tool string - var settings []byte - if err := s.db.QueryRow(r.Context(), `SELECT tool, settings FROM workflow_schedules WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName).Scan(&tool, &settings); err != nil { - writeError(w, http.StatusNotFound, "schedule not found") - return - } - var request map[string]any - _ = json.Unmarshal(settings, &request) - job, err := s.createWorkflowJob(r.Context(), tool, request) - if err != nil { - writeError(w, http.StatusInternalServerError, "scheduled job could not be queued") - return - } - _, _ = s.db.Exec(r.Context(), `UPDATE workflow_schedules SET last_run_at=NOW(), last_status='queued', next_run_at=NOW() + make_interval(mins => interval_minutes), updated_at=NOW() WHERE id=$1`, id) - s.enqueueWorkflowJob(job.ID) - writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "job": job}) -} - -func (s *Server) deleteWorkflowSchedule(w http.ResponseWriter, r *http.Request) { - result, err := s.db.Exec(r.Context(), `DELETE FROM workflow_schedules WHERE id=$1 AND service=$2`, chi.URLParam(r, "id"), s.cfg.ServiceName) - if err != nil || result.RowsAffected() == 0 { - writeError(w, http.StatusNotFound, "schedule not found") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Server) uploadCopy(w http.ResponseWriter, r *http.Request) { - if s.cfg.MaxUploadBytes > 0 { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) - } - filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushCopy) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - file := map[string]any{"filename": filename, "path": filename, "size": size} - writeJSON(w, http.StatusOK, map[string]any{"success": true, "filename": filename, "file": file, "files": []any{file}, "uploadCopyDir": "/copy"}) -} - -func (s *Server) toolUpload(w http.ResponseWriter, r *http.Request) { - if s.cfg.MaxUploadBytes > 0 { - r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) - } - filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushInput) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - writeJSON(w, http.StatusAccepted, map[string]any{"success": true, "filename": filename, "file": map[string]any{"filename": filename, "path": filename, "size": size}, "inputDir": "/input"}) -} - -func (s *Server) saveMultipartUpload(r *http.Request, push func(ctx context.Context, name, localPath string) (int64, error)) (string, int64, error) { - if err := r.ParseMultipartForm(8 << 20); err != nil { - return "", 0, errors.New("invalid multipart upload") - } - file, header, err := r.FormFile("file") - if err != nil { - file, header, err = r.FormFile("image") - } - if err != nil || file == nil || header == nil { - return "", 0, errors.New("file is required") - } - defer file.Close() - filename := uploadFilename(header.Filename) - temporary, err := os.CreateTemp("", "upload-*") - if err != nil { - return "", 0, errors.New("upload could not be stored") - } - temporaryPath := temporary.Name() - defer os.Remove(temporaryPath) - _, copyErr := io.Copy(temporary, file) - closeErr := temporary.Close() - if copyErr != nil || closeErr != nil { - return "", 0, errors.New("upload could not be stored") - } - size, err := push(r.Context(), filename, temporaryPath) - if err != nil { - return "", 0, errors.New("upload could not be stored") - } - return filename, size, nil -} - -func uploadFilename(original string) string { - name := filepath.Base(strings.TrimSpace(original)) - extension := filepath.Ext(name) - stem := strings.TrimSuffix(name, extension) - stem = sanitizeUploadPart(stem) - extension = sanitizeUploadPart(extension) - if stem == "" { - stem = "upload" - } - if extension != "" && !strings.HasPrefix(extension, ".") { - extension = "." + extension - } - id, err := randomID() - if err != nil || len(id) < 8 { - id = "upload00000000" - } - return id[:8] + "-" + stem[:minInt(len(stem), 160)] + extension -} - -func sanitizeUploadPart(value string) string { - var builder strings.Builder - for _, char := range value { - if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '.' || char == '_' || char == '-' { - builder.WriteRune(char) - } else { - builder.WriteByte('_') - } - } - return strings.Trim(builder.String(), "._-") -} - -func (s *Server) toolFile(w http.ResponseWriter, r *http.Request, mountPrefix string) { - relative := chi.URLParam(r, "*") - if relative == "" { - relative = strings.TrimPrefix(r.URL.Path, "/") - } - if !safeRelative(relative) { - writeError(w, http.StatusNotFound, "file not found") - return - } - s.proxyCarrierNode(w, r, mountPrefix+urlPath(relative)) -} - -func (s *Server) workflowList(w http.ResponseWriter, _ *http.Request) { - entries, err := os.ReadDir(s.cfg.WorkflowsRoot) - if err != nil { - writeJSON(w, http.StatusOK, map[string]any{"success": true, "builtIn": []string{}, "mine": []string{}, "data": []string{}}) - return - } - workflows := make([]string, 0, len(entries)) - for _, entry := range entries { - if entry.IsDir() { - continue - } - ext := strings.ToLower(filepath.Ext(entry.Name())) - if ext == ".json" || ext == ".png" { - workflows = append(workflows, entry.Name()) - } - } - sort.Strings(workflows) - writeJSON(w, http.StatusOK, map[string]any{"success": true, "builtIn": workflows, "mine": []string{}, "data": workflows}) -} - -func (s *Server) workflowMeta(w http.ResponseWriter, r *http.Request) { - name := filepath.Base(strings.TrimSpace(r.URL.Query().Get("name"))) - if name == "." || name == "" || !safeRelative(name) { - writeError(w, http.StatusBadRequest, "missing workflow name") - return - } - full, err := s.resolveUnderRoots(name, []string{s.cfg.WorkflowsRoot}) - if err != nil { - writeError(w, http.StatusNotFound, "workflow not found") - return - } - data, err := os.ReadFile(full) - if err != nil { - writeError(w, http.StatusInternalServerError, "workflow could not be read") - return - } - var graph map[string]map[string]any - if json.Unmarshal(data, &graph) != nil { - writeError(w, http.StatusBadRequest, "workflow JSON is invalid") - return - } - videoLength := false - for _, node := range graph { - if classType, _ := node["class_type"].(string); classType == "WanImageToVideo" { - videoLength = true - break - } - } - defaults := map[string]any{} - var videoFPS any - if videoLength { - defaults["videoLength"] = 5 - videoFPS = 16 - } - info, _ := os.Stat(full) - writeJSON(w, http.StatusOK, map[string]any{"success": true, "workflow": name, "graph": graph, "supports": map[string]bool{"videoLength": videoLength}, "defaults": defaults, "videoFps": videoFPS, "data": map[string]any{"name": name, "bytes": infoSize(info), "modifiedAt": infoTime(info)}}) -} - -func (s *Server) myGenerations(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, map[string]any{"items": []any{}, "generations": []any{}}) -} - -func (s *Server) downloadWorkflowResult(w http.ResponseWriter, r *http.Request) { - job, err := s.findWorkflowJob(r.Context(), chi.URLParam(r, "id")) - if err != nil { - writeError(w, http.StatusNotFound, "job not found") - return - } - if job.Status != "completed" { - writeError(w, http.StatusConflict, "job is not complete") - return - } - filename, _ := job.Result["outputFile"].(string) - if !safeRelative(filename) { - writeError(w, http.StatusNotFound, "job result not found") - return - } - carrierNodePath := "/mount/generated/" + urlPath(filename) - if exists, _, _, err := s.probeCarrierNode(r.Context(), carrierNodePath); err != nil || !exists { - writeError(w, http.StatusGone, "job result is no longer available") - return - } - w.Header().Set("Content-Disposition", `attachment; filename="`+filepath.Base(filename)+`"`) - s.proxyCarrierNode(w, r, carrierNodePath) -} - -func scanWorkflowJob(row interface{ Scan(...any) error }) (WorkflowJob, error) { - var job WorkflowJob - var request, result []byte - var errorMessage string - if err := row.Scan(&job.ID, &job.Service, &job.Tool, &job.Status, &job.Progress, &request, &result, &errorMessage, &job.CreatedAt, &job.StartedAt, &job.FinishedAt); err != nil { - return job, err - } - _ = json.Unmarshal(request, &job.Request) - _ = json.Unmarshal(result, &job.Result) - job.Error = errorMessage - return job, nil -} - -func minInt(left, right int) int { - if left < right { - return left - } - return right -} - -func infoTime(info os.FileInfo) any { - if info == nil { - return nil - } - return info.ModTime() -} - -func (s *Server) findWorkflowJob(ctx context.Context, id string) (WorkflowJob, error) { - return scanWorkflowJob(s.db.QueryRow(ctx, `SELECT id, service, tool, status, progress, request, result, COALESCE(error_message, ''), created_at, started_at, finished_at FROM workflow_jobs WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName)) -} - -func randomID() (string, error) { - data := make([]byte, 16) - if _, err := rand.Read(data); err != nil { - return "", err - } - return hex.EncodeToString(data), nil -} - -func mustJSON(value any) []byte { - if value == nil { - return []byte(`{}`) - } - data, err := json.Marshal(value) - if err != nil { - return []byte(`{}`) - } - return data -} - -func inferToolFromPath(value string) string { - for _, tool := range []string{"generator", "downloader", "converter"} { - if strings.Contains(value, tool) { - return tool - } - } - return "workflow" -} - -func validateDownloadURL(raw string) error { - parsed, err := url.Parse(strings.TrimSpace(raw)) - if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" { - return fmt.Errorf("url must be an absolute http(s) URL") - } - if parsed.User != nil { - return fmt.Errorf("URL credentials are not allowed") - } - host := parsed.Hostname() - if ip := net.ParseIP(host); ip != nil && isPrivateIP(ip) { - return fmt.Errorf("private and local download hosts are not allowed") - } - if strings.EqualFold(host, "localhost") || strings.HasSuffix(strings.ToLower(host), ".localhost") || strings.EqualFold(host, "metadata.google.internal") { - return fmt.Errorf("private and local download hosts are not allowed") - } - return nil -} - -func isPrivateIP(ip net.IP) bool { - if ip == nil { - return true - } - if ip.IsLoopback() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsPrivate() { - return true - } - if v4 := ip.To4(); v4 != nil { - ip = v4 - } - private := []*net.IPNet{} - for _, cidr := range []string{"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.168.0.0/16", "198.18.0.0/15", "::1/128", "fc00::/7", "fe80::/10"} { - _, network, _ := net.ParseCIDR(cidr) - private = append(private, network) - } - for _, network := range private { - if network.Contains(ip) { - return true - } - } - return false -} diff --git a/shared/packages/java-backend/README.md b/shared/packages/java-backend/README.md index 00de61c..8d83435 100644 --- a/shared/packages/java-backend/README.md +++ b/shared/packages/java-backend/README.md @@ -9,7 +9,7 @@ Shared account-management, TOTP, admin reset-code, and AuthGuard client primitiv ## How this package is actually consumed -Unlike its `node-backend`/`python-backend` siblings, this package is not published and installed as a dependency. Its real, already-identified consumer - [MegaBasterd](../../../../Forks/MegaBasterd) - instead adds this package's `src/main/java` as an extra source directory of its *own* Maven build, via the `build-helper-maven-plugin` "add-shared-java-auth" execution in `MegaBasterd/pom.xml`, and compiles these `.java` files straight into its own jar. That pom pins ``/`` to `1.8`, which is why every class in this package targets Java 8 and none of them (including `AuthClient`) take on a dependency beyond the JDK - both would break that real build. +Unlike its `node-backend`/`python-backend` siblings, this package is not published and installed as a dependency. Its real, already-identified consumer - [MegaBasterd](../../../../Fork/MegaBasterd) - instead adds this package's `src/main/java` as an extra source directory of its *own* Maven build, via the `build-helper-maven-plugin` "add-shared-java-auth" execution in `MegaBasterd/pom.xml`, and compiles these `.java` files straight into its own jar. That pom pins ``/`` to `1.8`, which is why every class in this package targets Java 8 and none of them (including `AuthClient`) take on a dependency beyond the JDK - both would break that real build. This package's own `pom.xml` exists only so it can be built and tested in isolation during development; it plays no part in how MegaBasterd (or any future consumer that adopts the same source-inclusion approach) actually builds. diff --git a/shared/scripts/sync-consumers.ps1 b/shared/scripts/sync-consumers.ps1 index cdc5aad..352db0e 100644 --- a/shared/scripts/sync-consumers.ps1 +++ b/shared/scripts/sync-consumers.ps1 @@ -23,11 +23,14 @@ function New-ConsumerProject { return [pscustomobject]@{ Path = $Path; Destination = $Destination } } -# Destination defaults to 'shared' (the snapshot folder name most consumers -# use). The engine/media-backend family below mounts the same snapshot at -# 'engine' instead - historically a git submodule, converted to this same -# vendored-copy pattern for consistency and to drop the private-submodule -# checkout auth dependency in CI. +# Destination defaults to 'shared' (the snapshot folder name every consumer +# uses) - originally a git submodule, converted to this vendored-copy pattern +# for consistency and to drop the private-submodule checkout auth dependency +# in CI. The media-family services (CarrierNode, ContentScanner, CraftStudio, +# MediaViewer, MediaKiosk, ModerationHub, ProjectConfigurator) used to mount +# a shared multi-flavor webui/media-backend at a separate 'engine' folder +# instead; each is now its own independent frontend/backend and vendors this +# snapshot the same way as every other consumer below. $consumerProjects = @( New-ConsumerProject 'Original/MediaDesktop' New-ConsumerProject 'Original/AutoCode' @@ -37,20 +40,20 @@ $consumerProjects = @( New-ConsumerProject 'Original/SyncServer' New-ConsumerProject 'Original/UnraidMonitor' New-ConsumerProject 'Original/PubliSafe' - New-ConsumerProject 'Forks/Bitmagnet' - New-ConsumerProject 'Forks/Heretic' + New-ConsumerProject 'Fork/Bitmagnet' + New-ConsumerProject 'Fork/Heretic' New-ConsumerProject 'Original/InfiniteVideo' - New-ConsumerProject 'Forks/MegaBasterd' - New-ConsumerProject 'Forks/HordeWorker' + New-ConsumerProject 'Fork/MegaBasterd' + New-ConsumerProject 'Forks/HordeWorker' # TODO: rename to Fork/HordeWorker once its locked directory can be moved (a long-running process holds it open) New-ConsumerProject 'Original/OutdoorGames' New-ConsumerProject 'Original/KioskDisplay' New-ConsumerProject 'Original/CraftStudio' New-ConsumerProject 'Original/MediaViewer' - New-ConsumerProject 'Central/CarrierNode' - New-ConsumerProject 'Central/ContentScanner' - New-ConsumerProject 'Central/ModerationHub' - New-ConsumerProject 'Central/ProjectConfigurator' - New-ConsumerProject 'Central/AuthGuard' + New-ConsumerProject 'Core/CarrierNode' + New-ConsumerProject 'Core/ContentScanner' + New-ConsumerProject 'Core/ModerationHub' + New-ConsumerProject 'Core/ProjectConfigurator' + New-ConsumerProject 'Core/AuthGuard' ) function Invoke-GitText { @@ -218,14 +221,16 @@ $sourceRepositoryRoot = (Invoke-GitText -WorkingDirectory $sourceRoot -Arguments $sourceRoot = Resolve-FullPath $sourceRepositoryRoot # The workspace root is the ancestor directory that contains both 'Original' -# and 'Forks' (every consumer project lives under one of those). Walk up from -# the shared repo instead of assuming a fixed nesting depth, since shared/ has -# moved before (e.g. Web/shared -> Web/Central/shared) and may move again. +# and 'Fork' (every consumer project lives under one of those, or under +# 'Core' for the central infrastructure services). Walk up from the shared +# repo instead of assuming a fixed nesting depth, since shared/ has moved +# before (e.g. Web/shared -> Web/Central/shared -> Web/Core/shared, with +# 'Forks' renamed to singular 'Fork' at the same time) and may move again. $workspaceRoot = Split-Path -Parent $sourceRoot -while ($workspaceRoot -and -not ((Test-Path -LiteralPath (Join-Path $workspaceRoot 'Original') -PathType Container) -and (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Forks') -PathType Container))) { +while ($workspaceRoot -and -not ((Test-Path -LiteralPath (Join-Path $workspaceRoot 'Original') -PathType Container) -and (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Fork') -PathType Container))) { $parent = Split-Path -Parent $workspaceRoot if (-not $parent -or $parent -eq $workspaceRoot) { - throw "Could not locate the workspace root (a directory containing both 'Original' and 'Forks') above $sourceRoot." + throw "Could not locate the workspace root (a directory containing both 'Original' and 'Fork') above $sourceRoot." } $workspaceRoot = $parent } diff --git a/shared/webui/.prettierignore b/shared/webui/.prettierignore deleted file mode 100644 index 355d563..0000000 --- a/shared/webui/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -.svelte-kit/ -build/ -node_modules/ diff --git a/shared/webui/README.md b/shared/webui/README.md deleted file mode 100644 index a4cbdf3..0000000 --- a/shared/webui/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# Shared media WebUI - -The browser-facing services in this workspace's shared media family share one SvelteKit application. The -service variant is selected at build time with `VITE_MEDIA_APP` and uses the same -Svelte 5, Tailwind CSS v4, bits-ui-compatible component patterns, Lucide icons, -semantic tokens, responsive shell, and static adapter as the other projects. - -From this directory: - -```sh -npm install -npm run build:all -``` - -`build:all` creates ignored `.webui/` directories in each service. Docker builds -compile the requested variant in a dedicated frontend stage and set -`MEDIA_UI_DIR` to the generated output. The existing JSON, media, WebSocket, -Socket.IO, and service-to-service routes remain owned by each backend. diff --git a/shared/webui/eslint.config.js b/shared/webui/eslint.config.js deleted file mode 100644 index bd03842..0000000 --- a/shared/webui/eslint.config.js +++ /dev/null @@ -1,62 +0,0 @@ -import js from '@eslint/js' -import globals from 'globals' -import svelte from 'eslint-plugin-svelte' -import prettierConfig from 'eslint-config-prettier' -import tseslint from 'typescript-eslint' - -export default tseslint.config( - { ignores: ['build', '.svelte-kit', 'node_modules'] }, - js.configs.recommended, - ...tseslint.configs.recommended, - ...svelte.configs.recommended, - { - files: ['**/*.ts', '**/*.svelte'], - languageOptions: { - ecmaVersion: 2022, - globals: { - ...globals.browser, - __MEDIA_APP__: 'readonly', - __FRONTEND_TECH_STACK__: 'readonly', - }, - }, - rules: { - 'no-console': 'error', - '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }], - }, - }, - { - files: ['**/*.{js,mjs,cjs}'], - languageOptions: { - ecmaVersion: 2022, - globals: globals.node, - }, - rules: {}, - }, - { - files: ['**/*.svelte'], - languageOptions: { - parserOptions: { - parser: tseslint.parser, - extraFileExtensions: ['.svelte'], - }, - }, - rules: { - 'prefer-const': 'off', - 'svelte/no-navigation-without-resolve': 'off', - }, - }, - prettierConfig, - ...svelte.configs.prettier, - { - files: ['**/*.svelte.ts'], - languageOptions: { - parser: tseslint.parser, - ecmaVersion: 2022, - globals: { - ...globals.browser, - __MEDIA_APP__: 'readonly', - __FRONTEND_TECH_STACK__: 'readonly', - }, - }, - }, -) diff --git a/shared/webui/package.json b/shared/webui/package.json deleted file mode 100644 index a15a01f..0000000 --- a/shared/webui/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "name": "@gabriel20xx/webui", - "private": true, - "version": "1.0.0", - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "build:all": "node scripts/build-all.mjs", - "build:viewer": "node scripts/build-all.mjs viewer", - "build:craftstudio": "node scripts/build-all.mjs craftstudio", - "build:contentscanner": "node scripts/build-all.mjs contentscanner", - "build:config": "node scripts/build-all.mjs config", - "build:moderator": "node scripts/build-all.mjs moderator", - "build:kiosk": "node scripts/build-all.mjs kiosk", - "build:carriernode": "node scripts/build-all.mjs carriernode", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", - "lint": "eslint .", - "format": "prettier --write .", - "format:check": "prettier --check ." - }, - "dependencies": { - "@gabriel20xx/web-ui": "file:../shared/packages/web-ui", - "@lucide/svelte": "1.28.0", - "@tanstack/svelte-query": "6.1.38", - "bits-ui": "2.18.1", - "class-variance-authority": "0.7.1", - "clsx": "2.1.1", - "tailwind-merge": "3.6.0" - }, - "devDependencies": { - "@eslint/js": "10.0.1", - "@sveltejs/adapter-static": "3.0.10", - "@sveltejs/kit": "2.70.2", - "@sveltejs/vite-plugin-svelte": "7.2.0", - "@tailwindcss/vite": "4.3.3", - "@types/node": "26.1.2", - "eslint": "10.8.0", - "eslint-config-prettier": "10.1.8", - "eslint-plugin-svelte": "3.22.0", - "globals": "17.9.0", - "prettier": "3.9.6", - "prettier-plugin-svelte": "4.1.1", - "svelte": "5.56.8", - "svelte-check": "4.7.4", - "tailwindcss": "4.3.3", - "tw-animate-css": "1.4.0", - "typescript": "6.0.3", - "typescript-eslint": "8.65.0", - "vite": "8.2.0" - } -} diff --git a/shared/webui/prettier.config.js b/shared/webui/prettier.config.js deleted file mode 100644 index 817a6f6..0000000 --- a/shared/webui/prettier.config.js +++ /dev/null @@ -1,9 +0,0 @@ -/** @type {import('prettier').Config} */ -export default { - plugins: ['prettier-plugin-svelte'], - semi: false, - singleQuote: true, - trailingComma: 'all', - printWidth: 120, - svelteSortOrder: 'options-scripts-markup-styles', -} diff --git a/shared/webui/project-icons.json b/shared/webui/project-icons.json deleted file mode 100644 index fcd323f..0000000 --- a/shared/webui/project-icons.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "viewer": { "name": "MediaViewer", "icon": "play" }, - "craftstudio": { "name": "CraftStudio", "icon": "wand-sparkles" }, - "contentscanner": { "name": "ContentScanner", "icon": "scan-search" }, - "config": { "name": "ProjectConfigurator", "icon": "settings-2" }, - "moderator": { "name": "MediaModerator", "icon": "shield-check" }, - "kiosk": { "name": "MediaKiosk", "icon": "image" }, - "carriernode": { "name": "CarrierNode", "icon": "server" } -} diff --git a/shared/webui/scripts/build-all.mjs b/shared/webui/scripts/build-all.mjs deleted file mode 100644 index 9961926..0000000 --- a/shared/webui/scripts/build-all.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import { cp, mkdir, rm } from 'node:fs/promises' -import path from 'node:path' -import { spawn } from 'node:child_process' - -const webUiDir = path.resolve(import.meta.dirname, '..') -const enginesDir = path.resolve(webUiDir, '..') -const targets = { - viewer: 'MediaViewer', - craftstudio: 'CraftStudio', - contentscanner: 'ContentScanner', - config: 'ProjectConfigurator', - moderator: 'MediaModerator', - kiosk: 'MediaKiosk', - carriernode: 'CarrierNode', -} - -const requested = process.argv.slice(2) -const apps = requested.length ? requested : Object.keys(targets) -const unknown = apps.filter((app) => !targets[app]) -if (unknown.length) { - console.error(`Unknown shared WebUI app: ${unknown.join(', ')}`) - process.exit(1) -} - -function runBuild(app) { - return new Promise((resolve, reject) => { - const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', 'build'], { - cwd: webUiDir, - env: { ...process.env, VITE_MEDIA_APP: app }, - shell: process.platform === 'win32', - stdio: 'inherit', - }) - child.on('error', reject) - child.on('exit', (code) => { - if (code === 0) resolve() - else reject(new Error(`WebUI build failed for ${app} with exit code ${code}`)) - }) - }) -} - -for (const app of apps) { - await runBuild(app) - const target = path.join(enginesDir, targets[app], '.webui') - await rm(target, { recursive: true, force: true }) - await mkdir(target, { recursive: true }) - await cp(path.join(webUiDir, 'build'), target, { recursive: true }) - console.log(`[webui] ${app} -> ${path.relative(enginesDir, target)}`) -} diff --git a/shared/webui/scripts/project-favicon.mjs b/shared/webui/scripts/project-favicon.mjs deleted file mode 100644 index 5a32e00..0000000 --- a/shared/webui/scripts/project-favicon.mjs +++ /dev/null @@ -1,49 +0,0 @@ -import fs from 'node:fs' -import path from 'node:path' - -const webUiDir = path.resolve(import.meta.dirname, '..') - -/** @typedef {{ name: string, icon: string }} ProjectIconConfig */ -/** @typedef {[string, Record]} IconNode */ - -/** @type {Record} */ -const projectIcons = JSON.parse(fs.readFileSync(path.join(webUiDir, 'project-icons.json'), 'utf8')) -const lucideIconsDir = path.join(webUiDir, 'node_modules', '@lucide', 'svelte', 'dist', 'icons') - -/** @param {unknown} value */ -function escapeAttribute(value) { - return String(value) - .replaceAll('&', '&') - .replaceAll('"', '"') - .replaceAll('<', '<') - .replaceAll('>', '>') -} - -/** @param {string} iconName @returns {IconNode[]} */ -function getIconNode(iconName) { - const source = fs.readFileSync(path.join(lucideIconsDir, `${iconName}.svelte`), 'utf8') - const match = source.match(/const iconNode = (\[[\s\S]*?\]);/) - if (!match) throw new Error(`Unable to read Lucide icon node for ${iconName}`) - return /** @type {IconNode[]} */ (JSON.parse(match[1])) -} - -/** @param {IconNode} node */ -function renderIconNode([tag, attributes]) { - const renderedAttributes = Object.entries(attributes) - .map(([name, value]) => `${name}="${escapeAttribute(value)}"`) - .join(' ') - return ` <${tag} ${renderedAttributes} />` -} - -/** @param {string} appId */ -export function renderProjectFavicon(appId) { - const project = projectIcons[appId] - if (!project) throw new Error(`Unknown project: ${appId}`) - - const iconNode = getIconNode(project.icon) - return ` - ${escapeAttribute(project.name)} -${iconNode.map(renderIconNode).join('\n')} - -` -} diff --git a/shared/webui/src/app.css b/shared/webui/src/app.css deleted file mode 100644 index 31eed21..0000000 --- a/shared/webui/src/app.css +++ /dev/null @@ -1,167 +0,0 @@ -@import 'tailwindcss'; -@import 'tw-animate-css'; - -:root, -[data-theme='dark'] { - --color-bg: #0b0f14; - --color-surface: #131820; - --color-surface-hover: #1c2330; - --color-border: #2a3140; - --color-fg: #e6e9ef; - --color-muted-fg: #8b95a5; - --color-primary: #5b8cff; - --color-primary-fg: #06122b; - --color-secondary: #2563eb; - --color-secondary-fg: #ffffff; - --color-accent: #5b8cff; - --color-accent-fg: #06122b; - --color-danger: #ef4444; - --color-danger-fg: #450a0a; - --color-success: #22c55e; - --color-success-fg: #052e14; - --color-warning: #f59e0b; - --color-warning-fg: #2a1a00; - --color-ring: #5b8cff; - color-scheme: dark; -} - -[data-theme='light'] { - --color-bg: #f5f7fb; - --color-surface: #ffffff; - --color-surface-hover: #eef1f7; - --color-border: #dbe1ea; - --color-fg: #10151f; - --color-muted-fg: #5b6472; - --color-primary: #2f5fe0; - --color-primary-fg: #ffffff; - --color-secondary: #1e3fae; - --color-secondary-fg: #ffffff; - --color-accent: #2f5fe0; - --color-accent-fg: #ffffff; - --color-danger: #dc2626; - --color-danger-fg: #ffffff; - --color-success: #059669; - --color-success-fg: #ffffff; - --color-warning: #b45309; - --color-warning-fg: #ffffff; - --color-ring: #2f5fe0; - color-scheme: light; -} - -@media (prefers-color-scheme: light) { - :root:not([data-theme]) { - --color-bg: #f5f7fb; - --color-surface: #ffffff; - --color-surface-hover: #eef1f7; - --color-border: #dbe1ea; - --color-fg: #10151f; - --color-muted-fg: #5b6472; - --color-primary: #2f5fe0; - --color-primary-fg: #ffffff; - --color-secondary: #1e3fae; - --color-secondary-fg: #ffffff; - --color-accent: #2f5fe0; - --color-accent-fg: #ffffff; - --color-danger: #dc2626; - --color-danger-fg: #ffffff; - --color-success: #059669; - --color-success-fg: #ffffff; - --color-warning: #b45309; - --color-warning-fg: #ffffff; - --color-ring: #2f5fe0; - color-scheme: light; - } -} - -@theme inline { - --color-bg: var(--color-bg); - --color-surface: var(--color-surface); - --color-surface-hover: var(--color-surface-hover); - --color-border: var(--color-border); - --color-fg: var(--color-fg); - --color-muted-fg: var(--color-muted-fg); - --color-primary: var(--color-primary); - --color-primary-fg: var(--color-primary-fg); - --color-secondary: var(--color-secondary); - --color-secondary-fg: var(--color-secondary-fg); - --color-accent: var(--color-accent); - --color-accent-fg: var(--color-accent-fg); - --color-danger: var(--color-danger); - --color-danger-fg: var(--color-danger-fg); - --color-success: var(--color-success); - --color-success-fg: var(--color-success-fg); - --color-warning: var(--color-warning); - --color-warning-fg: var(--color-warning-fg); - --color-ring: var(--color-ring); - --font-sans: 'Inter', ui-sans-serif, system-ui, -apple-system, sans-serif; - --font-mono: 'JetBrains Mono', 'Fira Code', Consolas, monospace; -} - -html, -body { - min-height: 100%; -} - -body { - margin: 0; - background: var(--color-bg); - color: var(--color-fg); - font-family: var(--font-sans); - font-size: 14px; - line-height: 1.5; - transition: - background-color 150ms ease, - color 150ms ease; -} - -button, -input, -select, -textarea { - font: inherit; -} - -.field { - width: 100%; - height: 2.5rem; - border: 1px solid var(--color-border); - border-radius: 0.375rem; - background: var(--color-bg); - padding: 0 0.75rem; - color: var(--color-fg); - outline: none; -} - -.field:focus-visible { - box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-ring) 35%, transparent); -} - -* { - scrollbar-width: thin; - scrollbar-color: var(--color-border) transparent; -} - -::selection { - background: var(--color-primary); - color: var(--color-primary-fg); -} - -.media-shimmer { - background: linear-gradient( - 90deg, - var(--color-surface) 25%, - var(--color-surface-hover) 50%, - var(--color-surface) 75% - ); - background-size: 200% 100%; - animation: media-shimmer 1.5s infinite; -} - -@keyframes media-shimmer { - 0% { - background-position: -200% 0; - } - 100% { - background-position: 200% 0; - } -} diff --git a/shared/webui/src/app.d.ts b/shared/webui/src/app.d.ts deleted file mode 100644 index 3aa853e..0000000 --- a/shared/webui/src/app.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const __MEDIA_APP__: string -declare const __FRONTEND_TECH_STACK__: Array<{ name: string; version: string }> diff --git a/shared/webui/src/app.html b/shared/webui/src/app.html deleted file mode 100644 index 3fffd23..0000000 --- a/shared/webui/src/app.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - Loading… - %sveltekit.head% - - -
%sveltekit.body%
- - diff --git a/shared/webui/src/lib/api.ts b/shared/webui/src/lib/api.ts deleted file mode 100644 index 75f8660..0000000 --- a/shared/webui/src/lib/api.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { ApiError } from './types' - -export class ApiRequestError extends Error { - status: number - payload: ApiError | null - - constructor(message: string, status: number, payload: ApiError | null = null) { - super(message) - this.name = 'ApiRequestError' - this.status = status - this.payload = payload - } -} - -export async function request(path: string, init: RequestInit = {}): Promise { - const response = await fetch(path, { - credentials: 'include', - ...init, - headers: { - ...(init.body && !(init.body instanceof FormData) ? { 'content-type': 'application/json' } : {}), - ...(init.headers || {}), - }, - }) - - const contentType = response.headers.get('content-type') || '' - const payload = contentType.includes('json') ? await response.json().catch(() => null) : null - if (!response.ok) { - const error = payload as ApiError | null - throw new ApiRequestError( - error?.error || error?.message || error?.detail || response.statusText, - response.status, - error, - ) - } - return (payload ?? (await response.text())) as T -} - -export function get(path: string) { - return request(path) -} - -export function post(path: string, body?: unknown) { - return request(path, { - method: 'POST', - ...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }), - }) -} - -export function put(path: string, body: unknown) { - return request(path, { method: 'PUT', body: JSON.stringify(body) }) -} - -export function del(path: string) { - return request(path, { method: 'DELETE' }) -} diff --git a/shared/webui/src/lib/app-config.ts b/shared/webui/src/lib/app-config.ts deleted file mode 100644 index 207b6a4..0000000 --- a/shared/webui/src/lib/app-config.ts +++ /dev/null @@ -1,256 +0,0 @@ -import projectIcons from '../../project-icons.json' -import type { AppConfig, AppId } from './types' -import type { ProjectIconName } from './types' - -function projectIcon(id: AppId): ProjectIconName { - return projectIcons[id].icon as ProjectIconName -} - -const configs: Record = { - viewer: { - id: 'viewer', - name: 'MediaViewer', - icon: projectIcon('viewer'), - eyebrow: 'Immersive media library', - description: 'Browse, search, and play your media collection from one calm workspace.', - nav: [ - { - label: 'Library', - panel: 'library', - path: '/', - icon: 'gallery-horizontal-end', - description: 'Browse, search, and play your media collection.', - }, - { - label: 'Feed', - panel: 'view', - path: '/feed', - icon: 'monitor-play', - description: 'View a focused stream of media from your collection.', - }, - { - label: 'Tags', - panel: 'tags', - path: '/tags', - icon: 'tags', - description: 'Explore media by tags and related items.', - }, - { - label: 'Playlists', - panel: 'playlists', - path: '/playlists', - icon: 'list-video', - description: 'Organize media into playlists for convenient playback.', - }, - ], - }, - craftstudio: { - id: 'craftstudio', - name: 'CraftStudio', - icon: projectIcon('craftstudio'), - eyebrow: 'Media workflow studio', - description: 'Generate, download, convert, and schedule media jobs in one place.', - nav: [ - { - label: 'Generator', - panel: 'generator', - path: '/', - icon: 'wand-sparkles', - description: 'Generate new media and monitor generation jobs.', - }, - { - label: 'Downloader', - panel: 'downloader', - path: '/downloader', - icon: 'cloud-download', - description: 'Download media from configured sources.', - }, - { - label: 'Converter', - panel: 'converter', - path: '/converter', - icon: 'refresh-cw', - description: 'Convert media between supported formats.', - }, - { - label: 'Schedules', - panel: 'schedules', - path: '/schedules', - icon: 'activity', - description: 'Schedule recurring media tools and maintenance jobs.', - }, - { - label: 'Library', - panel: 'library', - path: '/library', - icon: 'image', - description: 'Inspect media produced by the tools workspace.', - }, - ], - }, - contentscanner: { - id: 'contentscanner', - name: 'ContentScanner', - icon: projectIcon('contentscanner'), - eyebrow: 'Processing operations', - description: 'Monitor discovery and define per-type processing pipelines and automation queues.', - nav: [ - { - label: 'Dashboard', - panel: 'dashboard', - path: '/', - icon: 'layout-dashboard', - description: 'Monitor processing queues, progress, and recent history.', - }, - { - label: 'Discover', - panel: 'discover', - path: '/discover', - icon: 'folder-open', - description: 'Discover and register media from configured locations.', - }, - { - label: 'Images', - panel: 'images', - path: '/images', - icon: 'image', - description: 'Define the image pipeline: thumbnails, metadata extraction, and AI analysis.', - }, - { - label: 'Videos', - panel: 'videos', - path: '/videos', - icon: 'monitor-play', - description: 'Define the video pipeline: thumbnails, metadata extraction, and AI analysis.', - }, - { - label: 'Audios', - panel: 'audios', - path: '/audios', - icon: 'audio-lines', - description: 'Define the audio pipeline: thumbnails, metadata extraction, and AI analysis.', - }, - { - label: 'Funscripts', - panel: 'funscripts', - path: '/funscripts', - icon: 'scroll-text', - description: 'Define the funscript pipeline: thumbnails, metadata extraction, and AI analysis.', - }, - { - label: 'Schedules', - panel: 'schedules', - path: '/schedules', - icon: 'activity', - description: 'Configure recurring analyzer operations.', - }, - ], - }, - config: { - id: 'config', - name: 'ProjectConfigurator', - icon: projectIcon('config'), - eyebrow: 'Platform configuration', - description: 'Connect central, main, and third-party services and configure their mounts.', - nav: [ - { - label: 'Projects', - panel: 'projects', - path: '/', - icon: 'hard-drive', - description: 'Connect central, main, and third-party services and configure their mounts.', - }, - ], - }, - moderator: { - id: 'moderator', - name: 'MediaModerator', - icon: projectIcon('moderator'), - eyebrow: 'Administration and safety', - description: 'Review users, media, tags, visibility, and platform health.', - nav: [ - { - label: 'Dashboard', - panel: 'dashboard', - path: '/', - icon: 'bar-chart-3', - description: 'Review moderation activity and platform health.', - }, - { - label: 'Users', - panel: 'users', - path: '/users', - icon: 'users', - description: 'Manage accounts, roles, and access.', - }, - { - label: 'Media', - panel: 'media', - path: '/media', - icon: 'shield-check', - description: 'Review media visibility and moderation status.', - }, - ], - }, - kiosk: { - id: 'kiosk', - name: 'MediaKiosk', - icon: projectIcon('kiosk'), - eyebrow: 'Ambient display', - description: 'Show the latest collection output in a focused, full-screen canvas.', - nav: [ - { - label: 'Kiosk', - panel: 'kiosk', - path: '/', - icon: 'monitor-play', - description: 'Show the latest collection output in a focused display.', - }, - ], - }, - carriernode: { - id: 'carriernode', - name: 'CarrierNode', - icon: projectIcon('carriernode'), - eyebrow: 'Storage and delivery', - description: 'Inspect mounts, file activity, bandwidth, and media delivery health.', - nav: [ - { - label: 'Overview', - panel: 'overview', - path: '/', - icon: 'server', - description: 'Inspect storage, delivery, and service health.', - }, - { - label: 'Files', - panel: 'files', - path: '/files', - icon: 'folder-open', - description: 'Review recent files and media activity.', - }, - ], - }, -} - -export function getAppConfig(id: string): AppConfig { - return configs[(id as AppId) in configs ? (id as AppId) : 'viewer'] -} - -function normalizePathname(pathname: string): string { - const normalized = String(pathname || '/').replace(/\/+$/, '') - return normalized || '/' -} - -export function getPanelForPath(app: AppConfig, pathname: string): string { - const normalizedPath = normalizePathname(pathname) - const matchingItem = app.nav.find((item) => { - if (item.path === '/') return normalizedPath === '/' - return normalizedPath === item.path || normalizedPath.startsWith(`${item.path}/`) - }) - return matchingItem?.panel || app.nav[0]?.panel || '' -} - -export function getPathForPanel(app: AppConfig, panel: string): string { - return app.nav.find((item) => item.panel === panel)?.path || app.nav[0]?.path || '/' -} diff --git a/shared/webui/src/lib/components/AppShell.svelte b/shared/webui/src/lib/components/AppShell.svelte deleted file mode 100644 index 78d95eb..0000000 --- a/shared/webui/src/lib/components/AppShell.svelte +++ /dev/null @@ -1,232 +0,0 @@ - - -{#if auth.loading || auth.error || auth.setupRequired || (auth.authRequired && !auth.user)} - -{:else} -
- - -
- -
- - {@render children?.()} -
-
-{/if} - - - - {#snippet icon()} - - {/snippet} - - - - - diff --git a/shared/webui/src/lib/components/AuthPage.svelte b/shared/webui/src/lib/components/AuthPage.svelte deleted file mode 100644 index 17b0189..0000000 --- a/shared/webui/src/lib/components/AuthPage.svelte +++ /dev/null @@ -1,22 +0,0 @@ - - - diff --git a/shared/webui/src/lib/components/ContentScannerHistory.svelte b/shared/webui/src/lib/components/ContentScannerHistory.svelte deleted file mode 100644 index b8dfbf8..0000000 --- a/shared/webui/src/lib/components/ContentScannerHistory.svelte +++ /dev/null @@ -1,207 +0,0 @@ - - - - -
- {#if !mediaType} - - {/if} - -
- {#if error} -

{error}

- {/if} - {#if loading} -

Loading history…

- {:else if entries.length === 0} - - {:else} -
- {#each entries as entry, index (String(entry.id || entry.file_path || index))} - {@const name = firstValue(entry, ['file_name', 'fileName', 'file', 'type', 'action'], 'Processed element')} - {@const path = firstValue(entry, ['file_path', 'filePath', 'path'], '')} - {@const entryMediaType = firstValue(entry, ['media_type', 'mediaType', 'type'], '')} - {@const status = firstValue(entry, ['status', 'state'], 'recorded')} - {@const progress = firstValue(entry, ['progress'], '')} - {@const timestamp = firstValue( - entry, - ['finished_at', 'finishedAt', 'created_at', 'createdAt', 'queued_at', 'queuedAt', 'timestamp'], - '', - )} - {@const message = firstValue(entry, ['error', 'error_message', 'message'], '')} -
-
-
-

{name}

- {#if path}

{path}

{/if} -
- {status} -
-
- {#if entryMediaType}{entryMediaType}{/if} - {#if progress}{progress}% complete{/if} - {#if timestamp}{timestamp}{/if} -
- {#if message}

{message}

{/if} -
- {/each} -
-
-

Showing {entries.length} of {total.toLocaleString()}

-
- -
-
- {/if} -
diff --git a/shared/webui/src/lib/components/ContentScannerLiveStatus.svelte b/shared/webui/src/lib/components/ContentScannerLiveStatus.svelte deleted file mode 100644 index b166972..0000000 --- a/shared/webui/src/lib/components/ContentScannerLiveStatus.svelte +++ /dev/null @@ -1,208 +0,0 @@ - - - - - {#if loading} -

Loading status…

- {:else} -
-
- State -
- {stateLabel} - {#if canStop} - - {/if} -
-
-
- Pending - {queued} -
-
- Processing - {processing} -
-
- Worker - {worker} -
-
- Current item - {current} -
- {#if total > 0} -
-
- Progress - {progressCompleted} / {total} -
-
-
-
-
- {:else if running && progressCompleted > 0} -
-
- Progress - {progressCompleted} processed -
-
-
-
-
- {/if} -
- Last update - {lastUpdate} -
- {#if lastError} -

{lastError}

- {/if} -
- {/if} -
diff --git a/shared/webui/src/lib/components/ContentScannerPipelineBreakdown.svelte b/shared/webui/src/lib/components/ContentScannerPipelineBreakdown.svelte deleted file mode 100644 index 9d946c2..0000000 --- a/shared/webui/src/lib/components/ContentScannerPipelineBreakdown.svelte +++ /dev/null @@ -1,84 +0,0 @@ - - - - -
- {#each mediaTypes as mediaType (mediaType.key)} -
-
-

{mediaType.label}

- {total(mediaType.key).toLocaleString()} total -
-
- Process stage - Pending - Done - Errors - {#each stagesFor(mediaType.key) as stage (stage.key)} - {stage.label} - {count(stage.key, mediaType.key, 'queued')} - {count(stage.key, mediaType.key, 'completed')} - {count(stage.key, mediaType.key, 'errors')} - {/each} -
-
- {/each} -
-
diff --git a/shared/webui/src/lib/components/PipelineFlowDiagram.svelte b/shared/webui/src/lib/components/PipelineFlowDiagram.svelte deleted file mode 100644 index 31de7f9..0000000 --- a/shared/webui/src/lib/components/PipelineFlowDiagram.svelte +++ /dev/null @@ -1,352 +0,0 @@ - - -{#snippet connector(active: boolean)} -
- - -
-{/snippet} - -{#snippet toggle(enabled: boolean, onToggle: (value: boolean) => void, toggleLabel: string)} - -{/snippet} - -{#snippet detailsToggle(open: boolean, onClick: () => void)} - -{/snippet} - -{#snippet statusGrid(status: StageStatus, stage: StageKey, onRetry: () => void)} - {@const panel = errorPanels[stage]} -
-
-

{status.pending}

-

Pending

-
-
-

{status.processing}

-

Processing

-
-
-

{status.processed}

-

Processed

-
-
- {#if status.errors > 0} -
- {status.errors} error{status.errors === 1 ? '' : 's'} -
- - -
-
- {#if panel?.open} -
- {#if panel.loading} -

Loading errors…

- {:else if panel.items.length === 0} -

No recent error text available.

- {:else} - {#each panel.items as item (item.filePath)} -

{item.filePath}: {item.error}

- {/each} - {/if} -
- {/if} - {/if} -{/snippet} - -
-
- -

{discovered}

-

{discoveredLabel} discovered

-
- - {@render connector(metadataStatus.active)} - -
-
-
- - Metadata -
- {#if metadataStatus.active} - Active - {:else} - Idle - {/if} -
-

{metadataDescription}

- {@render detailsToggle(metadataDetailsOpen, () => (metadataDetailsOpen = !metadataDetailsOpen))} - {#if metadataDetailsOpen} -

{metadataDetails}

- {/if} - {@render statusGrid(metadataStatus, 'metadata', () => onRetryErrors('metadata'))} - {@render toggle(metadataEnabled, onToggleMetadata, 'Enabled')} -
- - {#if thumbnailsSupported} - {@render connector(thumbnailsStatus.active)} - -
-
-
- - Thumbnails -
- {#if thumbnailsStatus.active} - Active - {:else} - Idle - {/if} -
-

{thumbnailsDescription}

- {@render detailsToggle(thumbnailsDetailsOpen, () => (thumbnailsDetailsOpen = !thumbnailsDetailsOpen))} - {#if thumbnailsDetailsOpen} -

{thumbnailsDetails}

- {/if} - {@render statusGrid(thumbnailsStatus, 'thumbnails', () => onRetryErrors('thumbnails'))} - {@render toggle(thumbnailsEnabled, onToggleThumbnails, 'Enabled')} -
- {/if} - - {#if showAiAnalysis} - {@render connector(analysisStatus.active)} - -
-
-
- - AI analysis -
- {#if analysisStatus.active} - Active - {:else} - Idle - {/if} -
-

- {hasAiModel - ? 'Toggle a task on, then choose which model handles it. Runs as part of the pipeline alongside metadata and thumbnails.' - : 'No AI model is available for this media type yet.'} -

- {#if hasAiModel} - {@render detailsToggle(aiDetailsOpen, () => (aiDetailsOpen = !aiDetailsOpen))} - {#if aiDetailsOpen} -
- {#each aiStages as stage (stage.key)} -

{stage.label}: {MODEL_DETAILS[stage.model] ?? 'No description available for this model.'}

- {/each} -
- {/if} - {/if} -
- {#each aiStages as stage (stage.key)} -
-
- {stage.label} - - onToggleStage(stage.key, (event.currentTarget as HTMLInputElement).checked)} - /> - - -
- -
- {/each} -
- {#if hasAiModel} - {@render statusGrid(analysisStatus, 'analyze', () => onRetryErrors('analyze'))} - {/if} -
- {/if} -
diff --git a/shared/webui/src/lib/components/ProjectIcon.svelte b/shared/webui/src/lib/components/ProjectIcon.svelte deleted file mode 100644 index 13c0513..0000000 --- a/shared/webui/src/lib/components/ProjectIcon.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - -