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 MediaServant'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 (MediaAnalyzer's "images"/"videos"/"audios", MediaViewer/MediaKiosk's "media", ...) // but they're all describing locations MediaServant 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. 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) 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 MediaTools 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) 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 }