From acde180086ed07a8703ebb5701fd46ad099a80ab Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Mon, 31 Aug 2026 22:06:29 +0200 Subject: [PATCH] Fold MediaEngine (media-backend, media-webui) into this repo Per owner decision: MediaEngine (the Media product family's Go backend and SvelteKit frontend, previously its own repo referenced by 7 thin service repos via git submodule) is folded directly into shared/ as media-backend/ and media-webui/, rather than staying separate. media-backend/go.mod's replace directive now points at ../backend (a true sibling within this repo) instead of a vendored ../shared/backend copy, since there's no more nested vendoring - it's the real thing. Also moved MediaEngine's own CI (media-backend-lint.yml, media-backend-tests.yml) and dev tooling scripts (scripts/media/*, audit/lint/enforce scripts for the media-backend+media-webui content), fixing their path assumptions for the new layout, and dropped scripts/media/sync-shared.mjs (confirmed dead code, and now doubly obsolete since there's no more vendored shared/ subfolder for it to check). Added media:* script aliases to package.json for the moved tooling, namespaced to avoid colliding with this repo's own scripts. Also fixed sync-consumers.ps1's workspace-root resolution to walk up until it finds a directory containing both Original/ and Forks/, instead of assuming shared/ is always a direct child of the workspace root - it broke when shared/ moved from Web/shared to Web/Central/shared earlier in this same restructuring. Removed the now-obsolete Original/MediaEngine entry from its consumer list. Co-Authored-By: Claude Sonnet 5 --- .github/workflows/media-backend-lint.yml | 32 + .github/workflows/media-backend-tests.yml | 32 + backend/README.md | 2 + backend/authclient/client.go | 177 ++ backend/logshipper/shipper.go | 438 ++++ media-backend/.env.example | 22 + media-backend/README.md | 31 + media-backend/cmd/mediacollectiond/main.go | 42 + media-backend/go.mod | 21 + media-backend/go.sum | 32 + media-backend/internal/auth/auth.go | 956 ++++++++ media-backend/internal/auth/auth_test.go | 28 + media-backend/internal/config/config.go | 237 ++ media-backend/internal/config/config_test.go | 43 + media-backend/internal/database/database.go | 55 + .../database/migrations/001_initial.sql | 321 +++ .../internal/server/admin_storage.go | 1128 +++++++++ media-backend/internal/server/analyzer.go | 2182 +++++++++++++++++ media-backend/internal/server/analyzer_ai.go | 710 ++++++ .../internal/server/analyzer_schedule.go | 139 ++ media-backend/internal/server/kiosk.go | 195 ++ media-backend/internal/server/media.go | 1078 ++++++++ media-backend/internal/server/path_test.go | 83 + .../internal/server/servant_client.go | 331 +++ media-backend/internal/server/server.go | 433 ++++ media-backend/internal/server/sync.go | 541 ++++ media-backend/internal/server/workflows.go | 1005 ++++++++ media-webui/.prettierignore | 3 + media-webui/README.md | 18 + media-webui/eslint.config.js | 62 + media-webui/package.json | 53 + media-webui/prettier.config.js | 9 + media-webui/project-icons.json | 10 + media-webui/scripts/build-all.mjs | 49 + media-webui/scripts/project-favicon.mjs | 49 + media-webui/src/app.css | 167 ++ media-webui/src/app.d.ts | 2 + media-webui/src/app.html | 14 + media-webui/src/lib/api.ts | 55 + media-webui/src/lib/app-config.ts | 286 +++ .../src/lib/components/AnalyzerHistory.svelte | 211 ++ .../lib/components/AnalyzerLiveStatus.svelte | 212 ++ .../AnalyzerPipelineBreakdown.svelte | 85 + .../src/lib/components/AppShell.svelte | 292 +++ .../src/lib/components/AuthPage.svelte | 43 + .../src/lib/components/EmptyState.svelte | 14 + .../lib/components/PipelineFlowDiagram.svelte | 352 +++ .../src/lib/components/ProjectIcon.svelte | 20 + .../src/lib/components/SectionTitle.svelte | 10 + .../src/lib/components/SettingsDialog.svelte | 97 + .../src/lib/components/StatusDialog.svelte | 102 + .../src/lib/components/StatusWidget.svelte | 97 + .../src/lib/components/WorkspacePage.svelte | 87 + .../src/lib/components/ui/badge.svelte | 32 + .../src/lib/components/ui/button.svelte | 43 + media-webui/src/lib/components/ui/card.svelte | 14 + .../src/lib/components/ui/metric.svelte | 32 + .../src/lib/features/AboutWorkspace.svelte | 5 + .../src/lib/features/AnalyzerWorkspace.svelte | 626 +++++ .../src/lib/features/ConfigWorkspace.svelte | 1394 +++++++++++ .../src/lib/features/DesktopWorkspace.svelte | 99 + .../src/lib/features/FeedWorkspace.svelte | 116 + .../src/lib/features/KioskWorkspace.svelte | 231 ++ .../src/lib/features/MediaTypePipeline.svelte | 490 ++++ .../lib/features/ModeratorWorkspace.svelte | 502 ++++ .../src/lib/features/ServantWorkspace.svelte | 184 ++ .../src/lib/features/TagsWorkspace.svelte | 270 ++ .../src/lib/features/ToolsWorkspace.svelte | 472 ++++ media-webui/src/lib/features/VideoPage.svelte | 1059 ++++++++ .../src/lib/features/ViewerWorkspace.svelte | 631 +++++ .../features/about/TechStackSection.svelte | 76 + media-webui/src/lib/language.svelte.ts | 63 + media-webui/src/lib/status.ts | 17 + .../src/lib/stores/page-actions.svelte.ts | 6 + media-webui/src/lib/theme.svelte.ts | 84 + media-webui/src/lib/types.ts | 74 + media-webui/src/lib/utils/cn.ts | 6 + media-webui/src/routes/+layout.svelte | 16 + media-webui/src/routes/+page.svelte | 5 + media-webui/src/routes/[...path]/+page.svelte | 5 + media-webui/static/favicon.svg | 4 + media-webui/svelte.config.js | 10 + media-webui/tsconfig.json | 14 + media-webui/vite.config.ts | 58 + package.json | 15 +- scripts/media/audit-html-js.mjs | 29 + scripts/media/audit-inline-layout.mjs | 89 + scripts/media/clean-test-artifacts.mjs | 153 ++ scripts/media/enforce-design-system-css.mjs | 117 + scripts/media/enforce-js-mapping.mjs | 129 + scripts/media/enforce-no-skipped-tests.mjs | 102 + scripts/media/inspect-vitest-exports.mjs | 3 + scripts/media/lint-all-json.mjs | 99 + scripts/media/lint-all.mjs | 112 + scripts/media/list-skipped-tests.mjs | 104 + scripts/media/report-test-timings.mjs | 47 + scripts/media/simulate-category-removal.mjs | 5 + scripts/media/upgrade-deps.mjs | 142 ++ scripts/sync-consumers.ps1 | 12 + 99 files changed, 20488 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/media-backend-lint.yml create mode 100644 .github/workflows/media-backend-tests.yml create mode 100644 backend/authclient/client.go create mode 100644 backend/logshipper/shipper.go create mode 100644 media-backend/.env.example create mode 100644 media-backend/README.md create mode 100644 media-backend/cmd/mediacollectiond/main.go create mode 100644 media-backend/go.mod create mode 100644 media-backend/go.sum create mode 100644 media-backend/internal/auth/auth.go create mode 100644 media-backend/internal/auth/auth_test.go create mode 100644 media-backend/internal/config/config.go create mode 100644 media-backend/internal/config/config_test.go create mode 100644 media-backend/internal/database/database.go create mode 100644 media-backend/internal/database/migrations/001_initial.sql create mode 100644 media-backend/internal/server/admin_storage.go create mode 100644 media-backend/internal/server/analyzer.go create mode 100644 media-backend/internal/server/analyzer_ai.go create mode 100644 media-backend/internal/server/analyzer_schedule.go create mode 100644 media-backend/internal/server/kiosk.go create mode 100644 media-backend/internal/server/media.go create mode 100644 media-backend/internal/server/path_test.go create mode 100644 media-backend/internal/server/servant_client.go create mode 100644 media-backend/internal/server/server.go create mode 100644 media-backend/internal/server/sync.go create mode 100644 media-backend/internal/server/workflows.go create mode 100644 media-webui/.prettierignore create mode 100644 media-webui/README.md create mode 100644 media-webui/eslint.config.js create mode 100644 media-webui/package.json create mode 100644 media-webui/prettier.config.js create mode 100644 media-webui/project-icons.json create mode 100644 media-webui/scripts/build-all.mjs create mode 100644 media-webui/scripts/project-favicon.mjs create mode 100644 media-webui/src/app.css create mode 100644 media-webui/src/app.d.ts create mode 100644 media-webui/src/app.html create mode 100644 media-webui/src/lib/api.ts create mode 100644 media-webui/src/lib/app-config.ts create mode 100644 media-webui/src/lib/components/AnalyzerHistory.svelte create mode 100644 media-webui/src/lib/components/AnalyzerLiveStatus.svelte create mode 100644 media-webui/src/lib/components/AnalyzerPipelineBreakdown.svelte create mode 100644 media-webui/src/lib/components/AppShell.svelte create mode 100644 media-webui/src/lib/components/AuthPage.svelte create mode 100644 media-webui/src/lib/components/EmptyState.svelte create mode 100644 media-webui/src/lib/components/PipelineFlowDiagram.svelte create mode 100644 media-webui/src/lib/components/ProjectIcon.svelte create mode 100644 media-webui/src/lib/components/SectionTitle.svelte create mode 100644 media-webui/src/lib/components/SettingsDialog.svelte create mode 100644 media-webui/src/lib/components/StatusDialog.svelte create mode 100644 media-webui/src/lib/components/StatusWidget.svelte create mode 100644 media-webui/src/lib/components/WorkspacePage.svelte create mode 100644 media-webui/src/lib/components/ui/badge.svelte create mode 100644 media-webui/src/lib/components/ui/button.svelte create mode 100644 media-webui/src/lib/components/ui/card.svelte create mode 100644 media-webui/src/lib/components/ui/metric.svelte create mode 100644 media-webui/src/lib/features/AboutWorkspace.svelte create mode 100644 media-webui/src/lib/features/AnalyzerWorkspace.svelte create mode 100644 media-webui/src/lib/features/ConfigWorkspace.svelte create mode 100644 media-webui/src/lib/features/DesktopWorkspace.svelte create mode 100644 media-webui/src/lib/features/FeedWorkspace.svelte create mode 100644 media-webui/src/lib/features/KioskWorkspace.svelte create mode 100644 media-webui/src/lib/features/MediaTypePipeline.svelte create mode 100644 media-webui/src/lib/features/ModeratorWorkspace.svelte create mode 100644 media-webui/src/lib/features/ServantWorkspace.svelte create mode 100644 media-webui/src/lib/features/TagsWorkspace.svelte create mode 100644 media-webui/src/lib/features/ToolsWorkspace.svelte create mode 100644 media-webui/src/lib/features/VideoPage.svelte create mode 100644 media-webui/src/lib/features/ViewerWorkspace.svelte create mode 100644 media-webui/src/lib/features/about/TechStackSection.svelte create mode 100644 media-webui/src/lib/language.svelte.ts create mode 100644 media-webui/src/lib/status.ts create mode 100644 media-webui/src/lib/stores/page-actions.svelte.ts create mode 100644 media-webui/src/lib/theme.svelte.ts create mode 100644 media-webui/src/lib/types.ts create mode 100644 media-webui/src/lib/utils/cn.ts create mode 100644 media-webui/src/routes/+layout.svelte create mode 100644 media-webui/src/routes/+page.svelte create mode 100644 media-webui/src/routes/[...path]/+page.svelte create mode 100644 media-webui/static/favicon.svg create mode 100644 media-webui/svelte.config.js create mode 100644 media-webui/tsconfig.json create mode 100644 media-webui/vite.config.ts create mode 100644 scripts/media/audit-html-js.mjs create mode 100644 scripts/media/audit-inline-layout.mjs create mode 100644 scripts/media/clean-test-artifacts.mjs create mode 100644 scripts/media/enforce-design-system-css.mjs create mode 100644 scripts/media/enforce-js-mapping.mjs create mode 100644 scripts/media/enforce-no-skipped-tests.mjs create mode 100644 scripts/media/inspect-vitest-exports.mjs create mode 100644 scripts/media/lint-all-json.mjs create mode 100644 scripts/media/lint-all.mjs create mode 100644 scripts/media/list-skipped-tests.mjs create mode 100644 scripts/media/report-test-timings.mjs create mode 100644 scripts/media/simulate-category-removal.mjs create mode 100644 scripts/media/upgrade-deps.mjs diff --git a/.github/workflows/media-backend-lint.yml b/.github/workflows/media-backend-lint.yml new file mode 100644 index 0000000..3bf2201 --- /dev/null +++ b/.github/workflows/media-backend-lint.yml @@ -0,0 +1,32 @@ +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/.github/workflows/media-backend-tests.yml b/.github/workflows/media-backend-tests.yml new file mode 100644 index 0000000..d14f440 --- /dev/null +++ b/.github/workflows/media-backend-tests.yml @@ -0,0 +1,32 @@ +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/backend/README.md b/backend/README.md index 7d4f5d5..2beb52c 100644 --- a/backend/README.md +++ b/backend/README.md @@ -6,7 +6,9 @@ services, not application-specific SQL or HTTP handlers. - `config` — environment string, required value, boolean, integer, and duration helpers. - `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification. - `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence. +- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database. - `migrate` — embedded filesystem adapter for Goose migrations. +- `logshipper` — client adapter for LoggingServer (Web/LoggingServer): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package. Run `go test ./...` and `go vet ./...` from this directory. The module path is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is diff --git a/backend/authclient/client.go b/backend/authclient/client.go new file mode 100644 index 0000000..6aee046 --- /dev/null +++ b/backend/authclient/client.go @@ -0,0 +1,177 @@ +// Package authclient is how any Go service in this workspace adopts a +// centralized AuthServer (see the AuthServer project, a sibling of this +// shared/backend module) instead of embedding shared/backend/auth's +// Store directly against its own private database. +// +// A service that switches to AuthServer trades "its own local user table" +// for "one HTTP call per request to AuthServer's /api/session/validate", +// gaining a single shared identity across every project that does the +// same. This package is additive: it does not change how +// shared/backend/auth works, and no project in this workspace is wired up +// to use it yet — that migration is a deliberate per-project decision, not +// something this package does automatically. See AuthServer/README.md's +// "Migration notes" section. +package authclient + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" +) + +// User is the account AuthServer resolved for a validated session. It +// mirrors the fields returned by GET /api/session/validate. +type User struct { + ID int64 `json:"user_id"` + Username string `json:"username"` + Role string `json:"role"` +} + +// ErrInvalidSession is returned by Validate when AuthServer reports the +// token/cookie as not currently valid (expired, unknown, or missing). +var ErrInvalidSession = errors.New("authclient: invalid or missing session") + +// Client calls a centralized AuthServer instance over HTTP. +type Client struct { + // BaseURL is AuthServer's base URL, e.g. "https://auth.example.com" + // (no trailing slash required). + baseURL string + // HTTPClient is used for every request; defaults to a client with a + // short timeout suitable for a per-request auth check. + httpClient *http.Client + // CookieName is the cookie this client looks for on incoming requests + // when Middleware has no Authorization header to use. Defaults to + // "auth_session", matching AuthServer's SessionCookieName. + cookieName string +} + +// Option configures optional Client behavior. +type Option func(*Client) + +// WithHTTPClient overrides the default HTTP client (e.g. to tune timeouts +// or transport pooling). +func WithHTTPClient(hc *http.Client) Option { + return func(c *Client) { c.httpClient = hc } +} + +// WithCookieName overrides the cookie name Middleware reads from incoming +// requests. Only needed if the AuthServer deployment was configured with a +// non-default session cookie name. +func WithCookieName(name string) Option { + return func(c *Client) { c.cookieName = name } +} + +// New creates a Client for the AuthServer instance at baseURL. +func New(baseURL string, opts ...Option) *Client { + c := &Client{ + baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), + httpClient: &http.Client{Timeout: 5 * time.Second}, + cookieName: "auth_session", + } + for _, opt := range opts { + opt(c) + } + return c +} + +// Validate calls AuthServer's GET /api/session/validate with token as a +// Bearer credential and returns the resolved user. It returns +// ErrInvalidSession (wrapped) when AuthServer reports the session as not +// valid, and a plain error for any transport/decoding failure. +func (c *Client) Validate(ctx context.Context, token string) (*User, error) { + if c == nil || c.baseURL == "" { + return nil, errors.New("authclient: client has no base URL") + } + token = strings.TrimSpace(token) + if token == "" { + return nil, ErrInvalidSession + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil) + if err != nil { + return nil, fmt.Errorf("authclient: build request: %w", err) + } + req.Header.Set("Authorization", "Bearer "+token) + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("authclient: call AuthServer: %w", err) + } + defer resp.Body.Close() + + var payload struct { + Valid bool `json:"valid"` + UserID int64 `json:"user_id"` + Username string `json:"username"` + Role string `json:"role"` + } + if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { + if resp.StatusCode == http.StatusUnauthorized { + return nil, ErrInvalidSession + } + return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err) + } + + if resp.StatusCode != http.StatusOK || !payload.Valid { + return nil, ErrInvalidSession + } + return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil +} + +// contextKey is unexported so only this package can set/read the resolved +// user on a request context. +type contextKey struct{} + +var userContextKey contextKey + +// UserFromContext returns the user Middleware attached to the request +// context, or nil if none is present (e.g. called outside Middleware). +func UserFromContext(ctx context.Context) *User { + user, _ := ctx.Value(userContextKey).(*User) + return user +} + +// Middleware extracts the session token from an incoming request — the +// cookie named by WithCookieName (default "auth_session"), falling back to +// an Authorization: Bearer header — validates it against AuthServer, and +// either responds 401 or attaches the resolved *User to the request +// context (retrieve it with UserFromContext) before calling next. +func (c *Client) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := c.tokenFromRequest(r) + user, err := c.Validate(r.Context(), token) + if err != nil { + status := http.StatusUnauthorized + if !errors.Is(err, ErrInvalidSession) { + // A transport/decoding failure talking to AuthServer is not + // the same as "this visitor is unauthenticated"; still fail + // closed (401) rather than letting the request through, but + // keep the two cases distinguishable for callers that want + // to log or alert differently. + status = http.StatusUnauthorized + } + http.Error(w, "authentication required", status) + return + } + r = r.WithContext(context.WithValue(r.Context(), userContextKey, user)) + next.ServeHTTP(w, r) + }) +} + +func (c *Client) tokenFromRequest(r *http.Request) string { + if header := r.Header.Get("Authorization"); header != "" { + if token, ok := strings.CutPrefix(header, "Bearer "); ok { + if token = strings.TrimSpace(token); token != "" { + return token + } + } + } + if cookie, err := r.Cookie(c.cookieName); err == nil { + return cookie.Value + } + return "" +} diff --git a/backend/logshipper/shipper.go b/backend/logshipper/shipper.go new file mode 100644 index 0000000..600a360 --- /dev/null +++ b/backend/logshipper/shipper.go @@ -0,0 +1,438 @@ +// Package logshipper is the client-side adapter for LoggingServer +// (Web/LoggingServer), the workspace's centralized log sink. It is the +// logging equivalent of the authclient package added alongside AuthServer: +// each service currently owns its own local internal/logging package (see +// Original/OutdoorGames/OutdoorGamesServerGo/internal/logging/logging.go for +// the canonical shape — a Logger tagged by module name, an env-driven level +// threshold, Debug/Info/Warn/Error/Critical/Audit/*Ctx methods, and an +// optional verbose JSON context dump gated by LOG_ALL). Shipper exposes that +// exact same method surface so a project can eventually swap its local +// logging.New(...) call for logshipper.New(...) with no call-site changes, +// once the owner decides to migrate a given service. +// +// No project imports this yet — see LoggingServer/README.md's "Migration +// notes" for the deliberate, per-project follow-up this requires. +// +// Shipper always writes the same human-readable line to stdout/stderr that +// the local loggers write today, in addition to batching entries off to +// LoggingServer. Nothing is lost if LoggingServer is never wired up, never +// reachable, or removed later — this is a mirror, not a replacement, for the +// container's own stdout/stderr logs. +package logshipper + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "strings" + "sync" + "time" +) + +// Level mirrors internal/logging's severity scale in every service's local +// logger, so a threshold configured via the same LOG env var behaves +// identically whether it gates a local Logger or a Shipper. +type Level int + +const ( + LevelDebug Level = 10 + LevelInfo Level = 20 + LevelWarn Level = 30 + LevelError Level = 40 + LevelCritical Level = 50 + LevelSilent Level = 100 +) + +func levelOf(s string) Level { + switch strings.ToLower(strings.TrimSpace(s)) { + case "debug": + return LevelDebug + case "warn", "warning": + return LevelWarn + case "error": + return LevelError + case "critical": + return LevelCritical + case "silent", "none", "off": + return LevelSilent + default: + return LevelInfo + } +} + +// sevName is the canonical, lowercase level name LoggingServer's ingest API +// expects (debug/info/warn/error/critical), independent of the uppercase +// name used in the local stdout/stderr line. +func sevName(sev Level) (upper, lower string) { + switch sev { + case LevelDebug: + return "DEBUG", "debug" + case LevelWarn: + return "WARN", "warn" + case LevelError: + return "ERROR", "error" + case LevelCritical: + return "CRITICAL", "critical" + default: + return "INFO", "info" + } +} + +const ( + defaultFlushInterval = 2 * time.Second + defaultMaxBatchSize = 100 + defaultBufferCapacity = 2000 + defaultHTTPTimeout = 5 * time.Second + defaultWarnInterval = time.Minute +) + +// Config configures a Shipper. Only BaseURL, IngestToken, and Service are +// normally set by a caller; everything else has a workable default. +type Config struct { + // BaseURL is LoggingServer's base URL, e.g. "http://loggingserver:8090". + // Required. + BaseURL string + // IngestToken is the shared INGEST_TOKEN bearer secret LoggingServer + // requires (see LoggingServer/README.md). Required. + IngestToken string + // Service is this process's service name as reported to LoggingServer, + // e.g. "playhouse" or "outdoorgames-server-go". Required. + Service string + + // Module is the local tag included in the human-readable stdout/stderr + // line, mirroring internal/logging.New's module argument. Defaults to + // Service when empty. + Module string + // Level is the severity threshold, same values/aliases as the LOG env + // var (debug/info/warn/error/critical/silent). Defaults to "info". + Level string + // LogAll mirrors the LOG_ALL env var: when true, a verbose JSON context + // dump is also printed locally (never sent to LoggingServer differently + // than normal — see Debug/InfoCtx doc comments). + LogAll bool + + // FlushInterval is how often buffered entries are sent to LoggingServer. + // Defaults to 2s. + FlushInterval time.Duration + // MaxBatchSize triggers an out-of-band flush as soon as the buffer + // reaches this many entries, instead of waiting for FlushInterval. + // Defaults to 100. + MaxBatchSize int + // BufferCapacity is the maximum number of not-yet-flushed entries held + // in memory. Once full, new entries are dropped (oldest-first callers + // are not blocked) rather than applying backpressure to the caller. + // Defaults to 2000. + BufferCapacity int + + // HTTPClient overrides the client used to POST to LoggingServer. + // Defaults to a client with a 5s timeout. + HTTPClient *http.Client +} + +// wireEntry mirrors LoggingServer's POST /api/logs request shape +// (LoggingServer/internal/httpapi.LogEntryInput) field-for-field. +type wireEntry struct { + Service string `json:"service"` + Level string `json:"level"` + Message string `json:"message"` + Context json.RawMessage `json:"context,omitempty"` + OccurredAt time.Time `json:"occurred_at"` +} + +// Shipper batches log entries in memory and flushes them to LoggingServer on +// a background goroutine, while also behaving like a local +// internal/logging.Logger (same method surface, same stdout/stderr output). +// A Shipper is safe for concurrent use. +type Shipper struct { + module string + threshold Level + logAll bool + + service string + url string + token string + client *http.Client + + maxBatch int + bufCap int + + mu sync.Mutex + buffer []wireEntry + + flushSignal chan struct{} + closeOnce sync.Once + closeCh chan struct{} + doneCh chan struct{} + + warnMu sync.Mutex + lastWarn time.Time +} + +// New creates a Shipper. It starts a background flush goroutine immediately; +// call Close (or Flush, for a one-off synchronous flush) during shutdown to +// avoid losing buffered entries. +func New(cfg Config) *Shipper { + module := cfg.Module + if module == "" { + module = cfg.Service + } + flushInterval := cfg.FlushInterval + if flushInterval <= 0 { + flushInterval = defaultFlushInterval + } + maxBatch := cfg.MaxBatchSize + if maxBatch <= 0 { + maxBatch = defaultMaxBatchSize + } + bufCap := cfg.BufferCapacity + if bufCap <= 0 { + bufCap = defaultBufferCapacity + } + client := cfg.HTTPClient + if client == nil { + client = &http.Client{Timeout: defaultHTTPTimeout} + } + + s := &Shipper{ + module: module, + threshold: levelOf(cfg.Level), + logAll: cfg.LogAll, + service: cfg.Service, + url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs", + token: cfg.IngestToken, + client: client, + maxBatch: maxBatch, + bufCap: bufCap, + flushSignal: make(chan struct{}, 1), + closeCh: make(chan struct{}), + doneCh: make(chan struct{}), + } + + go s.loop(flushInterval) + return s +} + +func (s *Shipper) loop(flushInterval time.Duration) { + defer close(s.doneCh) + ticker := time.NewTicker(flushInterval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + s.flush() + case <-s.flushSignal: + s.flush() + case <-s.closeCh: + s.flush() // final, best-effort flush of whatever is left + return + } + } +} + +// requestFlush asks the background loop to flush soon, without blocking the +// caller: if a flush is already pending the request is simply dropped. +func (s *Shipper) requestFlush() { + select { + case s.flushSignal <- struct{}{}: + default: + } +} + +// enqueue appends one entry to the buffer, dropping the incoming entry +// (rather than blocking the caller or evicting older entries) once the +// buffer is full. This is the sole non-blocking guarantee this package +// makes: a caller's Debug/Info/... call never waits on network I/O. +func (s *Shipper) enqueue(entry wireEntry) { + s.mu.Lock() + full := len(s.buffer) >= s.bufCap + if !full { + s.buffer = append(s.buffer, entry) + } + atCap := len(s.buffer) >= s.maxBatch + s.mu.Unlock() + + if full { + s.warnOnce(fmt.Errorf("logshipper: buffer full (cap=%d), dropping log entries for service %q", s.bufCap, s.service)) + return + } + if atCap { + s.requestFlush() + } +} + +// flush sends every currently buffered entry to LoggingServer in one +// request. Failures are swallowed (beyond a rate-limited local warning) by +// design: a host application must never fail, panic, or slow down because +// its log sink is unreachable. +func (s *Shipper) flush() { + s.mu.Lock() + if len(s.buffer) == 0 { + s.mu.Unlock() + return + } + batch := s.buffer + s.buffer = nil + s.mu.Unlock() + + body, err := json.Marshal(batch) + if err != nil { + s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err)) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body)) + if err != nil { + s.warnOnce(fmt.Errorf("logshipper: build request: %w", err)) + return + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+s.token) + + resp, err := s.client.Do(req) + if err != nil { + s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err)) + return + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + s.warnOnce(fmt.Errorf("logshipper: LoggingServer rejected %d entries: HTTP %d", len(batch), resp.StatusCode)) + } +} + +// warnOnce prints a local stderr warning at most once per minute, no matter +// how many sends fail in that window, so an unreachable LoggingServer cannot +// itself become a log-spam problem. +func (s *Shipper) warnOnce(err error) { + s.warnMu.Lock() + defer s.warnMu.Unlock() + if time.Since(s.lastWarn) < defaultWarnInterval { + return + } + s.lastWarn = time.Now() + fmt.Fprintf(os.Stderr, "[%s] [logshipper] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), err.Error()) +} + +// Flush synchronously sends any currently buffered entries. It never blocks +// longer than the underlying HTTP client's timeout and never returns an +// error to the caller (failures are reported via the same rate-limited +// stderr warning as background flushes) — this mirrors the "never block or +// panic the host app" guarantee the background path makes. +func (s *Shipper) Flush() { + s.flush() +} + +// Close stops the background flush goroutine after performing one final +// flush of any buffered entries, and waits for that flush to finish. Call it +// during graceful shutdown so the last few log lines before exit are not +// silently dropped. +func (s *Shipper) Close() error { + s.closeOnce.Do(func() { close(s.closeCh) }) + <-s.doneCh + return nil +} + +// ---- Logger-shaped methods ------------------------------------------------- +// +// Everything below matches internal/logging.Logger's method surface +// (Debug/Info/Warn/Error/Critical/Audit/*Ctx) so a Shipper can act as a +// near drop-in replacement for a project's local logger. + +func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) { + if sev < s.threshold { + return + } + now := time.Now() + msg := formatArgs(args) + upper, lower := sevName(sev) + + line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s", + now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg) + switch sev { + case LevelError, LevelCritical, LevelWarn: + fmt.Fprintln(os.Stderr, line) + default: + fmt.Fprintln(os.Stdout, line) + } + + if s.logAll && ctx != nil { + if b, err := json.Marshal(scrubIDs(ctx)); err == nil { + fmt.Fprintf(os.Stdout, "[%s] [%s] [DEBUG] [%s] [DETAILS] %s\n", + now.Format("2006-01-02"), now.Format("15:04:05.000"), s.module, string(b)) + } + } + + // Unlike the local-only verbose dump above (which scrubs IDs for + // readability), the context shipped to LoggingServer is sent unscrubbed: + // the whole point of centralizing logs is cross-service correlation by + // request/user/entity ID, so stripping IDs here would defeat that. + var rawCtx json.RawMessage + if ctx != nil { + if b, err := json.Marshal(ctx); err == nil { + rawCtx = b + } + } + s.enqueue(wireEntry{ + Service: s.service, + Level: lower, + Message: msg, + Context: rawCtx, + OccurredAt: now, + }) +} + +func formatArgs(args []any) string { + parts := make([]string, 0, len(args)) + for _, a := range args { + switch v := a.(type) { + case error: + parts = append(parts, v.Error()) + case string: + parts = append(parts, v) + default: + if b, err := json.Marshal(v); err == nil { + parts = append(parts, string(b)) + } else { + parts = append(parts, fmt.Sprintf("%v", v)) + } + } + } + return strings.Join(parts, " ") +} + +// scrubIDs drops raw identifier fields from the verbose local-only context +// dump, matching internal/logging.Logger's behavior. +func scrubIDs(ctx map[string]any) map[string]any { + out := make(map[string]any, len(ctx)) + for k, v := range ctx { + lower := strings.ToLower(k) + if lower == "id" || strings.HasSuffix(lower, "id") || strings.HasSuffix(lower, "_id") { + continue + } + out[k] = v + } + return out +} + +func (s *Shipper) Debug(args ...any) { s.emit(LevelDebug, nil, args...) } +func (s *Shipper) Info(args ...any) { s.emit(LevelInfo, nil, args...) } +func (s *Shipper) Warn(args ...any) { s.emit(LevelWarn, nil, args...) } +func (s *Shipper) Error(args ...any) { s.emit(LevelError, nil, args...) } +func (s *Shipper) Critical(args ...any) { s.emit(LevelCritical, nil, args...) } + +// Audit logs a structured audit-trail event at info level, matching +// internal/logging.Logger.Audit. +func (s *Shipper) Audit(event string, details map[string]any) { + s.emit(LevelInfo, details, "audit:"+event, details) +} + +func (s *Shipper) DebugCtx(ctx map[string]any, args ...any) { s.emit(LevelDebug, ctx, args...) } +func (s *Shipper) InfoCtx(ctx map[string]any, args ...any) { s.emit(LevelInfo, ctx, args...) } +func (s *Shipper) WarnCtx(ctx map[string]any, args ...any) { s.emit(LevelWarn, ctx, args...) } +func (s *Shipper) ErrorCtx(ctx map[string]any, args ...any) { s.emit(LevelError, ctx, args...) } diff --git a/media-backend/.env.example b/media-backend/.env.example new file mode 100644 index 0000000..023fa11 --- /dev/null +++ b/media-backend/.env.example @@ -0,0 +1,22 @@ +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=../Forge/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=mediacollection_session +COOKIE_SECURE=false +INTERNAL_SERVICE_SECRET= +MAX_UPLOAD_BYTES=50gb diff --git a/media-backend/README.md b/media-backend/README.md new file mode 100644 index 0000000..01c78d3 --- /dev/null +++ b/media-backend/README.md @@ -0,0 +1,31 @@ +# MediaCollection Go backend + +The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, `servant`, or `desktop` 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/mediacollectiond +``` + +Important settings: + +- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. Porter also walks + every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in MediaConfig's + Mounts 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. +- `SERVANT_URL` is only the bootstrap fallback for Porter's URL - once configured through + MediaConfig it's read from the `mediaservant_url` row in the `settings` table instead (see + `servantBaseURL` in `internal/server/servant_client.go`). +- `INTERNAL_SERVICE_SECRET` protects service-to-service mount and media-proxy APIs. + +Run `go test ./...` before packaging. The project Dockerfiles build this module and copy the WebUI into the final image; no Node server is started at runtime. diff --git a/media-backend/cmd/mediacollectiond/main.go b/media-backend/cmd/mediacollectiond/main.go new file mode 100644 index 0000000..c56f3a4 --- /dev/null +++ b/media-backend/cmd/mediacollectiond/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "context" + "errors" + "flag" + "log" + "net/http" + "os" + "os/signal" + "syscall" + + "mediacollection/internal/config" + "mediacollection/internal/database" + "mediacollection/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/media-backend/go.mod b/media-backend/go.mod new file mode 100644 index 0000000..1475bbc --- /dev/null +++ b/media-backend/go.mod @@ -0,0 +1,21 @@ +module mediacollection + +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/media-backend/go.sum b/media-backend/go.sum new file mode 100644 index 0000000..17000cd --- /dev/null +++ b/media-backend/go.sum @@ -0,0 +1,32 @@ +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/media-backend/internal/auth/auth.go b/media-backend/internal/auth/auth.go new file mode 100644 index 0000000..262a017 --- /dev/null +++ b/media-backend/internal/auth/auth.go @@ -0,0 +1,956 @@ +package auth + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/bcrypt" + sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" +) + +type User struct { + ID int64 `json:"id"` + Email string `json:"email"` + Username string `json:"username,omitempty"` + Role string `json:"role,omitempty"` + CanManageUsers bool `json:"canManageUsers"` + Bio string `json:"bio,omitempty"` + Avatar string `json:"avatarUrl,omitempty"` + MFAEnabled bool `json:"mfaEnabled"` +} + +type storedUser struct { + User + PasswordHash string + Disabled bool + TOTPSecret string +} + +type contextKey struct{} + +var userContextKey contextKey + +var ( + ErrUnauthorized = errors.New("authentication required") + ErrForbidden = errors.New("administrator access required") + ErrInvalidLogin = errors.New("Invalid username or password.") +) + +const loginRequiredSettingKey = "auth_required" + +type Service struct { + db *pgxpool.Pool + cookieName string + secureCookies bool + sessionTTL time.Duration + resetManager *sharedauth.ResetManager +} + +func New(db *pgxpool.Pool, cookieName string, secureCookies bool) *Service { + return &Service{ + db: db, + cookieName: cookieName, + secureCookies: secureCookies, + sessionTTL: 7 * 24 * time.Hour, + resetManager: sharedauth.NewResetManager(), + } +} + +func UserFromContext(ctx context.Context) *User { + value, _ := ctx.Value(userContextKey).(*User) + return value +} + +func (s *Service) CurrentUser(r *http.Request) (*User, error) { + cookie, err := r.Cookie(s.cookieName) + if errors.Is(err, http.ErrNoCookie) || cookie.Value == "" { + return nil, nil + } + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + var user User + var disabled bool + err = s.db.QueryRow(ctx, ` + SELECT u.id, u.email, COALESCE(u.username, ''), COALESCE(u.role, 'user'), + COALESCE(u.bio, ''), COALESCE(u.avatar_url, ''), u.disabled, COALESCE(u.mfa_enabled, false) + FROM go_sessions session + JOIN users u ON u.id = session.user_id + WHERE session.token_hash = $1 AND session.expires_at > NOW() + `, tokenHash(cookie.Value)).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &disabled, &user.MFAEnabled) + if errors.Is(err, pgx.ErrNoRows) || disabled { + return nil, nil + } + if err != nil { + return nil, err + } + user.CanManageUsers = sharedauth.CanManageUsers(user.Role) + return &user, nil +} + +func (s *Service) Optional(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, err := s.CurrentUser(r) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication lookup failed") + return + } + if user != nil { + r = r.WithContext(context.WithValue(r.Context(), userContextKey, user)) + } + next.ServeHTTP(w, r) + }) +} + +func (s *Service) Require(next http.Handler) http.Handler { + return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if UserFromContext(r.Context()) == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + next.ServeHTTP(w, r) + })) +} + +// RequireIfLoginRequired protects actions when the application has login +// enabled, while allowing explicitly public installations to use actions that +// do not need a user identity. +func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler { + return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if UserFromContext(r.Context()) != nil { + next.ServeHTTP(w, r) + return + } + + loginRequired, err := s.LoginRequired(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + if !loginRequired { + next.ServeHTTP(w, r) + return + } + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + })) +} + +func (s *Service) RequireAdmin(next http.Handler) http.Handler { + return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if !IsAdmin(user) { + writeError(w, http.StatusForbidden, ErrForbidden.Error()) + return + } + next.ServeHTTP(w, r) + })) +} + +// RequireAdminIfLoginRequired keeps administrative actions protected for +// authenticated users, while allowing explicitly public installations to use +// configuration endpoints that do not require a user identity. +func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler { + return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + loginRequired, err := s.LoginRequired(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + if !loginRequired { + next.ServeHTTP(w, r) + return + } + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + if !IsAdmin(user) { + writeError(w, http.StatusForbidden, ErrForbidden.Error()) + return + } + next.ServeHTTP(w, r) + })) +} + +func IsAdmin(user *User) bool { + if user == nil { + return false + } + switch strings.ToLower(strings.TrimSpace(user.Role)) { + case "admin", "superadmin", "moderator": + return true + default: + return false + } +} + +func (s *Service) Me(w http.ResponseWriter, r *http.Request) { + user, err := s.CurrentUser(r) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication lookup failed") + return + } + count, err := s.CountUsers(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + loginRequired, err := s.LoginRequired(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "user": user, + "authRequired": loginRequired, + "setupRequired": count == 0, + }) +} + +func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + + email := strings.ToLower(strings.TrimSpace(input.Email)) + username := strings.TrimSpace(input.Username) + if !strings.Contains(email, "@") || len(email) > 254 { + writeError(w, http.StatusBadRequest, "a valid email is required") + return + } + if username == "" || len([]rune(username)) > 64 { + writeError(w, http.StatusBadRequest, "a username is required") + return + } + + passwordHash := "" + if input.Password != "" { + if err := validatePassword(input.Password); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) + if err != nil { + writeError(w, http.StatusInternalServerError, "password could not be updated") + return + } + passwordHash = string(hash) + } + + if _, err := s.db.Exec(r.Context(), ` + UPDATE users + SET email = $1, username = $2, password_hash = COALESCE(NULLIF($3, ''), password_hash) + WHERE id = $4 + `, email, username, passwordHash, user.ID); err != nil { + writeError(w, http.StatusBadRequest, "profile could not be updated") + return + } + + updated, err := s.CurrentUser(r) + if err != nil || updated == nil { + writeError(w, http.StatusInternalServerError, "profile could not be loaded") + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": updated}) +} + +func (s *Service) RequireUserManager(next http.Handler) http.Handler { + return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if !sharedauth.CanManageUsers(user.Role) { + writeError(w, http.StatusForbidden, ErrForbidden.Error()) + return + } + next.ServeHTTP(w, r) + })) +} + +func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { + count, err := s.CountUsers(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": count == 0}) +} + +func (s *Service) LoginRequired(ctx context.Context) (bool, error) { + var value string + err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value) + if errors.Is(err, pgx.ErrNoRows) { + return true, nil + } + if err != nil { + return true, err + } + + switch strings.ToLower(strings.TrimSpace(value)) { + case "false", "0", "no", "off": + return false, nil + default: + return true, nil + } +} + +func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) { + loginRequired, err := s.LoginRequired(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "access settings unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired}) +} + +func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) { + var input struct { + LoginRequired *bool `json:"loginRequired"` + } + if err := decodeJSON(r, &input); err != nil || input.LoginRequired == nil { + writeError(w, http.StatusBadRequest, "loginRequired must be a boolean") + return + } + 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() + `, loginRequiredSettingKey, strconv.FormatBool(*input.LoginRequired)); err != nil { + writeError(w, http.StatusInternalServerError, "access setting could not be saved") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired}) +} + +func (s *Service) Status(w http.ResponseWriter, r *http.Request) { + count, err := s.CountUsers(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + user, _ := s.CurrentUser(r) + loginRequired, err := s.LoginRequired(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "authentication status unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "setupRequired": count == 0, + "authenticated": user != nil, + "authRequired": loginRequired, + "user": user, + }) +} + +type managedAccount struct { + ID int64 + Email string + Username string + Role string + Disabled bool + CreatedAt time.Time +} + +func (s *Service) managedAccount(ctx context.Context, id int64) (*managedAccount, error) { + var user managedAccount + err := s.db.QueryRow(ctx, ` + SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at + FROM users WHERE id = $1 + `, id).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + return &user, nil +} + +func managedAccountPayload(user *managedAccount) map[string]any { + return map[string]any{ + "id": user.ID, + "username": user.Username, + "email": user.Email, + "role": string(sharedauth.NormalizeRole(user.Role)), + "createdAt": user.CreatedAt, + } +} + +func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { + rows, err := s.db.Query(r.Context(), ` + SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at + FROM users ORDER BY created_at, id + `) + if err != nil { + writeError(w, http.StatusInternalServerError, "users unavailable") + return + } + defer rows.Close() + users := make([]map[string]any, 0) + for rows.Next() { + var user managedAccount + if err := rows.Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt); err != nil { + writeError(w, http.StatusInternalServerError, "users unavailable") + return + } + users = append(users, managedAccountPayload(&user)) + } + if err := rows.Err(); err != nil { + writeError(w, http.StatusInternalServerError, "users unavailable") + return + } + writeJSON(w, http.StatusOK, users) +} + +func (s *Service) ManagedCreateUser(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 := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + actor := UserFromContext(r.Context()) + role := sharedauth.NormalizeRole(input.Role) + if role == sharedauth.RoleSuperAdmin { + writeError(w, http.StatusBadRequest, "a new user cannot be a superadmin") + return + } + if actor == nil || sharedauth.NormalizeRole(actor.Role) != sharedauth.RoleSuperAdmin { + role = sharedauth.RoleUser + } + user, err := s.CreateUser(r.Context(), input.Email, input.Username, input.Password, string(role)) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + created, err := s.managedAccount(r.Context(), user.ID) + if err != nil || created == nil { + writeError(w, http.StatusInternalServerError, "user could not be loaded") + return + } + writeJSON(w, http.StatusCreated, managedAccountPayload(created)) +} + +func (s *Service) ManagedUpdateUser(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 + } + target, err := s.managedAccount(r.Context(), id) + if err != nil { + writeError(w, http.StatusInternalServerError, "user could not be loaded") + return + } + if target == nil { + writeError(w, http.StatusNotFound, "user not found") + return + } + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + Role *string `json:"role"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + actor := UserFromContext(r.Context()) + targetRole := sharedauth.NormalizeRole(target.Role) + role := targetRole + if targetRole != sharedauth.RoleSuperAdmin && actor != nil && sharedauth.NormalizeRole(actor.Role) == sharedauth.RoleSuperAdmin && input.Role != nil { + requested := sharedauth.NormalizeRole(*input.Role) + if requested == sharedauth.RoleSuperAdmin { + writeError(w, http.StatusBadRequest, "the superadmin role is protected") + return + } + role = requested + } + if err := s.UpdateUser(r.Context(), id, input.Email, input.Username, string(role), nil); err != nil { + writeError(w, http.StatusBadRequest, "user could not be updated") + return + } + if strings.TrimSpace(input.Password) != "" { + if err := s.SetPassword(r.Context(), id, input.Password); err != nil { + writeError(w, http.StatusBadRequest, "password could not be updated") + return + } + } + updated, err := s.managedAccount(r.Context(), id) + if err != nil || updated == nil { + writeError(w, http.StatusInternalServerError, "user could not be loaded") + return + } + writeJSON(w, http.StatusOK, managedAccountPayload(updated)) +} + +func (s *Service) ManagedDeleteUser(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 + } + target, err := s.managedAccount(r.Context(), id) + if err != nil { + writeError(w, http.StatusInternalServerError, "user could not be loaded") + return + } + if target == nil { + writeError(w, http.StatusNotFound, "user not found") + return + } + actor := UserFromContext(r.Context()) + if actor == nil || actor.ID == target.ID || sharedauth.NormalizeRole(target.Role) == sharedauth.RoleSuperAdmin { + writeError(w, http.StatusForbidden, "the current or first account cannot be removed") + return + } + if err := s.DeleteUser(r.Context(), id); err != nil { + writeError(w, http.StatusNotFound, "user not found") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + email, username, password, err := normalizeCredentials(input.Email, input.Username, input.Password) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + if username == "" { + writeError(w, http.StatusBadRequest, "a username is required") + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + writeError(w, http.StatusInternalServerError, "could not secure password") + return + } + var user User + err = s.db.QueryRow(r.Context(), ` + INSERT INTO users (email, username, password_hash, role) + SELECT $1, $2, $3, 'superadmin' + WHERE NOT EXISTS (SELECT 1 FROM users) + RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'superadmin') + `, email, username, string(hash)).Scan(&user.ID, &user.Email, &user.Username, &user.Role) + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusConflict, "Setup has already been completed.") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "could not create account") + return + } + user.CanManageUsers = sharedauth.CanManageUsers(user.Role) + if err := s.startSession(w, r.Context(), user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "could not start session") + return + } + writeJSON(w, http.StatusCreated, map[string]any{"user": user}) +} + +func (s *Service) Login(w http.ResponseWriter, r *http.Request) { + var input struct { + Identifier string `json:"identifier"` + Email string `json:"email"` + Password string `json:"password"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + identifier := strings.TrimSpace(input.Identifier) + if identifier == "" { + identifier = strings.TrimSpace(input.Email) + } + var user storedUser + err := s.db.QueryRow(r.Context(), ` + SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), COALESCE(bio, ''), + COALESCE(avatar_url, ''), password_hash, disabled, COALESCE(mfa_enabled, false), COALESCE(totp_secret, '') + FROM users WHERE LOWER(email) = LOWER($1) OR LOWER(COALESCE(username, '')) = LOWER($1) + LIMIT 1 + `, identifier).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &user.PasswordHash, &user.Disabled, &user.MFAEnabled, &user.TOTPSecret) + if errors.Is(err, pgx.ErrNoRows) { + writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "could not authenticate") + return + } + user.User.CanManageUsers = sharedauth.CanManageUsers(user.Role) + if user.Disabled || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)) != nil { + writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) + return + } + if user.MFAEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, strings.TrimSpace(input.TOTPToken), time.Now()) { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true}) + return + } + _, _ = s.db.Exec(r.Context(), `UPDATE users SET last_login_at = NOW() WHERE id = $1`, user.ID) + if err := s.startSession(w, r.Context(), user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "could not start session") + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": user.User}) +} + +func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled}) +} + +func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + if user.MFAEnabled { + writeError(w, http.StatusConflict, "multi-factor authentication is already enabled") + return + } + secret, err := sharedauth.GenerateTOTPSecret() + if err != nil { + writeError(w, http.StatusInternalServerError, "could not create authenticator secret") + return + } + if _, err := s.db.Exec(r.Context(), `UPDATE users SET totp_secret = $1, mfa_enabled = false WHERE id = $2`, secret, user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "could not save authenticator secret") + return + } + account := user.Username + if account == "" { + account = user.Email + } + uri := sharedauth.TOTPProvisioningURI("MediaCollection", account, secret) + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"secret": secret, "otpauth": uri, "otpauthUrl": uri, "enabled": false}}) +} + +func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + var input struct { + Token string `json:"token"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + var secret string + if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, '') FROM users WHERE id = $1`, user.ID).Scan(&secret); err != nil { + writeError(w, http.StatusInternalServerError, "could not load authenticator secret") + return + } + token := strings.TrimSpace(input.TOTPToken) + if token == "" { + token = strings.TrimSpace(input.Token) + } + if !sharedauth.VerifyTOTP(secret, token, time.Now()) { + writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") + return + } + if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = true WHERE id = $1 AND totp_secret <> ''`, user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "could not enable multi-factor authentication") + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}}) +} + +func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + var input struct { + Token string `json:"token"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + var secret string + var enabled bool + if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, ''), COALESCE(mfa_enabled, false) FROM users WHERE id = $1`, user.ID).Scan(&secret, &enabled); err != nil { + writeError(w, http.StatusInternalServerError, "could not load authenticator state") + return + } + token := strings.TrimSpace(input.TOTPToken) + if token == "" { + token = strings.TrimSpace(input.Token) + } + if !enabled || !sharedauth.VerifyTOTP(secret, token, time.Now()) { + writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") + return + } + if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = false, totp_secret = NULL WHERE id = $1`, user.ID); err != nil { + writeError(w, http.StatusInternalServerError, "could not disable multi-factor authentication") + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}}) +} + +func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie(s.cookieName); err == nil && cookie.Value != "" { + _, _ = s.db.Exec(r.Context(), `DELETE FROM go_sessions WHERE token_hash = $1`, tokenHash(cookie.Value)) + } + http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1}) + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Service) RequestAdminReset(w http.ResponseWriter, _ *http.Request) { + if _, err := s.resetManager.Request(); err != nil { + writeError(w, http.StatusInternalServerError, "could not create reset code") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Service) ConfirmAdminReset(w http.ResponseWriter, r *http.Request) { + var input struct { + Code string `json:"code"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + if !s.resetManager.Confirm(input.Code) { + writeError(w, http.StatusUnauthorized, "Invalid or expired reset code.") + return + } + if _, err := s.db.Exec(r.Context(), `DELETE FROM users`); err != nil { + writeError(w, http.StatusInternalServerError, "could not reset administrator accounts") + return + } + http.SetCookie(w, &http.Cookie{ + Name: s.cookieName, + Value: "", + Path: "/", + HttpOnly: true, + Secure: s.secureCookies, + SameSite: http.SameSiteLaxMode, + MaxAge: -1, + }) + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Service) CountUsers(ctx context.Context) (int64, error) { + var count int64 + err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count) + return count, err +} + +func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) { + email, username, password, err := normalizeCredentials(email, username, password) + if err != nil { + return nil, err + } + role = normalizeRole(role) + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return nil, err + } + var user User + err = s.db.QueryRow(ctx, ` + INSERT INTO users (email, username, password_hash, role) + VALUES ($1, $2, $3, $4) + RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user') + `, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role) + if err != nil { + return nil, err + } + return &user, nil +} + +func (s *Service) ListUsers(ctx context.Context, search string, limit, offset int) ([]map[string]any, int64, error) { + search = strings.TrimSpace(search) + if limit <= 0 || limit > 200 { + limit = 50 + } + if offset < 0 { + offset = 0 + } + pattern := "%" + search + "%" + rows, err := s.db.Query(ctx, ` + SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at, last_login_at + FROM users + WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2) + ORDER BY id DESC LIMIT $3 OFFSET $4 + `, search, pattern, limit, offset) + if err != nil { + return nil, 0, err + } + defer rows.Close() + users := make([]map[string]any, 0) + for rows.Next() { + var id int64 + var email, username, role string + var disabled bool + var created time.Time + var lastLogin *time.Time + if err := rows.Scan(&id, &email, &username, &role, &disabled, &created, &lastLogin); err != nil { + return nil, 0, err + } + users = append(users, map[string]any{"id": id, "email": email, "username": username, "role": role, "disabled": disabled, "createdAt": created, "lastLoginAt": lastLogin}) + } + var total int64 + err = s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)`, search, pattern).Scan(&total) + return users, total, err +} + +func (s *Service) DeleteUser(ctx context.Context, id int64) error { + _, err := s.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id) + return err +} + +func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, role string, disabled *bool) error { + role = strings.ToLower(strings.TrimSpace(role)) + if role != "" { + role = normalizeRole(role) + } + _, err := s.db.Exec(ctx, ` + UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username), + role = COALESCE(NULLIF($4, ''), role), disabled = COALESCE($5, disabled) WHERE id = $1 + `, id, strings.TrimSpace(email), strings.TrimSpace(username), role, disabled) + return err +} + +func (s *Service) SetPassword(ctx context.Context, id int64, password string) error { + if err := validatePassword(password); err != nil { + return err + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + _, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash)) + return err +} + +func validatePassword(password string) error { + if len([]rune(password)) < 8 || len([]rune(password)) > 1024 { + return fmt.Errorf("Password must be at least 8 characters.") + } + return nil +} + +func (s *Service) startSession(w http.ResponseWriter, ctx context.Context, userID int64) error { + token, err := randomToken() + if err != nil { + return err + } + expires := time.Now().Add(s.sessionTTL) + if _, err := s.db.Exec(ctx, `INSERT INTO go_sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, tokenHash(token), userID, expires); err != nil { + return err + } + _, _ = s.db.Exec(ctx, `DELETE FROM go_sessions WHERE expires_at <= NOW()`) + http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: token, Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, Expires: expires, MaxAge: int(s.sessionTTL.Seconds())}) + return nil +} + +func normalizeCredentials(email, username, password string) (string, string, string, error) { + email = strings.ToLower(strings.TrimSpace(email)) + username = strings.TrimSpace(username) + if !strings.Contains(email, "@") || len(email) > 254 { + return "", "", "", fmt.Errorf("a valid email is required") + } + if len([]rune(username)) > 64 { + return "", "", "", fmt.Errorf("username is too long") + } + if len([]rune(password)) < 8 || len([]rune(password)) > 1024 { + return "", "", "", fmt.Errorf("Password must be at least 8 characters.") + } + return email, username, password, nil +} + +func normalizeRole(role string) string { + switch strings.ToLower(strings.TrimSpace(role)) { + case "admin", "superadmin", "moderator": + return strings.ToLower(strings.TrimSpace(role)) + default: + return "user" + } +} + +func randomToken() (string, error) { + data := make([]byte, 32) + if _, err := rand.Read(data); err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(data), nil +} + +func tokenHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +func decodeJSON(r *http.Request, target any) error { + defer r.Body.Close() + decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024)) + 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}) +} + +func (u User) String() string { return strconv.FormatInt(u.ID, 10) } diff --git a/media-backend/internal/auth/auth_test.go b/media-backend/internal/auth/auth_test.go new file mode 100644 index 0000000..fc3099f --- /dev/null +++ b/media-backend/internal/auth/auth_test.go @@ -0,0 +1,28 @@ +package auth + +import "testing" + +func TestNormalizeCredentials(t *testing.T) { + email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple") + if err != nil { + t.Fatal(err) + } + if email != "user@example.com" || username != "user" || password == "" { + t.Fatalf("normalized credentials = %q, %q, %q", email, username, password) + } +} + +func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) { + if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil { + t.Fatalf("empty optional username rejected: %v", err) + } +} + +func TestNormalizeRole(t *testing.T) { + if normalizeRole("MODERATOR") != "moderator" { + t.Fatal("moderator role was not normalized") + } + if normalizeRole("unknown") != "user" { + t.Fatal("unknown role was not reduced to user") + } +} diff --git a/media-backend/internal/config/config.go b/media-backend/internal/config/config.go new file mode 100644 index 0000000..af30d48 --- /dev/null +++ b/media-backend/internal/config/config.go @@ -0,0 +1,237 @@ +package config + +import ( + "fmt" + "os" + "path/filepath" + "strconv" + "strings" +) + +type Service string + +const ( + Viewer Service = "viewer" + Tools Service = "tools" + Analyzer Service = "analyzer" + ConfigService Service = "config" + Moderator Service = "moderator" + Kiosk Service = "kiosk" + Servant Service = "servant" + Desktop Service = "desktop" +) + +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 + InternalServiceSecret string + FFmpeg string + FFprobe string + YTDLP string + ComfyURL string + AnalyzerModelsURL string + ServantURL 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("..", "Forge", "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", "mediacollection_session"), + SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""), + 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"), "/"), + ServantURL: strings.TrimRight(envOr("SERVANT_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 "tools", "mediatools": + return Tools + case "analyzer", "mediaanalyzer": + return Analyzer + case "config", "mediaconfig": + return ConfigService + case "moderator", "mediamoderator": + return Moderator + case "kiosk", "mediakiosk": + return Kiosk + case "servant", "mediaservant": + return Servant + case "desktop", "mediadesktop": + return Desktop + default: + return "" + } +} + +func serviceName(service Service) string { + switch service { + case Viewer: + return "MediaViewer" + case Tools: + return "MediaTools" + case Analyzer: + return "MediaAnalyzer" + case ConfigService: + return "MediaConfig" + case Moderator: + return "MediaModerator" + case Kiosk: + return "MediaKiosk" + case Servant: + return "MediaServant" + case Desktop: + return "MediaDesktop" + default: + return "MediaCollection" + } +} + +func defaultPort(service Service) string { + switch service { + case ConfigService: + return "3005" + case Moderator: + return "8090" + case Servant: + 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/media-backend/internal/config/config_test.go b/media-backend/internal/config/config_test.go new file mode 100644 index 0000000..3a3a8ea --- /dev/null +++ b/media-backend/internal/config/config_test.go @@ -0,0 +1,43 @@ +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/media-backend/internal/database/database.go b/media-backend/internal/database/database.go new file mode 100644 index 0000000..f7b19db --- /dev/null +++ b/media-backend/internal/database/database.go @@ -0,0 +1,55 @@ +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/media-backend/internal/database/migrations/001_initial.sql b/media-backend/internal/database/migrations/001_initial.sql new file mode 100644 index 0000000..9ab84df --- /dev/null +++ b/media-backend/internal/database/migrations/001_initial.sql @@ -0,0 +1,321 @@ +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 Lookout 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/media-backend/internal/server/admin_storage.go b/media-backend/internal/server/admin_storage.go new file mode 100644 index 0000000..2471ac6 --- /dev/null +++ b/media-backend/internal/server/admin_storage.go @@ -0,0 +1,1128 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" +) + +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) + 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}) +} + +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}) +} + +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 MediaConfig's Mounts workspace. +type mountEntry struct { + Type string `json:"type"` + Path string `json:"path"` +} + +// configuredMounts parses the configured_mounts setting - the live source MediaConfig's Mounts +// 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 Porter'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 Mounts 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 MediaConfig's Mounts 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 (Lookout's "images"/"videos"/"audios", Playhouse/Marquee's "media", ...) +// but they're all describing locations Porter 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 Servant actually walks and resolves files under: the static +// MEDIA_ROOTS/MEDIA_ROOT env config (if any) plus every media-library path configured through +// MediaConfig's Mounts workspace, deduped. Settings are read fresh from the DB on every call +// (no caching, same as mediaservant_url/servantBaseURL), so a mount saved in MediaConfig takes +// effect on Servant'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) mountServantRoutes(r chi.Router) { + r.Get("/stats", s.servantStats) + r.Get("/mounts", s.servantMounts) + r.Get("/files/recent", s.servantRecentFiles) + r.Get("/files", s.servantFiles) + r.Get("/files/count", s.servantFileCount) + r.Get("/folders", s.servantFolders) + r.Get("/browse", s.servantBrowse) + r.Get("/watch", s.servantWatch) + r.With(s.internalServiceAuth).Get("/downloads", s.servantDownloads) + r.With(s.internalServiceAuth).Post("/reload-mounts", s.servantReloadMounts) + r.With(s.internalServiceAuth).Get("/probe", s.servantProbeFile) + protected := r.With(s.auth.Optional, s.requireAdminOrInternal) + protected.Post("/upload", s.servantUpload) + protected.Post("/upload-mounted", s.servantUpload) + protected.Delete("/downloads/{filename}", s.servantDeleteDownload) + protected.Post("/store", s.servantStore) + internal := r.With(s.internalServiceAuth) + internal.Post("/thumbnails/{id}", s.servantThumbnailUpload) + internal.Delete("/thumbnails/{id}", s.servantThumbnailDelete) + internal.Post("/outputs/{name}", s.servantOutputUpload) + internal.Post("/inputs/{name}", s.servantInputUpload) + internal.Post("/copies/{name}", s.servantCopyUpload) +} + +func (s *Server) servantStats(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) servantMounts(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) servantRecentFiles(w http.ResponseWriter, r *http.Request) { + s.writeServantFiles(w, r, true) +} +func (s *Server) servantFiles(w http.ResponseWriter, r *http.Request) { + s.writeServantFiles(w, r, false) +} + +func (s *Server) servantFileCount(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) writeServantFiles(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. Lookout 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) servantFolders(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) servantBrowse(w http.ResponseWriter, r *http.Request) { s.servantFiles(w, r) } + +func (s *Server) servantWatch(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) servantReloadMounts(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Server) servantDownloads(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 MediaConfig's +// Mounts 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("servant: 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) servantUpload(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") { + s.servantRawUpload(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) servantDeleteDownload(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) servantStore(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 Servant's own local-filesystem lookup for /api/store, which catalogs a +// file Forge already pushed into one of Servant'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) servantRawUpload(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) servantMedia(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) servantDownloadMedia(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) servantGeneratedMedia(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) servantThumbnail(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) servantInputMedia(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) servantCopyMedia(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) +} + +// servantStreamUpload 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 servantRawUpload's existing filename handling). +func (s *Server) servantStreamUpload(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) servantThumbnailUpload(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.servantStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg") +} + +func (s *Server) servantThumbnailDelete(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) servantOutputUpload(w http.ResponseWriter, r *http.Request) { + s.servantStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name")) +} + +func (s *Server) servantInputUpload(w http.ResponseWriter, r *http.Request) { + s.servantStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name")) +} + +func (s *Server) servantCopyUpload(w http.ResponseWriter, r *http.Request) { + s.servantStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name")) +} + +func (s *Server) servantProbeFile(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) mountDesktopRoutes(r chi.Router) { + r.Get("/status", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": "MediaDesktop", "native": true}) + }) +} + +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" + } +} + +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/media-backend/internal/server/analyzer.go b/media-backend/internal/server/analyzer.go new file mode 100644 index 0000000..0152676 --- /dev/null +++ b/media-backend/internal/server/analyzer.go @@ -0,0 +1,2182 @@ +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" + + "mediacollection/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. Porter 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.fetchServantToScratch(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.servantPushThumbnail(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.servantDeleteThumbnail(ctx, thumbnailID) + return "", fmt.Errorf("save thumbnail record: %w", err) + } + if insertTag.RowsAffected() == 0 { + _ = s.servantDeleteThumbnail(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.proxyServant(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.probeServant(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.servantDeleteThumbnail(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.servantListFiles(ctx, "", false, 0) + if err != nil { + log.Printf("analyzer: discovery scan: failed to list files: %v", err) + runErr = fmt.Errorf("could not reach Porter to list files: %w", err) + return + } + // Porter 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: Porter reported zero files") + runErr = fmt.Errorf("Porter reported no files under its configured media root(s) - check the Mounts settings in MediaConfig") + 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 + // Servant has the storage mounted and can probe/stat locally; every other service goes + // through Servant's HTTP API instead of touching MediaRoots itself (see servant_client.go). + if s.cfg.Service == config.Servant { + 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 servantProbeResult + probe, probeErr = s.servantProbe(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.probeServant(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.servantProbe(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 +// (Lookout) - it checks for the sidecar on Servant 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.probeServant(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.servantDeleteThumbnail(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/media-backend/internal/server/analyzer_ai.go b/media-backend/internal/server/analyzer_ai.go new file mode 100644 index 0000000..f901bc7 --- /dev/null +++ b/media-backend/internal/server/analyzer_ai.go @@ -0,0 +1,710 @@ +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 Servant 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.fetchServantToScratch(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.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil { + return scratchPath, cleanup, nil + } + } + + videoScratch, cleanupVideo, err := s.fetchServantToScratch(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 Lookout/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.servantProbe(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/media-backend/internal/server/analyzer_schedule.go b/media-backend/internal/server/analyzer_schedule.go new file mode 100644 index 0000000..4e4b7cb --- /dev/null +++ b/media-backend/internal/server/analyzer_schedule.go @@ -0,0 +1,139 @@ +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/media-backend/internal/server/kiosk.go b/media-backend/internal/server/kiosk.go new file mode 100644 index 0000000..bb43d1e --- /dev/null +++ b/media-backend/internal/server/kiosk.go @@ -0,0 +1,195 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "github.com/coder/websocket" + "github.com/go-chi/chi/v5" + + "mediacollection/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.servantListFiles(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.proxyServant(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/media-backend/internal/server/media.go b/media-backend/internal/server/media.go new file mode 100644 index 0000000..c3ab6d5 --- /dev/null +++ b/media-backend/internal/server/media.go @@ -0,0 +1,1078 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + + "mediacollection/internal/auth" +) + +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) +} + +func (s *Server) getSyncState(w http.ResponseWriter, r *http.Request) { + sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default")) + writeJSON(w, http.StatusOK, s.sync.httpState(sessionID)) +} + +func (s *Server) 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") + return + } + clientID := boundedSyncString(syncString(input, "clientId")) + if clientID == "" { + writeError(w, http.StatusBadRequest, "clientId is required") + return + } + sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default")) + state := map[string]any{ + "sessionId": sessionID, + "mediaId": input["mediaId"], + "timeMs": syncInt(input, "timeMs", 0), + "paused": syncBool(input, "paused"), + "fps": syncFPS(input), + "frame": syncInt(input, "frame", 0), + "fromClientId": clientID, + "updatedAt": time.Now().UTC().Format(time.RFC3339Nano), + } + if value, ok := input["playAt"]; ok { + state["playAt"] = value + } + s.sync.setHTTPState(sessionID, state) + s.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) +} + +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 (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) + if err != nil { + writeError(w, http.StatusNotFound, "media not found") + return + } + s.proxyServant(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 (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) { + id := identifier + 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.probeServant(r.Context(), thumbnailPath); err == nil && exists { + s.proxyServant(w, r, thumbnailPath) + return + } + } + record, err := s.findMedia(r.Context(), id) + if err != nil || !isImagePath(record.FilePath) { + writeError(w, http.StatusNotFound, "thumbnail not found") + return + } + s.proxyServant(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.probeServant(r.Context(), candidatePath); err == nil && exists { + s.proxyServant(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.probeServant(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) { + 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()) + 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 { + 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) + 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) + } + 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 (s *Server) mediaSave(w http.ResponseWriter, r *http.Request) { + s.mediaStatMutation(w, r, "save") +} + +func (s *Server) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { + user := auth.UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, "not authenticated") + return + } + var input struct { + MediaKey string `json:"mediaKey"` + Like *bool `json:"like"` + Save *bool `json:"save"` + Value *bool `json:"value"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + key := strings.TrimSpace(input.MediaKey) + if key == "" { + writeError(w, http.StatusBadRequest, "missing mediaKey") + return + } + enabled := true + if statType == "like" && input.Like != nil { + enabled = *input.Like + } + if statType == "save" && input.Save != nil { + enabled = *input.Save + } + if input.Value != nil { + 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) + 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) + } + 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()) + var input struct { + MediaKey string `json:"mediaKey"` + } + if r.Body != nil && r.ContentLength != 0 { + _ = decodeRequestJSON(r, &input) + } + key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey"))) + if key == "" { + writeError(w, http.StatusBadRequest, "missing mediaKey") + return + } + var userID any + 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 { + 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()) + var input struct { + MediaKey string `json:"mediaKey"` + DurationMs int64 `json:"durationMs"` + Duration int64 `json:"duration"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + duration := input.DurationMs + if duration <= 0 { + duration = input.Duration + } + if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 { + writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required") + return + } + var userID any + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "view session could not be recorded") + return + } + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "liked media unavailable") + return + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var key string + var created time.Time + if rows.Scan(&key, &created) == nil { + items = append(items, map[string]any{"mediaKey": key, "createdAt": created, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}) + } + } + writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items}) +} + +func (s *Server) mediaTags(w http.ResponseWriter, r *http.Request) { + key := strings.TrimSpace(chi.URLParam(r, "id")) + rows, err := s.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) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) + return + } + defer rows.Close() + tags := make([]map[string]any, 0) + for rows.Next() { + var tag string + var score int64 + if rows.Scan(&tag, &score) == nil { + tags = append(tags, map[string]any{"tag": tag, "score": score, "myVote": 0}) + } + } + writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) +} + +func (s *Server) addMediaTag(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + var input struct { + Tag string `json:"tag"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + tag := strings.TrimSpace(input.Tag) + if tag == "" || len([]rune(tag)) > 80 { + writeError(w, http.StatusBadRequest, "tag is invalid") + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "tag could not be added") + return + } + writeJSON(w, http.StatusCreated, map[string]any{"tag": tag}) +} + +func (s *Server) voteMediaTag(w http.ResponseWriter, r *http.Request) { + user := auth.UserFromContext(r.Context()) + var input struct { + Vote int `json:"vote"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + if input.Vote != -1 && input.Vote != 0 && input.Vote != 1 { + writeError(w, http.StatusBadRequest, "vote must be -1, 0, or 1") + return + } + 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) + } 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "tag vote failed") + return + } + } + writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote}) +} + +func (s *Server) 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) + if err != nil { + writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) + return + } + defer rows.Close() + tags := make([]map[string]any, 0) + for rows.Next() { + var tag string + var count int64 + if rows.Scan(&tag, &count) == nil { + tags = append(tags, map[string]any{"tag": tag, "count": count}) + } + } + writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) +} + +func (s *Server) 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "tag media unavailable") + return + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var key string + if rows.Scan(&key) == nil { + items = append(items, map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key), "name": filepath.Base(urlPath(key))}) + } + } + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "playlists unavailable") + return + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var id int64 + var name string + var created time.Time + if rows.Scan(&id, &name, &created) == nil { + items = append(items, map[string]any{"id": id, "name": name, "createdAt": created}) + } + } + 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()) + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "playlist summary unavailable") + return + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var id, count int64 + var name string + var created time.Time + if rows.Scan(&id, &name, &created, &count) == nil { + items = append(items, map[string]any{"id": id, "name": name, "item_count": count, "createdAt": created}) + } + } + 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()) + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil || user == nil { + writeError(w, http.StatusNotFound, "playlist not found") + return + } + 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 { + 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()) + var input struct { + Name string `json:"name"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + name := strings.TrimSpace(input.Name) + if name == "" || len([]rune(name)) > 120 { + 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) + 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 { + 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()) + 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) + if err != nil || result.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "playlist not found") + return + } + 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()) + 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 { + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "playlist items unavailable") + return + } + defer rows.Close() + items := make([]map[string]any, 0) + for rows.Next() { + var itemID int64 + var key string + var position int + var created time.Time + if rows.Scan(&itemID, &key, &position, &created) == nil { + items = append(items, map[string]any{"id": itemID, "media_key": key, "mediaKey": key, "position": position, "createdAt": created, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}) + } + } + 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()) + 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 { + writeError(w, http.StatusNotFound, "playlist not found") + return + } + var input struct { + MediaKey string `json:"mediaKey"` + MediaKeySnake string `json:"media_key"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + key := strings.TrimSpace(firstNonEmpty(input.MediaKey, input.MediaKeySnake)) + if key == "" { + 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) + if err != nil { + writeError(w, http.StatusInternalServerError, "playlist item could not be added") + return + } + 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()) + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid playlist id") + return + } + var input struct { + MediaKey string `json:"mediaKey"` + MediaKeySnake string `json:"media_key"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + 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) + if err != nil || result.RowsAffected() == 0 { + writeError(w, http.StatusNotFound, "playlist item not found") + return + } + 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()) + if user == nil { + writeError(w, http.StatusNotFound, "playlist not found") + return + } + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid playlist id") + 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 { + 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()) + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid playlist id") + return + } + var input struct { + IDs []int64 `json:"ids"` + ItemIDs []int64 `json:"itemIds"` + } + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + ids := input.IDs + if len(ids) == 0 { + 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) + } + 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()) + if user == nil { + writeJSON(w, http.StatusOK, map[string]any{"user": nil}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": user}) +} + +func (s *Server) findMedia(ctx context.Context, identifier string) (MediaRecord, error) { + identifier = strings.TrimSpace(identifier) + var record MediaRecord + row := s.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), + COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), COALESCE(speed, 0), COALESCE(modified_at, created_at) + FROM media WHERE media_key=$1 OR CAST(id AS TEXT)=$1 LIMIT 1`, identifier) + 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 MediaRecord{}, 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 +} + +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 { + filename := record.OriginalName + if filename == "" { + filename = filepath.Base(urlPath(record.FilePath)) + } + mediaType := record.MediaType + if mediaType == "unknown" || mediaType == "" { + mediaType = inferMediaType(filename) + } + return map[string]any{ + "id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey, + "filename": filename, "name": filename, "title": record.Title, "description": record.Description, + "relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source, + "url": mediaStreamURL(record.MediaKey), "thumbnail": mediaThumbnailURL(record.MediaKey), + "width": intValue(record.Width), "height": intValue(record.Height), "durationMs": int64Value(record.DurationMs), + "sizeBytes": int64Value(record.SizeBytes), "isVr": record.IsVR, "hasFunscript": record.HasFunscript, "speed": floatValue(record.Speed), + "modifiedAt": record.ModifiedAt, + } +} + +func (s *Server) resolveMediaPath(ctx context.Context, relative string) (string, error) { + return s.resolveUnderRoots(relative, s.effectiveMediaRoots(ctx)) +} + +// 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) +} + +func (s *Server) resolveThumbnailPath(relative string) (string, error) { + return s.resolveUnderRoots(relative, []string{s.cfg.ThumbnailRoot}) +} + +func (s *Server) resolveUnderRoots(value string, roots []string) (string, error) { + value = strings.TrimSpace(strings.TrimPrefix(value, "/media/")) + value = strings.TrimPrefix(value, "/") + if value == "" || strings.ContainsRune(value, 0) { + return "", errors.New("empty path") + } + for _, root := range roots { + rootAbs, err := filepath.Abs(root) + if err != nil { + continue + } + candidate := value + if !filepath.IsAbs(candidate) { + candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate)) + } + candidate, err = filepath.Abs(candidate) + if err != nil || !withinRoot(rootAbs, candidate) { + continue + } + info, err := os.Stat(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) { + file, err := os.Open(fullPath) + if err != nil { + writeError(w, http.StatusNotFound, "file not found") + return + } + defer file.Close() + info, err := file.Stat() + if err != nil || info.IsDir() { + writeError(w, http.StatusNotFound, "file not found") + return + } + if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" { + w.Header().Set("Content-Type", contentType) + } + 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 + } + 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 { + switch strings.ToLower(filepath.Ext(value)) { + case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg": + return true + default: + return false + } +} + +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)) +} + +func mediaThumbnailURL(identifier string) string { + return "/api/media/thumb?mediaKey=" + url.QueryEscape(strings.TrimSpace(identifier)) +} + +func urlPath(value string) string { + value = strings.ReplaceAll(value, `\`, "/") + value = strings.TrimPrefix(value, "/") + value = strings.TrimPrefix(value, "media/") + return value +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return value + } + } + return "" +} diff --git a/media-backend/internal/server/path_test.go b/media-backend/internal/server/path_test.go new file mode 100644 index 0000000..d60883a --- /dev/null +++ b/media-backend/internal/server/path_test.go @@ -0,0 +1,83 @@ +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/media-backend/internal/server/servant_client.go b/media-backend/internal/server/servant_client.go new file mode 100644 index 0000000..f51f73f --- /dev/null +++ b/media-backend/internal/server/servant_client.go @@ -0,0 +1,331 @@ +package server + +// Servant client: every non-Servant service serves and stores media by calling Porter's +// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/ +// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those +// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's +// own code path. + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +// servantHTTPClient has no blanket timeout since it streams large media files; callers bound +// individual calls with a context deadline instead. +var servantHTTPClient = &http.Client{} + +func (s *Server) servantClient() *http.Client { + return servantHTTPClient +} + +// servantBaseURL is configured in MediaConfig and stored in the settings table (key +// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for +// every project's connection URL) - not a static env var, so a change in MediaConfig takes +// effect on every service's very next request without a restart. SERVANT_URL is only the +// bootstrap fallback before that setting has ever been saved. +func (s *Server) servantBaseURL(ctx context.Context) string { + return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/") +} + +func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { + request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(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 servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"} +var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"} + +// proxyServant streams a Servant 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) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) { + request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil) + if err != nil { + writeError(w, http.StatusBadGateway, "media service unavailable") + return + } + for _, header := range servantForwardRequestHeaders { + if value := r.Header.Get(header); value != "" { + request.Header.Set(header, value) + } + } + response, err := s.servantClient().Do(request) + if err != nil { + writeError(w, http.StatusBadGateway, "media service unavailable") + return + } + defer response.Body.Close() + for _, header := range servantForwardResponseHeaders { + 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) + } +} + +// probeServant checks whether a Servant-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) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) { + request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil) + if err != nil { + return false, 0, time.Time{}, err + } + response, err := s.servantClient().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("servant 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 +} + +// fetchServantToScratch downloads a Servant-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) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) { + request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil) + if err != nil { + return "", nil, err + } + response, err := s.servantClient().Do(request) + if err != nil { + return "", nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status) + } + scratch, err := os.CreateTemp("", "servant-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 +} + +// pushToServant streams a local file as the request body without buffering it in memory. +func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) { + file, err := os.Open(localPath) + if err != nil { + return nil, err + } + defer file.Close() + request, err := s.newServantRequest(ctx, method, servantPath, file) + if err != nil { + return nil, err + } + if info, statErr := file.Stat(); statErr == nil { + request.ContentLength = info.Size() + } + response, err := s.servantClient().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("servant push failed: %s: %s", response.Status, string(body)) + } + return response, nil +} + +func servantPushedSize(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) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) { + response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath) + if err != nil { + return 0, err + } + return servantPushedSize(response), nil +} + +func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error { + request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil) + if err != nil { + return err + } + response, err := s.servantClient().Do(request) + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound { + return fmt.Errorf("servant delete thumbnail failed: %s", response.Status) + } + return nil +} + +func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) { + response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return servantPushedSize(response), nil +} + +func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) { + response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return servantPushedSize(response), nil +} + +func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) { + response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath) + if err != nil { + return 0, err + } + return servantPushedSize(response), nil +} + +// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download +// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint. +func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) { + response, err := s.pushToServant(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 +} + +// servantStoreDownload catalogs an already-uploaded file into Servant'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) servantStoreDownload(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.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body)) + if err != nil { + return nil, err + } + request.Header.Set("Content-Type", "application/json") + response, err := s.servantClient().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("servant store failed: %s: %s", response.Status, string(errorBody)) + } + var payload map[string]any + _ = json.NewDecoder(response.Body).Decode(&payload) + return payload, nil +} + +// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent) +// endpoints - the replacement for a local filepath.WalkDir over MediaRoots. +func (s *Server) servantListFiles(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.newServantRequest(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + response, err := s.servantClient().Do(request) + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, fmt.Errorf("servant 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 servantProbeResult struct { + DurationMs int64 `json:"durationMs"` + Width int `json:"width"` + Height int `json:"height"` +} + +// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the +// metadata fields - bytes never leave Servant, unlike every other helper in this file. +func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) { + query := url.Values{} + query.Set("path", relative) + request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil) + if err != nil { + return servantProbeResult{}, err + } + response, err := s.servantClient().Do(request) + if err != nil { + return servantProbeResult{}, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status) + } + var result servantProbeResult + if err := json.NewDecoder(response.Body).Decode(&result); err != nil { + return servantProbeResult{}, err + } + return result, nil +} diff --git a/media-backend/internal/server/server.go b/media-backend/internal/server/server.go new file mode 100644 index 0000000..5ade02b --- /dev/null +++ b/media-backend/internal/server/server.go @@ -0,0 +1,433 @@ +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" + + "mediacollection/internal/auth" + "mediacollection/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. Porter 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), + 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.Post("/reset/request", s.auth.RequestAdminReset) + r.Post("/reset/confirm", s.auth.ConfirmAdminReset) + 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.Servant { + internal := s.internalServiceAuth + router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia))) + router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia))) + router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia))) + router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia))) + router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia))) + router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail))) + } + + 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.Tools: + s.mountToolsRoutes(r) + case config.Analyzer: + s.mountAnalyzerRoutes(r) + case config.ConfigService: + s.mountConfigRoutes(r) + case config.Moderator: + s.mountModeratorRoutes(r) + case config.Kiosk: + s.mountKioskRoutes(r) + case config.Servant: + s.mountServantRoutes(r) + case config.Desktop: + s.mountDesktopRoutes(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.Analyzer { + go s.runAnalyzerScheduler(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/media-backend/internal/server/sync.go b/media-backend/internal/server/sync.go new file mode 100644 index 0000000..33da0a0 --- /dev/null +++ b/media-backend/internal/server/sync.go @@ -0,0 +1,541 @@ +package server + +import ( + "context" + "encoding/json" + "math" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "github.com/coder/websocket" +) + +const ( + maxSyncIdentifier = 128 + maxSyncSessions = 1000 +) + +type syncPeer struct { + conn *websocket.Conn + writeMu sync.Mutex + clientID string + sessionID string + userAgent string + ipAddress string + remoteControlEnabled bool + uiView string + uiMediaID any + uiMediaIDSet bool +} + +type syncHub struct { + mu sync.Mutex + peers map[*syncPeer]struct{} + states map[string]map[string]any + playAt map[string]string + playAtLocalMs map[string]int64 + capturedAtMs map[string]int64 + controlOwners map[string]string +} + +func newSyncHub() *syncHub { + return &syncHub{ + peers: make(map[*syncPeer]struct{}), + states: make(map[string]map[string]any), + playAt: make(map[string]string), + playAtLocalMs: make(map[string]int64), + capturedAtMs: make(map[string]int64), + controlOwners: make(map[string]string), + } +} + +func (h *syncHub) add(peer *syncPeer) { + h.mu.Lock() + h.peers[peer] = struct{}{} + h.mu.Unlock() +} + +func (h *syncHub) remove(peer *syncPeer) string { + h.mu.Lock() + defer h.mu.Unlock() + delete(h.peers, peer) + if peer.clientID != "" && !h.hasClientLocked(peer.clientID) { + delete(h.controlOwners, peer.clientID) + for targetID, ownerID := range h.controlOwners { + if ownerID == peer.clientID { + delete(h.controlOwners, targetID) + } + } + } + return peer.sessionID +} + +func (h *syncHub) hasClientLocked(clientID string) bool { + for peer := range h.peers { + if peer.clientID == clientID { + return true + } + } + return false +} + +func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) { + h.mu.Lock() + if clientID != "" { + peer.clientID = clientID + } + if sessionID != "" { + peer.sessionID = sessionID + } + h.mu.Unlock() +} + +func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) { + h.mu.Lock() + defer h.mu.Unlock() + if sessionID != "" { + peer.sessionID = sessionID + } + if view != "" { + peer.uiView = view + } + if mediaIDSet { + peer.uiMediaID = mediaID + peer.uiMediaIDSet = true + } + if remoteSet { + peer.remoteControlEnabled = remote + if !remote && h.controlOwners[peer.clientID] != "" { + delete(h.controlOwners, peer.clientID) + } + } +} + +func (h *syncHub) clientsLocked(sessionID string) []map[string]any { + byID := make(map[string]map[string]any) + for peer := range h.peers { + if peer.sessionID != sessionID || peer.clientID == "" { + continue + } + entry, exists := byID[peer.clientID] + if !exists { + entry = map[string]any{ + "clientId": peer.clientID, + "userAgent": peer.userAgent, + "ipAddress": peer.ipAddress, + "remoteControlEnabled": peer.remoteControlEnabled, + "controlOwnerClientId": nil, + } + byID[peer.clientID] = entry + } else if peer.remoteControlEnabled { + entry["remoteControlEnabled"] = true + } + if peer.uiView != "" { + entry["uiView"] = peer.uiView + } + if peer.uiMediaIDSet { + entry["uiMediaId"] = peer.uiMediaID + } + } + for clientID, entry := range byID { + if owner := h.controlOwners[clientID]; owner != "" { + entry["controlOwnerClientId"] = owner + } + } + clients := make([]map[string]any, 0, len(byID)) + for _, entry := range byID { + clients = append(clients, entry) + } + return clients +} + +func (h *syncHub) stateLocked(sessionID string) map[string]any { + state, ok := h.states[sessionID] + if !ok { + return map[string]any{ + "sessionId": sessionID, + "mediaId": nil, + "timeMs": int64(0), + "paused": true, + "fps": 30, + "frame": int64(0), + "fromClientId": "", + "updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano), + } + } + return cloneMap(state) +} + +func (h *syncHub) 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) { + h.mu.Lock() + defer h.mu.Unlock() + h.states[sessionID] = cloneMap(state) + if len(h.states) > maxSyncSessions { + for key := range h.states { + delete(h.states, key) + break + } + } +} + +func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[string]any { + paused, _ := state["paused"].(bool) + if !paused { + if value := h.playAt[sessionID]; value != "" { + state["playAt"] = value + } + } + if value, ok := h.playAtLocalMs[sessionID]; ok { + state["playAtLocalMs"] = value + } + if value, ok := h.capturedAtMs[sessionID]; ok { + state["capturedAtLocalMs"] = value + } + return state +} + +func (h *syncHub) 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) + } + } + 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") + } + } +} + +func (peer *syncPeer) send(message any) error { + data, err := json.Marshal(message) + if err != nil { + return err + } + peer.writeMu.Lock() + defer peer.writeMu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + return peer.conn.Write(ctx, websocket.MessageText, data) +} + +func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions { + options := &websocket.AcceptOptions{} + if s.cfg.AllowedOrigin == "*" { + options.InsecureSkipVerify = true + return options + } + + patterns := make([]string, 0, 2) + addOrigin := func(value string) { + parsed, err := url.Parse(strings.TrimSpace(value)) + if err == nil && parsed.Scheme != "" && parsed.Host != "" { + patterns = append(patterns, parsed.Scheme+"://"+parsed.Host) + } + } + addOrigin(s.cfg.AllowedOrigin) + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + addOrigin(scheme + "://" + r.Host) + options.OriginPatterns = patterns + return options +} + +func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) { + conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r)) + if err != nil { + return + } + peer := &syncPeer{ + 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) + defer func() { + sessionID := s.sync.remove(peer) + _ = conn.Close(websocket.StatusNormalClosure, "") + if sessionID != "" { + s.sync.broadcast(sessionID) + } + }() + + _ = peer.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()}) + for { + messageType, payload, readErr := conn.Read(r.Context()) + if readErr != nil { + return + } + if messageType != websocket.MessageText { + continue + } + var message map[string]any + if json.Unmarshal(payload, &message) != nil { + continue + } + s.handleSyncMessage(peer, message) + } +} + +func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) { + typ, _ := message["type"].(string) + switch typ { + case "ws:ping": + _ = peer.send(map[string]any{ + "type": "ws:pong", + "nonce": syncString(message, "nonce"), + "clientSentAt": syncNumberValue(message, "clientSentAt"), + "serverReceivedAt": time.Now().UnixMilli(), + }) + case "sync:hello": + clientID := boundedSyncString(syncString(message, "clientId")) + sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default")) + if clientID == "" || sessionID == "" { + return + } + s.sync.updatePeer(peer, clientID, sessionID) + s.sync.broadcast(sessionID) + case "client:status": + clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID)) + sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default")) + if clientID == "" { + return + } + s.sync.updatePeer(peer, 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) + case "control:claim", "control:release": + s.handleControlMessage(peer, typ, message) + case "sync:update": + s.handleSyncUpdate(peer, 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")) + targetID := boundedSyncString(syncString(message, "targetClientId")) + if requesterID == "" || targetID == "" || requesterID != peer.clientID { + return + } + + s.sync.mu.Lock() + owner := s.sync.controlOwners[targetID] + ok := false + reason := "" + if typ == "control:claim" { + enabled := false + for candidate := range s.sync.peers { + if candidate.clientID == targetID && candidate.remoteControlEnabled { + enabled = true + break + } + } + switch { + case !enabled: + reason = "disabled" + case owner != "" && owner != requesterID: + reason = "busy" + default: + s.sync.controlOwners[targetID] = requesterID + owner = requesterID + ok = true + } + } else if owner != "" && owner != requesterID { + reason = "not-owner" + } else { + delete(s.sync.controlOwners, targetID) + owner = "" + ok = true + } + s.sync.mu.Unlock() + + _ = peer.send(map[string]any{ + "type": "control:ack", + "ok": ok, + "action": strings.TrimPrefix(typ, "control:"), + "targetClientId": targetID, + "ownerClientId": nullableString(owner), + "reason": nullableString(reason), + }) + s.sync.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 { + return + } + mediaID, _ := syncMediaID(message) + paused := syncBool(message, "paused") + state := map[string]any{ + "sessionId": sessionID, + "mediaId": mediaID, + "timeMs": syncInt(message, "timeMs", 0), + "paused": paused, + "fps": syncFPS(message), + "frame": syncInt(message, "frame", 0), + "fromClientId": clientID, + "updatedAt": time.Now().UTC().Format(time.RFC3339Nano), + } + for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} { + if value, ok := message[key]; ok { + state[key] = value + } + } + toClientID := boundedSyncString(syncString(message, "toClientId")) + playAtRaw, hasPlayAt := message["playAt"] + + s.sync.mu.Lock() + if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" { + delete(s.sync.playAt, sessionID) + delete(s.sync.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) + if local := syncInt(message, "playAtLocalMs", 0); local > 0 { + s.sync.playAtLocalMs[sessionID] = local + } else { + delete(s.sync.playAtLocalMs, sessionID) + } + } + if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 { + s.sync.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) + break + } + } + } + state = s.sync.timingLocked(sessionID, state) + clients := s.sync.clientsLocked(sessionID) + peers := make([]*syncPeer, 0) + if toClientID != "" { + for candidate := range s.sync.peers { + if candidate.sessionID == sessionID && candidate.clientID == toClientID { + peers = append(peers, candidate) + } + } + } + s.sync.mu.Unlock() + + messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients} + if toClientID != "" { + for _, target := range peers { + if err := target.send(messageOut); err != nil { + _ = target.conn.Close(websocket.StatusGoingAway, "write failed") + } + } + return + } + s.sync.broadcast(sessionID) +} + +func syncMediaID(message map[string]any) (any, bool) { + value, ok := message["mediaId"] + if !ok { + return nil, false + } + if value == nil { + return nil, true + } + return boundedSyncString(syncStringValue(value)), true +} + +func syncString(message map[string]any, key string) string { + return syncStringValue(message[key]) +} + +func syncStringValue(value any) string { + if value == nil { + return "" + } + if text, ok := value.(string); ok { + return strings.TrimSpace(text) + } + return "" +} + +func boundedSyncString(value string) string { + 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 syncNumberValue(message map[string]any, key string) any { + if value, ok := message[key]; ok { + return value + } + return nil +} + +func syncInt(message map[string]any, key string, fallback int64) int64 { + value, ok := message[key].(float64) + if !ok || math.IsNaN(value) || math.IsInf(value, 0) { + return fallback + } + if value < 0 { + return 0 + } + if value > float64(^uint64(0)>>1) { + return int64(^uint64(0) >> 1) + } + return int64(math.Round(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 +} + +func nullableString(value string) any { + if value == "" { + return nil + } + return value +} + +func cloneMap(value map[string]any) map[string]any { + result := make(map[string]any, len(value)) + for key, item := range value { + result[key] = item + } + return result +} diff --git a/media-backend/internal/server/workflows.go b/media-backend/internal/server/workflows.go new file mode 100644 index 0000000..757e241 --- /dev/null +++ b/media-backend/internal/server/workflows.go @@ -0,0 +1,1005 @@ +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" + + "mediacollection/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.fetchWorkflowFileFromServant(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.servantPushOutput(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 Servant's upload endpoint also catalogs the file into media/media_worker_jobs + // (see servantRawUpload) - no separate indexMediaFile call needed here. + if _, err := s.servantUploadDownload(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 "" +} + +// workflowFileServantPaths mirrors the search order resolveWorkflowFile used to walk locally +// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as Servant-side mount prefixes, since +// Forge no longer has any of those roots mounted on its own filesystem. +var workflowFileServantPaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"} + +// fetchWorkflowFileFromServant locates a converter input under any of Servant'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) fetchWorkflowFileFromServant(ctx context.Context, value string) (string, func(), error) { + value = strings.TrimSpace(value) + if !safeRelative(value) { + return "", nil, os.ErrNotExist + } + for _, prefix := range workflowFileServantPaths { + servantPath := prefix + urlPath(value) + if exists, _, _, err := s.probeServant(ctx, servantPath); err != nil || !exists { + continue + } + return s.fetchServantToScratch(ctx, servantPath, 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.servantPushCopy) + 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.servantPushInput) + 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.proxyServant(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 + } + servantPath := "/mount/generated/" + urlPath(filename) + if exists, _, _, err := s.probeServant(r.Context(), servantPath); 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.proxyServant(w, r, servantPath) +} + +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/media-webui/.prettierignore b/media-webui/.prettierignore new file mode 100644 index 0000000..355d563 --- /dev/null +++ b/media-webui/.prettierignore @@ -0,0 +1,3 @@ +.svelte-kit/ +build/ +node_modules/ diff --git a/media-webui/README.md b/media-webui/README.md new file mode 100644 index 0000000..83d299b --- /dev/null +++ b/media-webui/README.md @@ -0,0 +1,18 @@ +# MediaCollection WebUI + +The browser-facing MediaCollection services 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/media-webui/eslint.config.js b/media-webui/eslint.config.js new file mode 100644 index 0000000..bd03842 --- /dev/null +++ b/media-webui/eslint.config.js @@ -0,0 +1,62 @@ +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/media-webui/package.json b/media-webui/package.json new file mode 100644 index 0000000..961f011 --- /dev/null +++ b/media-webui/package.json @@ -0,0 +1,53 @@ +{ + "name": "@gabriel20xx/media-collection-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:tools": "node scripts/build-all.mjs tools", + "build:analyzer": "node scripts/build-all.mjs analyzer", + "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:servant": "node scripts/build-all.mjs servant", + "build:desktop": "node scripts/build-all.mjs desktop", + "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/media-webui/prettier.config.js b/media-webui/prettier.config.js new file mode 100644 index 0000000..817a6f6 --- /dev/null +++ b/media-webui/prettier.config.js @@ -0,0 +1,9 @@ +/** @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/media-webui/project-icons.json b/media-webui/project-icons.json new file mode 100644 index 0000000..0b3fa19 --- /dev/null +++ b/media-webui/project-icons.json @@ -0,0 +1,10 @@ +{ + "viewer": { "name": "Playhouse", "icon": "play" }, + "tools": { "name": "Forge", "icon": "wand-sparkles" }, + "analyzer": { "name": "Lookout", "icon": "scan-search" }, + "config": { "name": "MediaConfig", "icon": "settings-2" }, + "moderator": { "name": "Warden", "icon": "shield-check" }, + "kiosk": { "name": "Marquee", "icon": "image" }, + "servant": { "name": "Porter", "icon": "server" }, + "desktop": { "name": "Beacon", "icon": "monitor-play" } +} diff --git a/media-webui/scripts/build-all.mjs b/media-webui/scripts/build-all.mjs new file mode 100644 index 0000000..d50125d --- /dev/null +++ b/media-webui/scripts/build-all.mjs @@ -0,0 +1,49 @@ +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 collectionDir = path.resolve(webUiDir, '..') +const targets = { + viewer: 'Playhouse', + tools: 'Forge', + analyzer: 'Lookout', + config: 'MediaConfig', + moderator: 'Warden', + kiosk: 'Marquee', + servant: 'Porter', + desktop: 'Beacon', +} + +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 MediaCollection 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(collectionDir, 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(collectionDir, target)}`) +} diff --git a/media-webui/scripts/project-favicon.mjs b/media-webui/scripts/project-favicon.mjs new file mode 100644 index 0000000..938dfee --- /dev/null +++ b/media-webui/scripts/project-favicon.mjs @@ -0,0 +1,49 @@ +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 MediaCollection project: ${appId}`) + + const iconNode = getIconNode(project.icon) + return ` + ${escapeAttribute(project.name)} +${iconNode.map(renderIconNode).join('\n')} + +` +} diff --git a/media-webui/src/app.css b/media-webui/src/app.css new file mode 100644 index 0000000..31eed21 --- /dev/null +++ b/media-webui/src/app.css @@ -0,0 +1,167 @@ +@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/media-webui/src/app.d.ts b/media-webui/src/app.d.ts new file mode 100644 index 0000000..3aa853e --- /dev/null +++ b/media-webui/src/app.d.ts @@ -0,0 +1,2 @@ +declare const __MEDIA_APP__: string +declare const __FRONTEND_TECH_STACK__: Array<{ name: string; version: string }> diff --git a/media-webui/src/app.html b/media-webui/src/app.html new file mode 100644 index 0000000..3e6d560 --- /dev/null +++ b/media-webui/src/app.html @@ -0,0 +1,14 @@ + + + + + + + + MediaCollection + %sveltekit.head% + + +
%sveltekit.body%
+ + diff --git a/media-webui/src/lib/api.ts b/media-webui/src/lib/api.ts new file mode 100644 index 0000000..75f8660 --- /dev/null +++ b/media-webui/src/lib/api.ts @@ -0,0 +1,55 @@ +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/media-webui/src/lib/app-config.ts b/media-webui/src/lib/app-config.ts new file mode 100644 index 0000000..5511690 --- /dev/null +++ b/media-webui/src/lib/app-config.ts @@ -0,0 +1,286 @@ +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: 'Playhouse', + 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.', + }, + ], + }, + tools: { + id: 'tools', + name: 'Forge', + icon: projectIcon('tools'), + 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.', + }, + ], + }, + analyzer: { + id: 'analyzer', + name: 'Lookout', + icon: projectIcon('analyzer'), + 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: 'MediaConfig', + icon: projectIcon('config'), + eyebrow: 'Platform configuration', + description: 'Connect services, configure mounts, and tune shared processing parameters.', + nav: [ + { + label: 'Mounts', + panel: 'mounts', + path: '/', + icon: 'hard-drive', + description: 'Configure collection mounts and connected storage.', + }, + { + label: 'Parameters', + panel: 'parameters', + path: '/parameters', + icon: 'sliders-horizontal', + description: 'Tune shared processing and service parameters.', + }, + ], + }, + moderator: { + id: 'moderator', + name: 'Warden', + 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: 'Marquee', + 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.', + }, + ], + }, + servant: { + id: 'servant', + name: 'Porter', + icon: projectIcon('servant'), + 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.', + }, + ], + }, + desktop: { + id: 'desktop', + name: 'Beacon', + icon: projectIcon('desktop'), + eyebrow: 'Connected player', + description: 'Control playback, funscripts, and connected devices from your desktop.', + nav: [ + { + label: 'Player', + panel: 'player', + path: '/', + icon: 'monitor-play', + description: 'Control playback and connected desktop devices.', + }, + { + label: 'Devices', + panel: 'devices', + path: '/devices', + icon: 'box', + description: 'Manage connected playback and funscript devices.', + }, + ], + }, +} + +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/media-webui/src/lib/components/AnalyzerHistory.svelte b/media-webui/src/lib/components/AnalyzerHistory.svelte new file mode 100644 index 0000000..6928301 --- /dev/null +++ b/media-webui/src/lib/components/AnalyzerHistory.svelte @@ -0,0 +1,211 @@ + + + + +
+ {#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/media-webui/src/lib/components/AnalyzerLiveStatus.svelte b/media-webui/src/lib/components/AnalyzerLiveStatus.svelte new file mode 100644 index 0000000..2edc184 --- /dev/null +++ b/media-webui/src/lib/components/AnalyzerLiveStatus.svelte @@ -0,0 +1,212 @@ + + + + + {#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/media-webui/src/lib/components/AnalyzerPipelineBreakdown.svelte b/media-webui/src/lib/components/AnalyzerPipelineBreakdown.svelte new file mode 100644 index 0000000..1fadc41 --- /dev/null +++ b/media-webui/src/lib/components/AnalyzerPipelineBreakdown.svelte @@ -0,0 +1,85 @@ + + + + +
+ {#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/media-webui/src/lib/components/AppShell.svelte b/media-webui/src/lib/components/AppShell.svelte new file mode 100644 index 0000000..c20b97a --- /dev/null +++ b/media-webui/src/lib/components/AppShell.svelte @@ -0,0 +1,292 @@ + + +{#if auth.loading || auth.error || auth.setupRequired || (auth.authRequired && !auth.user)} + +{:else} +
+ + +
+ +
+ + {@render children?.()} +
+
+{/if} + + + + + {#snippet icon()} + + {/snippet} + + + + + diff --git a/media-webui/src/lib/components/AuthPage.svelte b/media-webui/src/lib/components/AuthPage.svelte new file mode 100644 index 0000000..a7edff5 --- /dev/null +++ b/media-webui/src/lib/components/AuthPage.svelte @@ -0,0 +1,43 @@ + + + diff --git a/media-webui/src/lib/components/EmptyState.svelte b/media-webui/src/lib/components/EmptyState.svelte new file mode 100644 index 0000000..8629576 --- /dev/null +++ b/media-webui/src/lib/components/EmptyState.svelte @@ -0,0 +1,14 @@ + + +
+ +
+

{title}

+

{message}

+
+
diff --git a/media-webui/src/lib/components/PipelineFlowDiagram.svelte b/media-webui/src/lib/components/PipelineFlowDiagram.svelte new file mode 100644 index 0000000..23b40bd --- /dev/null +++ b/media-webui/src/lib/components/PipelineFlowDiagram.svelte @@ -0,0 +1,352 @@ + + +{#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/media-webui/src/lib/components/ProjectIcon.svelte b/media-webui/src/lib/components/ProjectIcon.svelte new file mode 100644 index 0000000..13c0513 --- /dev/null +++ b/media-webui/src/lib/components/ProjectIcon.svelte @@ -0,0 +1,20 @@ + + +