package server import ( "context" "encoding/json" "errors" "fmt" "io" "log" "net/http" "net/url" "os" "path/filepath" "regexp" "slices" "sort" "strconv" "strings" "time" "github.com/go-chi/chi/v5" "repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config" ) func (s *Server) mountConfigRoutes(r chi.Router) { admin := r.With(s.auth.RequireAdminIfLoginRequired) admin.Get("/settings", s.settings) admin.Post("/settings", s.saveSettings) admin.Post("/check-connection", s.checkConnection) admin.Post("/discover-service", s.discoverService) admin.Post("/settings/sync", s.settingsSync) r.With(s.internalServiceAuth).Get("/settings/export", s.settingsExport) r.Get("/info", s.configInfo) r.With(s.internalServiceAuth).Get("/mounts/paths", s.mountPaths) admin.Post("/mounts/paths", s.saveMountPaths) r.With(s.internalServiceAuth).Get("/mounts/resolve", s.resolveMount) } func (s *Server) settings(w http.ResponseWriter, r *http.Request) { rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, '') FROM settings ORDER BY key`) if err != nil { writeError(w, http.StatusInternalServerError, "settings unavailable") return } defer rows.Close() values := map[string]string{} for rows.Next() { var key, value string if rows.Scan(&key, &value) != nil || sensitiveSetting(key) { continue } values[key] = value } writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values}) } func (s *Server) saveSettings(w http.ResponseWriter, r *http.Request) { var updates map[string]any if err := decodeRequestJSON(r, &updates); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } if len(updates) > 200 { writeError(w, http.StatusBadRequest, "too many settings") return } count := 0 for key, value := range updates { if strings.TrimSpace(key) == "" || len(key) > 160 || (sensitiveSetting(key) && strings.TrimSpace(fmt.Sprint(value)) == "") { continue } text := fmt.Sprint(value) if encoded, ok := value.(map[string]any); ok { text = string(mustJSON(encoded)) } if _, err := s.db.Exec(r.Context(), `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, text); err != nil { writeError(w, http.StatusInternalServerError, "setting could not be saved") return } count++ } writeJSON(w, http.StatusOK, map[string]any{"success": true, "updated": count}) } // settingsExport is the full-fidelity counterpart to settings: every row (sensitive ones // included, since this is only ever reachable with the shared X-Internal-Auth secret) plus each // key's updated_at, so a peer ProjectConfigurator instance can merge it with its own by recency. // This is what makes running more than one ProjectConfigurator instance for high availability // actually converge, whether or not the instances share a single Postgres database. func (s *Server) settingsExport(w http.ResponseWriter, r *http.Request) { rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, ''), updated_at FROM settings ORDER BY key`) if err != nil { writeError(w, http.StatusInternalServerError, "settings unavailable") return } defer rows.Close() values := map[string]any{} for rows.Next() { var key, value string var updatedAt time.Time if rows.Scan(&key, &value, &updatedAt) != nil { continue } values[key] = map[string]any{"value": value, "updatedAt": updatedAt} } writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values}) } // projectConfiguratorPeers reads the other ProjectConfigurator instances an operator has // registered in the Projects workspace's Central services section (configured_central, the same // setting regularProjects/centralInstancesFor reads client-side) - every instance whose base name // is "ProjectConfigurator" except the unsuffixed entry, which by convention represents this // instance itself rather than a remote peer. func (s *Server) projectConfiguratorPeers(ctx context.Context) []string { raw := s.settingValue(ctx, "configured_central", "") var central []string if raw == "" || json.Unmarshal([]byte(raw), ¢ral) != nil { return nil } peers := make([]string, 0, len(central)) for _, project := range central { key := strings.ToLower(strings.TrimSpace(project)) if key == "" || key == "projectconfigurator" || instanceBaseKey(key) != "projectconfigurator" { continue } if peerURL := strings.TrimSpace(s.settingValue(ctx, key+"_url", "")); peerURL != "" { peers = append(peers, peerURL) } } return peers } // pullSettingsFrom fetches one peer's full settings export and applies every key that peer last // touched more recently than this instance did - last-write-wins per key, the same rule // saveSettings already applies within a single instance, just extended across instances. func (s *Server) pullSettingsFrom(ctx context.Context, peerURL string) (int, error) { target, err := normalizeServiceURL(peerURL) if err != nil { return 0, err } reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, strings.TrimRight(target, "/")+"/api/settings/export", nil) if err != nil { return 0, err } if s.cfg.InternalServiceSecret != "" { request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret) } response, err := http.DefaultClient.Do(request) if err != nil { return 0, err } defer response.Body.Close() if response.StatusCode != http.StatusOK { return 0, fmt.Errorf("peer returned status %d", response.StatusCode) } var body struct { Settings map[string]struct { Value string `json:"value"` UpdatedAt time.Time `json:"updatedAt"` } `json:"settings"` } if err := json.NewDecoder(io.LimitReader(response.Body, 4<<20)).Decode(&body); err != nil { return 0, err } updated := 0 for key, remote := range body.Settings { key = strings.TrimSpace(key) if key == "" || len(key) > 160 { continue } result, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,$3) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=EXCLUDED.updated_at WHERE settings.updated_at < EXCLUDED.updated_at`, key, remote.Value, remote.UpdatedAt) if err != nil { continue } if result.RowsAffected() > 0 { updated++ } } return updated, nil } // settingsSync is the "Sync now" button's endpoint: pull every registered ProjectConfigurator // peer's settings on demand, on top of the periodic background sync (runSettingsSyncScheduler). func (s *Server) settingsSync(w http.ResponseWriter, r *http.Request) { peers := s.projectConfiguratorPeers(r.Context()) results := make([]map[string]any, 0, len(peers)) updated := 0 for _, peer := range peers { count, err := s.pullSettingsFrom(r.Context(), peer) result := map[string]any{"url": peer} if err != nil { result["ok"] = false result["error"] = err.Error() } else { result["ok"] = true result["updated"] = count updated += count } results = append(results, result) } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "peers": len(peers), "updated": updated, "results": results}) } // runSettingsSyncScheduler periodically pulls every registered peer's settings so multiple // ProjectConfigurator instances converge on their own, without an operator needing to click // "Sync now" - the actual high-availability behavior. Only started for the config service (see // Run). A fresh deployment with no peers registered yet just polls configured_central and finds // nothing to do each tick, which is cheap enough not to bother special-casing. func (s *Server) runSettingsSyncScheduler(ctx context.Context) { ticker := time.NewTicker(2 * time.Minute) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: for _, peer := range s.projectConfiguratorPeers(ctx) { if _, err := s.pullSettingsFrom(ctx, peer); err != nil { log.Printf("settings sync: pulling from %s: %v", peer, err) } } } } } func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) { var input struct { URL string `json:"url"` Project string `json:"project"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } if strings.TrimSpace(input.URL) == "" { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "No URL provided"}) return } target, err := normalizeServiceURL(input.URL) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "service": nil, "mismatch": false, "error": err.Error()}) return } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/healthz", nil) response, err := http.DefaultClient.Do(request) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "service": nil, "mismatch": false}) return } defer response.Body.Close() var body struct { Service string `json:"service"` } _ = json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) mismatch := input.Project != "" && body.Service != "" && !strings.EqualFold(input.Project, body.Service) writeJSON(w, http.StatusOK, map[string]any{"ok": response.StatusCode < 500, "service": body.Service, "mismatch": mismatch}) } func (s *Server) configInfo(w http.ResponseWriter, r *http.Request) { host := r.Host if s.cfg.PublicURL != "" { host = s.cfg.PublicURL } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "hostname": host, "port": s.cfg.Port, "url": host, "name": s.cfg.ServiceName, "service": s.cfg.ServiceName, "tabs": serviceTabs(s.cfg.Service), "mountTypes": serviceMountTypes(s.cfg.Service), }) } // tabOption mirrors one entry of a project's nav (see webui's app-config.ts) plus the // global About dialog every instance exposes - the set of "pages" ProjectConfigurator's Projects // workspace lets an operator require login for individually. type tabOption struct { Label string `json:"label"` Token string `json:"token"` } // serviceTabsByService mirrors webui/src/lib/app-config.ts's nav per Service, plus the // About dialog (AppShell.svelte, not itself part of app.nav). Kept in sync by hand - there is no // single source of truth shared between the Go backend and the SvelteKit frontend for this. var serviceTabsByService = map[config.Service][]tabOption{ config.Viewer: { {"Library", "/"}, {"Feed", "/feed"}, {"Tags", "/tags"}, {"Playlists", "/playlists"}, {"About", "/about"}, }, config.Tools: { {"Generator", "/"}, {"Downloader", "/downloader"}, {"Converter", "/converter"}, {"Schedules", "/schedules"}, {"Library", "/library"}, {"About", "/about"}, }, config.Analyzer: { {"Dashboard", "/"}, {"Discover", "/discover"}, {"Images", "/images"}, {"Videos", "/videos"}, {"Audios", "/audios"}, {"Funscripts", "/funscripts"}, {"Schedules", "/schedules"}, {"About", "/about"}, }, config.ConfigService: {{"Projects", "/"}, {"About", "/about"}}, config.Moderator: { {"Dashboard", "/"}, {"Users", "/users"}, {"Media", "/media"}, {"About", "/about"}, }, config.Kiosk: {{"Kiosk", "/"}, {"About", "/about"}}, config.CarrierNode: {{"Overview", "/"}, {"Files", "/files"}, {"About", "/about"}}, } // serviceMountTypesByService mirrors ConfigWorkspace.svelte's PROJECT_AVAILABLE_MOUNTS - the // mount "type" values each service's own tab accepts when configuring its mounts. var serviceMountTypesByService = map[config.Service][]string{ config.Viewer: {"media", "thumbnails", "funscripts"}, config.Tools: {"downloads", "generated", "converted", "converter input", "generator input", "generator copy"}, config.Analyzer: {"images", "videos", "audios", "funscripts", "models", "thumbnails"}, config.Moderator: {"media", "thumbnails"}, config.Kiosk: {"media"}, config.CarrierNode: {"media", "output"}, config.ConfigService: {}, } func serviceTabs(service config.Service) []tabOption { if tabs, ok := serviceTabsByService[service]; ok { return tabs } return []tabOption{{"Main", "/"}, {"About", "/about"}} } func serviceMountTypes(service config.Service) []string { if types, ok := serviceMountTypesByService[service]; ok { return types } return []string{} } // discoverService lets ProjectConfigurator's Projects workspace populate a new service's name, // tabs, and mount types from just its URL: it fetches the target's own public GET /api/info // server-side (avoiding a browser CORS round-trip, same reasoning as checkConnection) and relays // whatever it reports. A target that doesn't implement this yet (or is unreachable) reports // {"ok":false} so the caller can fall back to manual entry instead of erroring out. func (s *Server) discoverService(w http.ResponseWriter, r *http.Request) { var input struct { URL string `json:"url"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } target, err := normalizeServiceURL(input.URL) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()}) return } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/api/info", nil) response, err := http.DefaultClient.Do(request) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "unreachable"}) return } defer response.Body.Close() var body struct { OK bool `json:"ok"` Name string `json:"name"` Service string `json:"service"` Tabs []tabOption `json:"tabs"` MountTypes []string `json:"mountTypes"` } if response.StatusCode >= 300 || json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) != nil { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "invalid response"}) return } name := strings.TrimSpace(body.Name) if name == "" { name = strings.TrimSpace(body.Service) } if name == "" { writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "service did not report a name"}) return } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "name": name, "tabs": body.Tabs, "mountTypes": body.MountTypes, }) } func (s *Server) mountPaths(w http.ResponseWriter, r *http.Request) { mappings := s.mountMappings(r.Context()) writeJSON(w, http.StatusOK, map[string]any{"success": true, "mappings": mappings}) } func (s *Server) saveMountPaths(w http.ResponseWriter, r *http.Request) { var payload struct { Mappings map[string]any `json:"mappings"` } if err := decodeRequestJSON(r, &payload); err != nil || payload.Mappings == nil { writeError(w, http.StatusBadRequest, "mappings are required") return } if err := s.saveSetting(r.Context(), "mounts_path_mappings", string(mustJSON(payload.Mappings))); err != nil { writeError(w, http.StatusInternalServerError, "mount mappings could not be saved") return } writeJSON(w, http.StatusOK, map[string]any{"success": true}) } func (s *Server) resolveMount(w http.ResponseWriter, r *http.Request) { project := r.URL.Query().Get("project") functionName := r.URL.Query().Get("function") if project == "" || functionName == "" { writeError(w, http.StatusBadRequest, "project and function required") return } mappings := s.mountMappings(r.Context()) projectValue, ok := mappings[project] if !ok { for key, value := range mappings { if strings.EqualFold(key, project) { projectValue, ok = value, true break } } } if !ok { writeError(w, http.StatusNotFound, "mapping not found") return } functions, ok := projectValue.(map[string]any) if !ok { writeError(w, http.StatusNotFound, "mapping not found") return } value, ok := functions[functionName] if !ok { writeError(w, http.StatusNotFound, "mapping not found") return } paths := normalizeMappingPaths(value) if filename := r.URL.Query().Get("filename"); filename != "" { for _, base := range paths { if !safeRelative(filename) { continue } if _, err := os.Stat(filepath.Join(base, filepath.FromSlash(filename))); err == nil { writeJSON(w, http.StatusOK, map[string]any{"success": true, "absolutePath": filepath.Join(base, filepath.FromSlash(filename)), "basePath": base, "filename": filename, "basePaths": paths}) return } } } if len(paths) == 0 { writeError(w, http.StatusNotFound, "mapping not found") return } writeJSON(w, http.StatusOK, map[string]any{"success": true, "absolutePath": paths[0], "basePath": paths[0], "filename": r.URL.Query().Get("filename"), "basePaths": paths}) } // mountEntry mirrors WebUI's ConfigWorkspace.svelte MountEntry ({type, path}) - one row in a // project's mount list in ProjectConfigurator's Projects workspace. type mountEntry struct { Type string `json:"type"` Path string `json:"path"` } // configuredMounts parses the configured_mounts setting - the live source ProjectConfigurator's // Projects workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project // key -> mount entries. Returns nil if unset or malformed. func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry { raw := s.settingValue(ctx, "configured_mounts", "") if raw == "" { return nil } var byProject map[string][]mountEntry if json.Unmarshal([]byte(raw), &byProject) != nil { return nil } return byProject } // mountMappings returns each project's mount configuration as project -> mount type -> path(s), // the shape /mounts/resolve and /mounts/paths (and CarrierNode's own "Mount health" panel via // /mounts) expect. configured_mounts is the live source and wins per-project when present; // mounts_path_mappings is an older format nothing has written since the Projects workspace moved // to configured_mounts, kept only so a deployment that hasn't resaved its mounts since upgrading // doesn't lose data it already had. Keys are used as stored, not case-normalized - configured_mounts // is processed first so a legacy entry for a project already covered there (under the exact same // key) is skipped instead of showing up as a second, redundant copy. func (s *Server) mountMappings(ctx context.Context) map[string]any { mappings := map[string]any{} seen := map[string]bool{} for project, entries := range s.configuredMounts(ctx) { key := strings.TrimSpace(project) if key == "" { continue } functions := map[string]any{} for _, entry := range entries { mountType := strings.TrimSpace(entry.Type) path := strings.TrimSpace(entry.Path) if mountType == "" || path == "" { continue } switch existing := functions[mountType].(type) { case nil: functions[mountType] = path case string: if existing != path { functions[mountType] = []string{existing, path} } case []string: if !slices.Contains(existing, path) { functions[mountType] = append(existing, path) } } } if len(functions) > 0 { mappings[key] = functions seen[key] = true } } legacyValue := s.settingValue(ctx, "mounts_path_mappings", "{}") var legacy map[string]any if json.Unmarshal([]byte(legacyValue), &legacy) == nil { for project, value := range legacy { key := strings.TrimSpace(project) if key == "" || seen[key] { continue } mappings[key] = value } } return mappings } // mediaLibraryMountTypes are the mount "type" values ProjectConfigurator's Projects workspace (the // configured_mounts setting) accepts that describe an actual media-library directory, as // opposed to a project-specific working directory like "downloads", "generated", // "thumbnails", or "models", which have their own dedicated Root config fields instead and // are deliberately left out here. A path is entered under whichever project's tab happens to // need it (MediaAnalyzer's "images"/"videos"/"audios", MediaViewer/MediaKiosk's "media", ...) // but they're all describing locations CarrierNode itself has to walk, since it's the only // service with the volume mounted - see effectiveMediaRoots. var mediaLibraryMountTypes = map[string]bool{ "media": true, "images": true, "videos": true, "audios": true, "funscripts": true, } // mediaRootsFromMounts extracts every distinct path configured under a media-library mount // type across every project in the configured_mounts setting. func (s *Server) mediaRootsFromMounts(ctx context.Context) []string { seen := map[string]bool{} roots := make([]string, 0) for _, entries := range s.configuredMounts(ctx) { for _, entry := range entries { path := strings.TrimSpace(entry.Path) if path == "" || !mediaLibraryMountTypes[strings.ToLower(strings.TrimSpace(entry.Type))] { continue } path = filepath.Clean(path) if seen[path] { continue } seen[path] = true roots = append(roots, path) } } return roots } // effectiveMediaRoots is what CarrierNode actually walks and resolves files under: the static // MEDIA_ROOTS/MEDIA_ROOT env config (if any) plus every media-library path configured through // ProjectConfigurator's Projects workspace, deduped. Settings are read fresh from the DB on every // call (no caching, same as carriernode_url/carrierNodeBaseURL), so a mount saved in // ProjectConfigurator takes effect on CarrierNode's very next request - no reload or restart needed. func (s *Server) effectiveMediaRoots(ctx context.Context) []string { seen := map[string]bool{} roots := make([]string, 0, len(s.cfg.MediaRoots)) for _, root := range append(append([]string{}, s.cfg.MediaRoots...), s.mediaRootsFromMounts(ctx)...) { if root == "" || seen[root] { continue } seen[root] = true roots = append(roots, root) } return roots } func (s *Server) mountModeratorRoutes(r chi.Router) { admin := r.With(s.auth.RequireAdmin) admin.Get("/admin/users", s.adminUsers) admin.Post("/admin/users", s.adminCreateUser) admin.Post("/admin/users/actions", s.adminUserActions) admin.Get("/admin/users/{id}/media", s.adminUserMedia) admin.Patch("/admin/users/{id}", s.adminUpdateUser) admin.Put("/admin/users/{id}", s.adminUpdateUser) admin.Delete("/admin/users/{id}", s.adminDeleteUser) admin.Get("/admin/media", s.adminMedia) admin.Post("/admin/media/actions", s.adminMediaActions) admin.Get("/admin/media/likers", s.adminMediaLikers) admin.Get("/admin/stats", s.adminStats) r.Get("/search/images", s.adminMedia) r.Get("/search/media", s.adminMedia) r.Get("/__ready", s.ready) } func (s *Server) adminUsers(w http.ResponseWriter, r *http.Request) { users, total, err := s.auth.ListUsers(r.Context(), r.URL.Query().Get("search"), optionalInt(r.URL.Query().Get("limit"), 50, 1, 200), 0) if err != nil { writeError(w, http.StatusInternalServerError, "users unavailable") return } writeJSON(w, http.StatusOK, map[string]any{"users": users, "items": users, "total": total}) } func (s *Server) adminCreateUser(w http.ResponseWriter, r *http.Request) { var input struct { Email string `json:"email"` Username string `json:"username"` Password string `json:"password"` Role string `json:"role"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } user, err := s.auth.CreateUser(r.Context(), input.Email, input.Username, input.Password, input.Role) if err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } writeJSON(w, http.StatusCreated, map[string]any{"user": user}) } func (s *Server) adminUpdateUser(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid user id") return } var input struct { Email string `json:"email"` Username string `json:"username"` Password string `json:"password"` Role string `json:"role"` Disabled *bool `json:"disabled"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } if err := s.auth.UpdateUser(r.Context(), id, input.Email, input.Username, input.Role, input.Disabled); err != nil { writeError(w, http.StatusBadRequest, "user could not be updated") return } if strings.TrimSpace(input.Password) != "" { if err := s.auth.SetPassword(r.Context(), id, input.Password); err != nil { writeError(w, http.StatusBadRequest, "password could not be updated") return } } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (s *Server) adminDeleteUser(w http.ResponseWriter, r *http.Request) { id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || s.auth.DeleteUser(r.Context(), id) != nil { writeError(w, http.StatusNotFound, "user not found") return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } func (s *Server) adminUserActions(w http.ResponseWriter, r *http.Request) { var input struct { Action string `json:"action"` IDs []json.RawMessage `json:"ids"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } for _, raw := range input.IDs { var id int64 if json.Unmarshal(raw, &id) != nil { var text string if json.Unmarshal(raw, &text) == nil { id, _ = strconv.ParseInt(text, 10, 64) } } if id == 0 { continue } switch strings.ToLower(input.Action) { case "delete": _ = s.auth.DeleteUser(r.Context(), id) case "disable": _ = s.auth.UpdateUser(r.Context(), id, "", "", "", ptrBool(true)) case "enable", "activate": _ = s.auth.UpdateUser(r.Context(), id, "", "", "", ptrBool(false)) } } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (s *Server) adminUserMedia(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"media": []any{}, "items": []any{}}) } func (s *Server) adminMedia(w http.ResponseWriter, r *http.Request) { search := strings.TrimSpace(r.URL.Query().Get("search")) pattern := "%" + search + "%" rows, err := s.db.Query(r.Context(), `SELECT id, media_key, COALESCE(media_type,'unknown'), COALESCE(title,''), COALESCE(original_filename,''), active, COALESCE(source,'Filesystem'), COALESCE(size_bytes,0), COALESCE(modified_at, created_at) FROM media WHERE ($1='' OR media_key ILIKE $2 OR COALESCE(title,'') ILIKE $2 OR COALESCE(original_filename,'') ILIKE $2) ORDER BY modified_at DESC LIMIT 100`, search, pattern) if err != nil { writeError(w, http.StatusInternalServerError, "media unavailable") return } defer rows.Close() items := make([]map[string]any, 0) for rows.Next() { var id int64 var key, mediaType, title, name, source string var active bool var size int64 var modified time.Time if rows.Scan(&id, &key, &mediaType, &title, &name, &active, &source, &size, &modified) == nil { items = append(items, map[string]any{"id": id, "mediaKey": key, "media_key": key, "mediaType": mediaType, "title": title, "filename": name, "active": active, "source": source, "sizeBytes": size, "modifiedAt": modified}) } } writeJSON(w, http.StatusOK, map[string]any{"media": items, "items": items, "total": len(items)}) } func (s *Server) adminMediaActions(w http.ResponseWriter, r *http.Request) { var input struct { Action string `json:"action"` IDs []json.RawMessage `json:"ids"` } if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } for _, raw := range input.IDs { var id int64 if json.Unmarshal(raw, &id) != nil { var text string _ = json.Unmarshal(raw, &text) id, _ = strconv.ParseInt(text, 10, 64) } if id == 0 { continue } switch strings.ToLower(input.Action) { case "delete": _, _ = s.db.Exec(r.Context(), `DELETE FROM media WHERE id=$1`, id) case "hide", "deactivate": _, _ = s.db.Exec(r.Context(), `UPDATE media SET active=FALSE WHERE id=$1`, id) case "show", "activate": _, _ = s.db.Exec(r.Context(), `UPDATE media SET active=TRUE WHERE id=$1`, id) } } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (s *Server) adminMediaLikers(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"users": []any{}, "likers": []any{}}) } func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) { var users, media, likes, views int64 _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM users`).Scan(&users) _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media`).Scan(&media) _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE stat_type='like'`).Scan(&likes) _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE stat_type='view'`).Scan(&views) writeJSON(w, http.StatusOK, map[string]any{"users": users, "media": media, "likes": likes, "views": views}) } func (s *Server) mountCarrierNodeRoutes(r chi.Router) { r.Get("/stats", s.carrierNodeStats) r.Get("/mounts", s.carrierNodeMounts) r.Get("/files/recent", s.carrierNodeRecentFiles) r.Get("/files", s.carrierNodeFiles) r.Get("/files/count", s.carrierNodeFileCount) r.Get("/folders", s.carrierNodeFolders) r.Get("/browse", s.carrierNodeBrowse) r.Get("/watch", s.carrierNodeWatch) r.With(s.internalServiceAuth).Get("/downloads", s.carrierNodeDownloads) r.With(s.internalServiceAuth).Post("/reload-mounts", s.carrierNodeReloadMounts) r.With(s.internalServiceAuth).Get("/probe", s.carrierNodeProbeFile) protected := r.With(s.auth.Optional, s.requireAdminOrInternal) protected.Post("/upload", s.carrierNodeUpload) protected.Post("/upload-mounted", s.carrierNodeUpload) protected.Delete("/downloads/{filename}", s.carrierNodeDeleteDownload) protected.Post("/store", s.carrierNodeStore) internal := r.With(s.internalServiceAuth) internal.Post("/thumbnails/{id}", s.carrierNodeThumbnailUpload) internal.Delete("/thumbnails/{id}", s.carrierNodeThumbnailDelete) internal.Post("/outputs/{name}", s.carrierNodeOutputUpload) internal.Post("/inputs/{name}", s.carrierNodeInputUpload) internal.Post("/copies/{name}", s.carrierNodeCopyUpload) // Generic, project-agnostic mount access: any project registered in // ProjectConfigurator's Projects workspace with a mount path configured under // {type} can read/list/write/delete files there, not just the handful of // hardcoded media-family routes above (/media, /mount/generated, /thumbnails, ...). // See carrierNodeMountRoots's doc comment for why no cross-service call is needed. internal.Get("/mount/{project}/{type}", s.carrierNodeListMount) internal.Get("/mount/{project}/{type}/*", s.carrierNodeMountFile) internal.Post("/mount/{project}/{type}/*", s.carrierNodeMountUpload) internal.Delete("/mount/{project}/{type}/*", s.carrierNodeMountDelete) } // carrierNodeMountRoots resolves every root path registered for {project, type} through // ProjectConfigurator's Projects workspace (the same configured_mounts setting // /api/mounts/resolve serves) - not limited to the media-family's own hardcoded mount // categories (media/output/generated/...), any project name and any mount type an // operator has configured there works. No HTTP call to ProjectConfigurator is needed: every // MEDIA_SERVICE instance, CarrierNode included, reads the same settings table directly (see // mountMappings), the same way effectiveMediaRoots already resolves CarrierNode's own roots. func (s *Server) carrierNodeMountRoots(ctx context.Context, project, mountType string) []string { mappings := s.mountMappings(ctx) projectValue, ok := mappings[project] if !ok { for key, value := range mappings { if strings.EqualFold(key, project) { projectValue, ok = value, true break } } } if !ok { return nil } functions, ok := projectValue.(map[string]any) if !ok { return nil } value, ok := functions[mountType] if !ok { for key, candidate := range functions { if strings.EqualFold(key, mountType) { value, ok = candidate, true break } } } if !ok { return nil } return normalizeMappingPaths(value) } // carrierNodeListMount lists the files directly under every root configured for // {project, type} (non-recursive - each root is typically a flat upload/output directory). func (s *Server) carrierNodeListMount(w http.ResponseWriter, r *http.Request) { project := chi.URLParam(r, "project") mountType := chi.URLParam(r, "type") roots := s.carrierNodeMountRoots(r.Context(), project, mountType) if len(roots) == 0 { writeError(w, http.StatusNotFound, "no mount configured for this project/type") return } entries := make([]map[string]any, 0) for _, root := range roots { items, err := os.ReadDir(root) if err != nil { continue } for _, item := range items { if item.IsDir() { continue } info, err := item.Info() if err != nil { continue } entries = append(entries, map[string]any{"name": item.Name(), "size": info.Size(), "modifiedAt": info.ModTime()}) } } writeJSON(w, http.StatusOK, map[string]any{"success": true, "project": project, "type": mountType, "files": entries}) } // carrierNodeMountFile downloads one file by relative path from {project, type}'s mount. func (s *Server) carrierNodeMountFile(w http.ResponseWriter, r *http.Request) { roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) if len(roots) == 0 { writeError(w, http.StatusNotFound, "no mount configured for this project/type") return } full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots) if err != nil { writeError(w, http.StatusNotFound, "file not found") return } s.serveFile(w, r, full) } // carrierNodeMountUpload stores the request body as a file under {project, type}'s first // configured root. Like carrierNodeStreamUpload (which this delegates to), the destination // filename is flattened to its base name - no subdirectories. func (s *Server) carrierNodeMountUpload(w http.ResponseWriter, r *http.Request) { roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) if len(roots) == 0 { writeError(w, http.StatusNotFound, "no mount configured for this project/type") return } s.carrierNodeStreamUpload(w, r, roots[0], chi.URLParam(r, "*")) } // carrierNodeMountDelete removes one file by relative path from {project, type}'s mount. func (s *Server) carrierNodeMountDelete(w http.ResponseWriter, r *http.Request) { roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type")) if len(roots) == 0 { writeError(w, http.StatusNotFound, "no mount configured for this project/type") return } full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots) if err != nil { writeError(w, http.StatusNotFound, "file not found") return } if err := os.Remove(full); err != nil { writeError(w, http.StatusInternalServerError, "file could not be removed") return } writeJSON(w, http.StatusOK, map[string]any{"success": true}) } func (s *Server) carrierNodeStats(w http.ResponseWriter, r *http.Request) { files := s.walkFiles(r.Context(), "") roots := s.effectiveMediaRoots(r.Context()) byType := map[string]int{"image": 0, "video": 0, "audio": 0, "other": 0} for _, file := range files { byType[fileType(file.Rel)]++ } stats := map[string]any{"count": len(files), "total": len(files), "active": len(roots), "files": byType} writeJSON(w, http.StatusOK, map[string]any{"ok": true, "stats": stats, "bandwidth": map[string]any{"bytesOut": 0, "requests": 0}, "count": len(files), "total": len(files), "active": len(roots), "files": byType, "roots": roots}) } func (s *Server) carrierNodeMounts(w http.ResponseWriter, r *http.Request) { roots := s.effectiveMediaRoots(r.Context()) writeJSON(w, http.StatusOK, map[string]any{"mappings": s.mountMappings(r.Context()), "roots": roots, "count": len(roots)}) } type fileEntry struct { Rel string `json:"rel"` Path string `json:"path"` Type string `json:"type"` Size int64 `json:"size"` Mtime int64 `json:"mtime"` } func (s *Server) carrierNodeRecentFiles(w http.ResponseWriter, r *http.Request) { s.writeCarrierNodeFiles(w, r, true) } func (s *Server) carrierNodeFiles(w http.ResponseWriter, r *http.Request) { s.writeCarrierNodeFiles(w, r, false) } func (s *Server) carrierNodeFileCount(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"ok": true, "count": len(s.walkFiles(r.Context(), r.URL.Query().Get("path")))}) } func (s *Server) writeCarrierNodeFiles(w http.ResponseWriter, r *http.Request, recent bool) { files := s.walkFiles(r.Context(), r.URL.Query().Get("path")) if recent { sort.Slice(files, func(i, j int) bool { return files[i].Mtime > files[j].Mtime }) } // Internal callers (e.g. MediaAnalyzer discovery) need to list an entire real-sized library // in one pass; the public 1000-item cap stays in place for anyone without the shared secret. maxLimit := 1000 if s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret { maxLimit = 1000000 } limit := optionalInt(r.URL.Query().Get("limit"), 100, 1, maxLimit) if len(files) > limit { files = files[:limit] } writeJSON(w, http.StatusOK, map[string]any{"files": files, "items": files, "total": len(files)}) } func (s *Server) carrierNodeFolders(w http.ResponseWriter, r *http.Request) { seen := map[string]bool{} for _, file := range s.walkFiles(r.Context(), r.URL.Query().Get("path")) { seen[filepath.Dir(file.Rel)] = true } folders := make([]string, 0, len(seen)) for folder := range seen { folders = append(folders, folder) } sort.Strings(folders) writeJSON(w, http.StatusOK, map[string]any{"folders": folders}) } func (s *Server) carrierNodeBrowse(w http.ResponseWriter, r *http.Request) { s.carrierNodeFiles(w, r) } func (s *Server) carrierNodeWatch(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") _, _ = io.WriteString(w, "event: ready\ndata: {\"ok\":true}\n\n") if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } <-r.Context().Done() } func (s *Server) carrierNodeReloadMounts(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } func (s *Server) carrierNodeDownloads(w http.ResponseWriter, r *http.Request) { limit := optionalInt(r.URL.Query().Get("limit"), 500, 1, 1000) rows, err := s.db.Query(r.Context(), `SELECT file_name, file_path, media_type, source_url, file_size_bytes, created_at FROM downloaded_media WHERE file_name IS NOT NULL ORDER BY created_at DESC LIMIT $1`, limit) if err != nil { writeError(w, http.StatusInternalServerError, "downloads unavailable") return } defer rows.Close() files := make([]map[string]any, 0) for rows.Next() { var name, path, mediaType, sourceURL string var size int64 var created time.Time if rows.Scan(&name, &path, &mediaType, &sourceURL, &size, &created) != nil { continue } files = append(files, map[string]any{"name": name, "path": path, "type": mediaType, "sourceUrl": sourceURL, "size": size, "mtime": created}) } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "files": files}) } // walkRootTimeout bounds how long a single root's filesystem walk can run before walkFiles gives // up on it. effectiveMediaRoots now includes every media-library path configured in // ProjectConfigurator's Projects workspace across every project, not just the operator's own // verified MEDIA_ROOTS - a // typo'd path or a mount that isn't actually reachable from this container (an unresponsive // network share, say) would otherwise be able to hang every caller of walkFiles (discovery, // /api/stats, browsing) indefinitely, since a blocked stat/readdir syscall can't be interrupted by // checking ctx.Err() alone. The walk itself still runs to completion in its own goroutine if it's // genuinely just slow (a huge directory tree) - only the caller stops waiting on it. const walkRootTimeout = 15 * time.Second func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry { result := make([]fileEntry, 0) for _, root := range s.effectiveMediaRoots(ctx) { root := root base := root if relative != "" && safeRelative(relative) { base = filepath.Join(root, filepath.FromSlash(relative)) } done := make(chan []fileEntry, 1) go func() { found := make([]fileEntry, 0) _ = filepath.WalkDir(base, func(full string, entry os.DirEntry, err error) error { if err != nil || entry == nil || entry.IsDir() || ctx.Err() != nil { return nil } info, err := entry.Info() if err != nil { return nil } rel, err := filepath.Rel(root, full) if err != nil || !safeRelative(filepath.ToSlash(rel)) { return nil } found = append(found, fileEntry{Rel: filepath.ToSlash(rel), Path: filepath.ToSlash(rel), Type: fileType(rel), Size: info.Size(), Mtime: info.ModTime().UnixMilli()}) return nil }) done <- found }() select { case found := <-done: result = append(result, found...) case <-time.After(walkRootTimeout): log.Printf("carriernode: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout) case <-ctx.Done(): return result } } return result } func (s *Server) carrierNodeUpload(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") { s.carrierNodeRawUpload(w, r) return } if s.cfg.MaxUploadBytes > 0 { r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) } if err := r.ParseMultipartForm(8 << 20); err != nil { writeError(w, http.StatusBadRequest, "invalid upload") return } file, header, err := r.FormFile("file") if err != nil { writeError(w, http.StatusBadRequest, "file is required") return } defer file.Close() name := filepath.Base(header.Filename) if name == "." || name == "" || !safeRelative(name) { writeError(w, http.StatusBadRequest, "invalid filename") return } if err := os.MkdirAll(s.cfg.DownloadsRoot, 0o750); err != nil { writeError(w, http.StatusInternalServerError, "upload directory unavailable") return } target := filepath.Join(s.cfg.DownloadsRoot, name) out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) if err != nil { writeError(w, http.StatusInternalServerError, "upload could not be stored") return } defer out.Close() if _, err := io.Copy(out, file); err != nil { writeError(w, http.StatusInternalServerError, "upload could not be stored") return } writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "filename": name, "path": name}) } func (s *Server) carrierNodeDeleteDownload(w http.ResponseWriter, r *http.Request) { name := chi.URLParam(r, "filename") if !safeRelative(name) { writeError(w, http.StatusBadRequest, "invalid filename") return } full, err := s.resolveUnderRoots(name, []string{s.cfg.DownloadsRoot}) if err != nil { writeError(w, http.StatusNotFound, "file not found") return } if err := os.Remove(full); err != nil { writeError(w, http.StatusNotFound, "file not found") return } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } func (s *Server) carrierNodeStore(w http.ResponseWriter, r *http.Request) { var input map[string]any if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } filePath, _ := input["filePath"].(string) fullPath, err := s.resolveStoreFile(filePath) if err != nil { writeError(w, http.StatusBadRequest, "filePath must reference a file in a configured mount") return } info, err := os.Stat(fullPath) if err != nil || info.IsDir() { writeError(w, http.StatusNotFound, "file not found on disk") return } mediaKey := s.mediaKeyForPath(fullPath) mediaType := inferMediaType(fullPath) var mediaID int64 if err := s.db.QueryRow(r.Context(), `INSERT INTO media (media_key, media_type, source, file_path, original_filename, size_bytes, modified_at, active) VALUES ($1,$2,'MediaDownloader',$3,$4,$5,$6,TRUE) ON CONFLICT (media_key) DO UPDATE SET media_type=EXCLUDED.media_type, source=EXCLUDED.source, file_path=EXCLUDED.file_path, size_bytes=EXCLUDED.size_bytes, modified_at=EXCLUDED.modified_at, active=TRUE RETURNING id`, mediaKey, mediaType, mediaKey, filepath.Base(fullPath), info.Size(), info.ModTime()).Scan(&mediaID); err != nil { writeError(w, http.StatusInternalServerError, "media catalog update failed") return } sourceURL, _ := input["sourceUrl"].(string) tool, _ := input["tool"].(string) if strings.TrimSpace(tool) == "" { tool = "yt-dlp" } status, _ := input["status"].(string) if strings.TrimSpace(status) == "" { status = "completed" } _, _ = s.db.Exec(r.Context(), `INSERT INTO downloaded_media (media_id, source_url, tool, status, file_path, file_name, file_size_bytes, media_type) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, mediaID, sourceURL, tool, status, fullPath, filepath.Base(fullPath), info.Size(), mediaType) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaKey": mediaKey, "mediaId": mediaID}) } // resolveStoreFile is CarrierNode's own local-filesystem lookup for /api/store, which catalogs a // file MediaTools already pushed into one of CarrierNode's mounts (InputRoot, MediaRoots, // DownloadsRoot, OutputRoot) - unlike everything else in this file, it's called with a path that // isn't necessarily under MediaRoots, so it can't just use resolveMediaPath. func (s *Server) resolveStoreFile(value string) (string, error) { value = strings.TrimSpace(value) if value == "" || strings.ContainsRune(value, 0) { return "", os.ErrNotExist } roots := append([]string{s.cfg.InputRoot}, s.cfg.MediaRoots...) roots = append(roots, s.cfg.DownloadsRoot, s.cfg.OutputRoot) for _, root := range roots { rootAbs, err := filepath.Abs(root) if err != nil { continue } candidate := filepath.FromSlash(value) if !filepath.IsAbs(candidate) { candidate = filepath.Join(rootAbs, candidate) } candidate, err = filepath.Abs(candidate) if err != nil || !withinRoot(rootAbs, candidate) { continue } info, err := os.Stat(candidate) if err != nil || info.IsDir() { continue } if !sameRealRoot(rootAbs, candidate) { continue } return candidate, nil } return "", os.ErrNotExist } func (s *Server) carrierNodeRawUpload(w http.ResponseWriter, r *http.Request) { name := filepath.Base(strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("filename"), r.URL.Query().Get("file_name")))) if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) { writeError(w, http.StatusBadRequest, "valid filename query parameter is required") return } targetRoot := s.cfg.DownloadsRoot if strings.Contains(r.URL.Path, "upload-mounted") && len(s.cfg.MediaRoots) > 0 { targetRoot = s.cfg.MediaRoots[0] } if err := os.MkdirAll(targetRoot, 0o750); err != nil { writeError(w, http.StatusInternalServerError, "upload directory unavailable") return } target := filepath.Join(targetRoot, name) if !withinRoot(targetRoot, target) { writeError(w, http.StatusBadRequest, "invalid upload path") return } if s.cfg.MaxUploadBytes > 0 { r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) } out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) if err != nil { writeError(w, http.StatusInternalServerError, "upload could not be stored") return } _, copyErr := io.Copy(out, r.Body) closeErr := out.Close() if copyErr != nil || closeErr != nil { _ = os.Remove(target) writeError(w, http.StatusRequestEntityTooLarge, "upload could not be stored") return } info, _ := os.Stat(target) if info != nil && supportedMediaPath(target) { s.indexMediaFile(r.Context(), s.mediaKeyForPath(target), info.Size(), info.ModTime(), "upload-"+time.Now().UTC().Format("20060102T150405.000000000Z")) } writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "fileName": name, "filename": name, "path": name, "size": infoSize(info)}) } func (s *Server) mediaKeyForPath(fullPath string) string { for _, root := range append(append([]string{}, s.cfg.MediaRoots...), s.cfg.DownloadsRoot, s.cfg.OutputRoot) { rootAbs, err := filepath.Abs(root) if err == nil { if relative, relErr := filepath.Rel(rootAbs, fullPath); relErr == nil && safeRelative(filepath.ToSlash(relative)) { return filepath.ToSlash(relative) } } } return filepath.Base(fullPath) } func infoSize(info os.FileInfo) int64 { if info == nil { return 0 } return info.Size() } func (s *Server) carrierNodeMedia(w http.ResponseWriter, r *http.Request) { relative := chi.URLParam(r, "*") if relative == "" { relative = strings.TrimPrefix(r.URL.Path, "/media/") } full, err := s.resolveAnyMediaPath(r.Context(), relative) if err != nil { writeError(w, http.StatusNotFound, "file not found") return } s.serveFile(w, r, full) } func (s *Server) carrierNodeDownloadMedia(w http.ResponseWriter, r *http.Request) { relative := strings.TrimPrefix(r.URL.Path, "/media/downloads/") full, err := s.resolveUnderRoots(relative, []string{s.cfg.DownloadsRoot}) if err != nil { writeError(w, http.StatusNotFound, "download not found") return } s.serveFile(w, r, full) } func (s *Server) carrierNodeGeneratedMedia(w http.ResponseWriter, r *http.Request) { relative := strings.TrimPrefix(r.URL.Path, "/mount/generated/") full, err := s.resolveUnderRoots(relative, []string{s.cfg.OutputRoot}) if err != nil { writeError(w, http.StatusNotFound, "generated media not found") return } s.serveFile(w, r, full) } func (s *Server) carrierNodeThumbnail(w http.ResponseWriter, r *http.Request) { relative := chi.URLParam(r, "*") if relative == "" { relative = strings.TrimPrefix(r.URL.Path, "/thumbnails/") } full, err := s.resolveThumbnailPath(relative) if err != nil { writeError(w, http.StatusNotFound, "thumbnail not found") return } s.serveFile(w, r, full) } func (s *Server) carrierNodeInputMedia(w http.ResponseWriter, r *http.Request) { relative := strings.TrimPrefix(r.URL.Path, "/mount/inputs/") full, err := s.resolveUnderRoots(relative, []string{s.cfg.InputRoot}) if err != nil { writeError(w, http.StatusNotFound, "input file not found") return } s.serveFile(w, r, full) } func (s *Server) carrierNodeCopyMedia(w http.ResponseWriter, r *http.Request) { relative := strings.TrimPrefix(r.URL.Path, "/mount/copies/") full, err := s.resolveUnderRoots(relative, []string{s.cfg.CopyRoot}) if err != nil { writeError(w, http.StatusNotFound, "copy file not found") return } s.serveFile(w, r, full) } // carrierNodeStreamUpload writes a raw request body into root/name, used by every internal // push-result endpoint (thumbnails, outputs, inputs, copies). name is always reduced to its // base component - callers never need nested directories, and this keeps every write flat and // trivially contained within root (mirrors carrierNodeRawUpload's existing filename handling). func (s *Server) carrierNodeStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) { name = filepath.Base(strings.TrimSpace(name)) if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) { writeError(w, http.StatusBadRequest, "invalid filename") return } if err := os.MkdirAll(root, 0o750); err != nil { writeError(w, http.StatusInternalServerError, "storage directory unavailable") return } target := filepath.Join(root, name) if !withinRoot(root, target) { writeError(w, http.StatusBadRequest, "invalid filename") return } if s.cfg.MaxUploadBytes > 0 { r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes) } out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640) if err != nil { writeError(w, http.StatusInternalServerError, "file could not be stored") return } written, copyErr := io.Copy(out, r.Body) closeErr := out.Close() if copyErr != nil || closeErr != nil { _ = os.Remove(target) writeError(w, http.StatusRequestEntityTooLarge, "file could not be stored") return } writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "name": name, "size": written}) } func (s *Server) carrierNodeThumbnailUpload(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if !safeRelative(id) || strings.ContainsAny(id, `/\`) { writeError(w, http.StatusBadRequest, "invalid thumbnail id") return } s.carrierNodeStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg") } func (s *Server) carrierNodeThumbnailDelete(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") if !safeRelative(id) || strings.ContainsAny(id, `/\`) { writeError(w, http.StatusBadRequest, "invalid thumbnail id") return } if full, err := s.resolveThumbnailPath(id + ".jpg"); err == nil { _ = os.Remove(full) } writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) } func (s *Server) carrierNodeOutputUpload(w http.ResponseWriter, r *http.Request) { s.carrierNodeStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name")) } func (s *Server) carrierNodeInputUpload(w http.ResponseWriter, r *http.Request) { s.carrierNodeStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name")) } func (s *Server) carrierNodeCopyUpload(w http.ResponseWriter, r *http.Request) { s.carrierNodeStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name")) } func (s *Server) carrierNodeProbeFile(w http.ResponseWriter, r *http.Request) { full, err := s.resolveAnyMediaPath(r.Context(), r.URL.Query().Get("path")) if err != nil { writeError(w, http.StatusNotFound, "file not found") return } result, err := s.probeWithFFprobe(r.Context(), full) if err != nil { writeError(w, http.StatusUnprocessableEntity, "probe failed") return } writeJSON(w, http.StatusOK, result) } func (s *Server) mountKioskRoutes(r chi.Router) { r.Get("/kiosk/status", s.kioskStatus) r.Get("/config", s.kioskConfig) r.HandleFunc("/images/*", s.kioskImage) } func (s *Server) kioskConfig(w http.ResponseWriter, r *http.Request) { intSetting := func(key string, fallback int64) int64 { value := s.settingValue(r.Context(), key, "") if parsed, err := strconv.ParseInt(value, 10, 64); err == nil { return parsed } return fallback } writeJSON(w, http.StatusOK, map[string]any{ "defaultDisplayDuration": intSetting("default_display_duration", 5000), "defaultProgressVisibility": s.settingValue(r.Context(), "kiosk_progress_visibility", "hover"), "defaultQueueVisibility": s.settingValue(r.Context(), "kiosk_queue_visibility", "hover"), "defaultDurationVisibility": s.settingValue(r.Context(), "kiosk_duration_visibility", "hover"), "defaultIconVisibility": s.settingValue(r.Context(), "kiosk_icon_visibility", "hover"), "defaultStatsPosition": s.settingValue(r.Context(), "kiosk_stats_position", "bottom-left"), "defaultQueueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"), "defaultPreloadCount": intSetting("default_preload_count", 1), "defaultServerDisplayDuration": intSetting("server_display_duration", 5000), "currentQueueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"), "currentServerDisplayDuration": intSetting("server_display_duration", 5000), }) } func (s *Server) kioskStatus(w http.ResponseWriter, r *http.Request) { s.kioskMu.Lock() latest := s.kioskLatest s.kioskMu.Unlock() writeJSON(w, http.StatusOK, map[string]any{"ok": true, "latestImage": latest, "queueLength": 0}) } func (s *Server) mountKioskSocket(r chi.Router) { r.Get("/ws", s.kioskWebsocket) } func (s *Server) fileType(value string) string { return fileType(value) } func fileType(value string) string { switch strings.ToLower(filepath.Ext(value)) { case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".svg": return "image" case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac": return "audio" case ".mp4", ".mkv", ".mov", ".avi", ".webm", ".wmv": return "video" default: return "other" } } // trailingInstanceSuffix strips a "_2", "_3", ... instance suffix, mirroring // ConfigWorkspace.svelte's getBaseProject - the same "AuthGuard" / "AuthGuard_2" / "AuthGuard_3" // naming convention every multi-instance central/main service in the Projects workspace uses. var trailingInstanceSuffix = regexp.MustCompile(`_\d+$`) func instanceBaseKey(key string) string { return trailingInstanceSuffix.ReplaceAllString(key, "") } func sensitiveSetting(key string) bool { switch strings.ToLower(key) { case "session_secret", "internal_service_secret", "smtp_pass": return true default: return false } } func normalizeServiceURL(value string) (string, error) { parsed, err := url.Parse(strings.TrimSpace(value)) if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Hostname() == "" { return "", errors.New("a valid http(s) URL is required") } if parsed.User != nil { return "", errors.New("URL credentials are not allowed") } parsed.Path = strings.TrimRight(parsed.Path, "/") return parsed.String(), nil } func normalizeMappingPaths(value any) []string { result := []string{} switch raw := value.(type) { case string: if raw != "" { result = append(result, raw) } case []any: for _, item := range raw { if text, ok := item.(string); ok && text != "" { result = append(result, text) } } case []string: result = append(result, raw...) } return result } func ptrBool(value bool) *bool { return &value }