Files
shared/media-backend/internal/config/config.go
T
Gabriel20xxandClaude Sonnet 5 38a349eb52 Fix media-backend/media-webui: re-copy from post-revert MediaCollection
The original MediaEngine extraction (later folded into this repo) had
been done BEFORE the owner's decision to revert the MediaViewer/Forge/
etc. rename, and was never re-extracted afterward like the other 7
service repos were - it silently carried stale renamed-era text
(e.g. 'Porter' instead of 'MediaServant') into Go doc comments, WebUI
prose, project-icons.json, and app-config.ts. Re-copied both directories
fresh from the current (correctly reverted) MediaCollection/backend and
MediaCollection/WebUI, then re-applied the go.mod replace-directive fix
and re-added SECURITY_AUDIT.md (also newly migrated from MediaCollection
root - a real deployment security checklist that would otherwise have
been lost when MediaCollection is deleted).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-31 22:19:58 +02:00

238 lines
6.5 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type Service string
const (
Viewer Service = "viewer"
Tools Service = "tools"
Analyzer Service = "analyzer"
ConfigService Service = "config"
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
Desktop Service = "desktop"
)
type Config struct {
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
InternalServiceSecret string
FFmpeg string
FFprobe string
YTDLP string
ComfyURL string
AnalyzerModelsURL string
ServantURL string
MaxUploadBytes int64
TLSCertFile string
TLSKeyFile string
}
func Load() (*Config, error) {
service := normalizeService(os.Getenv("MEDIA_SERVICE"))
if service == "" {
service = normalizeService(os.Getenv("SERVICE"))
}
if service == "" {
service = Viewer
}
name := serviceName(service)
port := envOr("PORT", defaultPort(service))
root := envOr("MEDIA_ROOT", envOr("MEDIA_PATH", "./media"))
roots := splitPaths(os.Getenv("MEDIA_ROOTS"))
if len(roots) == 0 {
roots = []string{root}
}
for i := range roots {
roots[i] = filepath.Clean(roots[i])
}
maxUpload, err := parseBytes(envOr("MAX_UPLOAD_BYTES", "53687091200"))
if err != nil {
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
}
cfg := &Config{
Port: port,
DatabaseURL: strings.TrimSpace(os.Getenv("DATABASE_URL")),
Service: service,
ServiceName: name,
WebRoot: resolveWebRoot(service),
MediaRoots: roots,
InputRoot: filepath.Clean(envOr("INPUT_DIR", "./input")),
CopyRoot: filepath.Clean(envOr("UPLOAD_COPY_DIR", "./copy")),
WorkflowsRoot: filepath.Clean(envOr("WORKFLOWS_DIR", filepath.Join("..", "MediaTools", "public", "workflows"))),
ThumbnailRoot: filepath.Clean(envOr("THUMBNAIL_DIR", "./thumbnails")),
OutputRoot: filepath.Clean(envOr("OUTPUT_DIR", "./output")),
DownloadsRoot: filepath.Clean(envOr("DOWNLOADS_DIR", "./downloads")),
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"),
FFprobe: envOr("FFPROBE_PATH", "ffprobe"),
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
ServantURL: strings.TrimRight(envOr("SERVANT_URL", "http://127.0.0.1:3003"), "/"),
MaxUploadBytes: maxUpload,
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
}
if cfg.DatabaseURL == "" {
return nil, fmt.Errorf("DATABASE_URL is required")
}
if (cfg.TLSCertFile == "") != (cfg.TLSKeyFile == "") {
return nil, fmt.Errorf("TLS_CERT_FILE and TLS_KEY_FILE must be set together")
}
return cfg, nil
}
func normalizeService(value string) Service {
switch strings.ToLower(strings.TrimSpace(value)) {
case "viewer", "mediaviewer":
return Viewer
case "tools", "mediatools":
return Tools
case "analyzer", "mediaanalyzer":
return Analyzer
case "config", "mediaconfig":
return ConfigService
case "moderator", "mediamoderator":
return Moderator
case "kiosk", "mediakiosk":
return Kiosk
case "servant", "mediaservant":
return Servant
case "desktop", "mediadesktop":
return Desktop
default:
return ""
}
}
func serviceName(service Service) string {
switch service {
case Viewer:
return "MediaViewer"
case Tools:
return "MediaTools"
case Analyzer:
return "MediaAnalyzer"
case ConfigService:
return "MediaConfig"
case Moderator:
return "MediaModerator"
case Kiosk:
return "MediaKiosk"
case Servant:
return "MediaServant"
case Desktop:
return "MediaDesktop"
default:
return "MediaCollection"
}
}
func defaultPort(service Service) string {
switch service {
case ConfigService:
return "3005"
case Moderator:
return "8090"
case Servant:
return "3003"
default:
return "3000"
}
}
func resolveWebRoot(_ Service) string {
if value := strings.TrimSpace(os.Getenv("WEB_ROOT")); value != "" {
return filepath.Clean(value)
}
return filepath.Join("..", "WebUI", "build")
}
func splitPaths(value string) []string {
parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' })
result := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
func parseBytes(value string) (int64, error) {
value = strings.TrimSpace(strings.ToLower(value))
if value == "" {
return 0, nil
}
multiplier := int64(1)
suffixes := []struct {
suffix string
factor int64
}{
{"gb", 1 << 30},
{"mb", 1 << 20},
{"kb", 1 << 10},
{"b", 1},
}
for _, s := range suffixes {
if strings.HasSuffix(value, s.suffix) {
value = strings.TrimSpace(strings.TrimSuffix(value, s.suffix))
multiplier = s.factor
break
}
}
n, err := strconv.ParseInt(value, 10, 64)
if err != nil || n < 0 {
return 0, fmt.Errorf("must be a non-negative byte count")
}
return n * multiplier, nil
}
func envOr(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envBool(key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}