Files
CollabTable/shared/media-backend/internal/server/server.go
T
Gabriel20xx fd32419371
Docker / Docker Build & Push (push) Successful in 3m34s
Sync shared snapshot from 43d77dd
2026-09-01 08:44:09 +02:00

434 lines
14 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/auth"
"mediacollection/internal/config"
)
type Server struct {
cfg *config.Config
db *pgxpool.Pool
auth *auth.Service
startedAt time.Time
mediaMu sync.RWMutex
media map[string]MediaRecord
jobsMu sync.RWMutex
jobs map[string]*WorkflowJob
workflowSem chan struct{}
sync *syncHub
thumbnailMu sync.Mutex
thumbnail thumbnailGenerationState
thumbnailCancel context.CancelFunc
clearMu sync.Mutex
clear databaseClearState
scanMu sync.Mutex
scan scanState
scanCancel context.CancelFunc
analysisMu sync.Mutex
analysis analysisState
analysisCancel context.CancelFunc
kioskMu sync.Mutex
kioskClients map[chan []byte]struct{}
kioskLatest string
kioskPolling bool
}
type MediaRecord struct {
ID int64
MediaKey string
MediaType string
Title *string
Description *string
FilePath string
OriginalName string
Source string
Width *int
Height *int
DurationMs *int64
SizeBytes *int64
IsVR bool
HasFunscript bool
Speed *float32
ModifiedAt time.Time
}
type WorkflowJob struct {
ID string `json:"id"`
Service string `json:"service"`
Tool string `json:"tool"`
Status string `json:"status"`
Progress int `json:"progress"`
Request map[string]any `json:"request,omitempty"`
Result map[string]any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"createdAt"`
StartedAt *time.Time `json:"startedAt,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
}
type thumbnailGenerationState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the
// same live status endpoint as the analyzer workers. The reset itself is deliberately kept
// synchronous from the HTTP caller's perspective, but large libraries still need an honest state
// while their thumbnail files and database rows are being removed.
type databaseClearState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show
// which media type is actively being indexed right now - scanMediaFiles has no separate queue,
// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as
// it's found, so "active" here is the closest honest signal to a live "processing" state.
type scanState struct {
Running bool
Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep)
CurrentType string
CurrentFile string
FilesIndexed int64
// Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before
// looping. discover has no total (a live filesystem walk doesn't know its own size in advance)
// and leaves this at zero, which the UI treats as "not available".
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. MediaServant unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
func New(cfg *config.Config, db *pgxpool.Pool) *Server {
return &Server{
cfg: cfg,
db: db,
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
startedAt: time.Now(),
media: make(map[string]MediaRecord),
jobs: make(map[string]*WorkflowJob),
workflowSem: make(chan struct{}, 2),
sync: newSyncHub(),
thumbnail: thumbnailGenerationState{State: "idle"},
analysis: analysisState{State: "idle"},
kioskClients: make(map[chan []byte]struct{}),
}
}
func (s *Server) Handler() http.Handler {
router := chi.NewRouter()
router.Use(chimiddleware.RequestID)
router.Use(chimiddleware.Recoverer)
router.Use(s.securityHeadersMiddleware)
router.Use(s.cors)
router.Get("/healthz", s.health)
router.Get("/health", s.health)
router.Get("/ready", s.ready)
router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack)
router.Get("/__cache-policy", s.cachePolicy)
router.Route("/auth", func(r chi.Router) {
r.Post("/signup", s.auth.Signup)
r.Post("/login", s.auth.Login)
r.Post("/logout", s.auth.Logout)
r.Post("/reset/request", s.auth.RequestAdminReset)
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
r.Get("/me", s.auth.Me)
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
r.Get("/status", s.auth.Status)
r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded)
})
router.Route("/api/auth", func(r chi.Router) {
manager := r.With(s.auth.RequireUserManager)
manager.Get("/access", s.auth.AccessSettings)
manager.Put("/access", s.auth.UpdateAccessSettings)
manager.Get("/users", s.auth.ManagedUsers)
manager.Post("/users", s.auth.ManagedCreateUser)
manager.Put("/users/{id}", s.auth.ManagedUpdateUser)
manager.Patch("/users/{id}", s.auth.ManagedUpdateUser)
manager.Delete("/users/{id}", s.auth.ManagedDeleteUser)
})
router.Route("/api", func(r chi.Router) {
s.mountServiceRoutes(r)
})
if s.cfg.Service == config.Kiosk {
s.mountKioskSocket(router)
}
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.Servant {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
}
router.NotFound(s.staticHandler)
return router
}
func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountSharedRoutes(r)
switch s.cfg.Service {
case config.Viewer:
s.mountViewerRoutes(r)
case config.Tools:
s.mountToolsRoutes(r)
case config.Analyzer:
s.mountAnalyzerRoutes(r)
case config.ConfigService:
s.mountConfigRoutes(r)
case config.Moderator:
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.Desktop:
s.mountDesktopRoutes(r)
}
}
func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:")
next.ServeHTTP(w, r)
})
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())})
}
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
if s.db == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.db.Ping(ctx); err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName})
}
func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) {
appVersion := os.Getenv("APP_VERSION")
if appVersion == "" {
appVersion = "go-rewrite"
}
writeJSON(w, http.StatusOK, map[string]any{
"appVersion": appVersion,
"stack": []map[string]string{
{"label": "Runtime", "value": runtime.Version()},
{"label": "HTTP", "value": "net/http + chi"},
{"label": "Database", "value": "PostgreSQL + pgx"},
{"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"},
},
})
}
func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}})
}
func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) {
root := os.DirFS(s.cfg.WebRoot)
if _, err := fs.Stat(root, "."); err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"})
return
}
requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
if requested == "." || requested == "" {
requested = "index.html"
}
if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() {
http.FileServer(http.FS(root)).ServeHTTP(w, r)
return
}
if path.Ext(requested) != "" {
http.NotFound(w, r)
return
}
index, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(index)
}
func (s *Server) listenAndServe(ctx context.Context) error {
server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port)
if s.cfg.TLSCertFile != "" {
return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile)
}
return server.ListenAndServe()
}
func (s *Server) Run(ctx context.Context) error {
go s.resumeWorkflowJobs(ctx)
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
return s.listenAndServe(ctx)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func intValue(value *int) any {
if value == nil {
return nil
}
return *value
}
func int64Value(value *int64) any {
if value == nil {
return nil
}
return *value
}
func floatValue(value *float32) any {
if value == nil {
return nil
}
return *value
}
func boolQuery(value string) *bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "1", "true", "yes", "on":
result := true
return &result
case "0", "false", "no", "off":
result := false
return &result
default:
return nil
}
}
func (s *Server) internalServiceAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required")
})
}
func optionalInt(value string, fallback, minimum, maximum int) int {
var parsed int
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil {
return fallback
}
if parsed < minimum {
return minimum
}
if parsed > maximum {
return maximum
}
return parsed
}