Fold MediaEngine (media-backend, media-webui) into this repo

Per owner decision: MediaEngine (the Media product family's Go backend
and SvelteKit frontend, previously its own repo referenced by 7 thin
service repos via git submodule) is folded directly into shared/ as
media-backend/ and media-webui/, rather than staying separate.

media-backend/go.mod's replace directive now points at ../backend (a
true sibling within this repo) instead of a vendored ../shared/backend
copy, since there's no more nested vendoring - it's the real thing.

Also moved MediaEngine's own CI (media-backend-lint.yml,
media-backend-tests.yml) and dev tooling scripts (scripts/media/*,
audit/lint/enforce scripts for the media-backend+media-webui content),
fixing their path assumptions for the new layout, and dropped
scripts/media/sync-shared.mjs (confirmed dead code, and now doubly
obsolete since there's no more vendored shared/ subfolder for it to
check). Added media:* script aliases to package.json for the moved
tooling, namespaced to avoid colliding with this repo's own scripts.

Also fixed sync-consumers.ps1's workspace-root resolution to walk up
until it finds a directory containing both Original/ and Forks/,
instead of assuming shared/ is always a direct child of the workspace
root - it broke when shared/ moved from Web/shared to Web/Central/shared
earlier in this same restructuring. Removed the now-obsolete
Original/MediaEngine entry from its consumer list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-08-31 22:06:29 +02:00
1 parent 79d9461769
commit acde180086
99 files changed
+20488 -1

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,710 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// analysisState tracks the currently-running AI analysis pass, mirroring thumbnailGenerationState.
type analysisState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// analyzerTasksByMediaType mirrors WebUI/src/lib/features/MediaTypePipeline.svelte's stagesForType -
// the set of AI tasks that exist for each media type.
var analyzerTasksByMediaType = map[string][]string{
"image": {"tags", "title", "description", "age", "gender", "nsfw"},
"video": {"tags"},
"audio": {"tags"},
"funscript": {},
}
func (s *Server) analyzerAnalyzeStatus(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
state := s.analysis
s.analysisMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"status": map[string]any{
"running": state.Running,
"state": firstNonEmpty(state.State, "idle"),
"total": state.Total,
"completed": state.Completed,
"failed": state.Failed,
"current": state.Current,
"startedAt": state.StartedAt,
"finishedAt": state.FinishedAt,
"lastError": state.LastError,
},
})
}
func (s *Server) analyzerAnalyzeStart(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, false)
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
writeError(w, http.StatusConflict, "AI analysis is already running")
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(ctx, mediaTypesList(selected))
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"})
}
func (s *Server) analyzerAnalyzeStop(w http.ResponseWriter, r *http.Request) {
s.analysisMu.Lock()
cancel := s.analysisCancel
running := s.analysis.Running
s.analysisMu.Unlock()
if !running || cancel == nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
return
}
log.Printf("analyzer: AI analysis stop requested")
cancel()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
}
// runAiAnalysis queues any AI task that isn't already completed under the currently-configured
// model, then works through everything queued. mediaTypeFilters scopes both stages to a subset of
// media types (empty means every type) - used both by the dashboard's media-type selector and by
// the per-media-type retry-errors action (which passes a single-element list) so a scoped run
// never kicks off a full-library pass.
func (s *Server) runAiAnalysis(ctx context.Context, mediaTypeFilters []string) {
if err := s.syncAnalysisTasks(ctx, mediaTypeFilters); err != nil && ctx.Err() == nil {
log.Printf("analyzer: AI analysis: failed to sync tasks: %v", err)
s.finishAnalysis(err)
return
}
s.processAnalysisTasks(ctx, mediaTypeFilters)
}
type modelStageConfig struct {
Primary string
Enabled bool
}
// parseModelStageConfig mirrors MediaTypePipeline.svelte's own leniency: older saves stored the
// model as a bare string rather than {primary, fallback, enabled}.
func parseModelStageConfig(raw json.RawMessage) modelStageConfig {
var asString string
if json.Unmarshal(raw, &asString) == nil {
if asString == "" || asString == "disabled" {
return modelStageConfig{}
}
return modelStageConfig{Primary: asString, Enabled: true}
}
var asObject struct {
Primary string `json:"primary"`
Enabled bool `json:"enabled"`
}
if json.Unmarshal(raw, &asObject) == nil {
return modelStageConfig{Primary: asObject.Primary, Enabled: asObject.Enabled}
}
return modelStageConfig{}
}
// enabledAnalysisTasks reads the analyzer_model_config setting (the same one the model-config
// endpoints already read/write) and returns, per media type, the task->model pairs the user has
// actually turned on.
func (s *Server) enabledAnalysisTasks(ctx context.Context, mediaTypeFilters []string) map[string]map[string]string {
value := s.settingValue(ctx, "analyzer_model_config", "{}")
var wrapper struct {
Config map[string]map[string]json.RawMessage `json:"config"`
}
if json.Unmarshal([]byte(value), &wrapper) != nil {
return nil
}
filterSet := make(map[string]bool, len(mediaTypeFilters))
for _, mediaType := range mediaTypeFilters {
filterSet[mediaType] = true
}
result := make(map[string]map[string]string)
for mediaType, tasks := range analyzerTasksByMediaType {
if len(filterSet) > 0 && !filterSet[mediaType] {
continue
}
section, ok := wrapper.Config[mediaType]
if !ok {
continue
}
enabled := make(map[string]string)
for _, task := range tasks {
raw, ok := section[task]
if !ok {
continue
}
stage := parseModelStageConfig(raw)
if stage.Enabled && stage.Primary != "" && stage.Primary != "disabled" {
enabled[task] = stage.Primary
}
}
if len(enabled) > 0 {
result[mediaType] = enabled
}
}
return result
}
// syncAnalysisTasks upserts one media_analysis_tasks row per (active media file, enabled task).
// A file whose task previously errored, or whose configured model has since changed, is put back
// on the queue - mirroring how thumbnails/metadata already retry automatically on every run
// rather than requiring the dedicated retry-errors action.
func (s *Server) syncAnalysisTasks(ctx context.Context, mediaTypeFilters []string) error {
tasksByType := s.enabledAnalysisTasks(ctx, mediaTypeFilters)
if len(tasksByType) == 0 {
return nil
}
query := `SELECT media_key, LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)`
args = append(args, mediaTypeFilters)
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
return err
}
type mediaItem struct{ key, mediaType string }
items := make([]mediaItem, 0)
for rows.Next() {
var item mediaItem
if rows.Scan(&item.key, &item.mediaType) == nil {
items = append(items, item)
}
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, item := range items {
tasks, ok := tasksByType[item.mediaType]
if !ok {
continue
}
for task, model := range tasks {
if ctx.Err() != nil {
return nil
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_analysis_tasks (media_key, media_type, task, model, status)
VALUES ($1,$2,$3,$4,'queued')
ON CONFLICT (media_key, task) DO UPDATE SET
model = EXCLUDED.model,
status = 'queued',
error_message = NULL,
updated_at = NOW()
WHERE media_analysis_tasks.status = 'error'
OR (media_analysis_tasks.status = 'completed' AND media_analysis_tasks.model <> EXCLUDED.model)`,
item.key, item.mediaType, task, model)
}
}
return nil
}
type pendingAnalysisTask struct {
id int64
mediaKey, mediaType string
task, model, filePath string
}
func (s *Server) processAnalysisTasks(ctx context.Context, mediaTypeFilters []string) {
query := `
SELECT t.id, t.media_key, t.media_type, t.task, t.model, COALESCE(NULLIF(m.file_path, ''), m.media_key)
FROM media_analysis_tasks t
JOIN media m ON m.media_key = t.media_key
WHERE t.status = 'queued' AND m.active = TRUE`
args := []any{}
if len(mediaTypeFilters) > 0 {
query += ` AND t.media_type = ANY($1)`
args = append(args, mediaTypeFilters)
}
query += ` ORDER BY t.id ASC`
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
if ctx.Err() != nil {
s.finishAnalysis(nil)
} else {
log.Printf("analyzer: AI analysis: failed to load queued tasks: %v", err)
s.finishAnalysis(err)
}
return
}
items := make([]pendingAnalysisTask, 0)
for rows.Next() {
var item pendingAnalysisTask
if rows.Scan(&item.id, &item.mediaKey, &item.mediaType, &item.task, &item.model, &item.filePath) == nil {
items = append(items, item)
}
}
rows.Close()
log.Printf("analyzer: AI analysis started: %d tasks queued", len(items))
s.analysisMu.Lock()
s.analysis.Total = len(items)
s.analysisMu.Unlock()
for _, item := range items {
if ctx.Err() != nil {
s.finishAnalysis(nil)
return
}
s.analysisMu.Lock()
s.analysis.Current = item.filePath
s.analysis.CurrentType = item.mediaType
s.analysisMu.Unlock()
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='processing', started_at=NOW() WHERE id=$1`, item.id)
result, runErr := s.runAnalysisTask(ctx, item)
s.analysisMu.Lock()
if runErr != nil {
s.analysis.Failed++
s.analysis.LastError = runErr.Error()
} else {
s.analysis.Completed++
}
s.analysisMu.Unlock()
if runErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='error', error_message=$2, finished_at=NOW() WHERE id=$1`, item.id, runErr.Error())
continue
}
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='completed', error_message=NULL, result=$2, finished_at=NOW() WHERE id=$1`, item.id, mustJSON(result))
s.applyAnalysisResult(ctx, item.mediaKey, result)
}
s.finishAnalysis(nil)
}
func (s *Server) finishAnalysis(runErr error) {
now := time.Now().UTC()
s.analysisMu.Lock()
defer s.analysisMu.Unlock()
s.analysis.Running = false
s.analysisCancel = nil
s.analysis.Current = ""
s.analysis.CurrentType = ""
s.analysis.FinishedAt = &now
if runErr != nil {
s.analysis.State = "error"
s.analysis.LastError = runErr.Error()
} else if s.analysis.Completed+s.analysis.Failed < s.analysis.Total {
s.analysis.State = "stopped"
} else if s.analysis.Failed > 0 {
s.analysis.State = "completed_with_errors"
} else {
s.analysis.State = "completed"
s.analysis.LastError = ""
}
log.Printf("analyzer: AI analysis finished: %d/%d done, %d failed, state=%s", s.analysis.Completed, s.analysis.Total, s.analysis.Failed, s.analysis.State)
if s.analysis.LastError != "" {
log.Printf("analyzer: AI analysis last error: %s", s.analysis.LastError)
}
}
// runAnalysisTask dispatches one (file, task, model) unit of work. Every model produces a fixed
// output shape regardless of which task slot it was assigned to in the UI (the model dropdown
// isn't filtered per task), so storage in applyAnalysisResult is driven by what a model actually
// returns, not by the task key it ran under.
func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask) (map[string]any, error) {
sourcePath := filepath.ToSlash(item.filePath)
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
// than always fetching the whole video across the wire to Servant just to grab one frame.
if item.mediaType == "video" && item.model != "laplacian" {
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
if err != nil {
return nil, err
}
if cleanup != nil {
defer cleanup()
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
}
scratchPath, cleanup, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
}
defer cleanup()
if item.model == "laplacian" {
if item.mediaType != "image" {
return nil, fmt.Errorf("laplacian quality scoring only supports images")
}
variance, err := computeLaplacianVariance(scratchPath)
if err != nil {
return nil, err
}
return map[string]any{"quality": map[string]any{"laplacianVariance": variance}}, nil
}
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, scratchPath)
}
// videoAnalysisFrame reuses an already-generated thumbnail as the representative frame for
// image-shaped models when one exists, fetching the source video and extracting a temporary
// frame otherwise so AI analysis doesn't depend on the thumbnails stage being enabled. Both paths
// return a scratch file the AnalyzerModels sidecar (co-located in this container - see
// callAnalyzerModelsService) can read directly.
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
var thumbnailID string
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
if scratchPath, cleanup, fetchErr := s.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
return scratchPath, cleanup, nil
}
}
videoScratch, cleanupVideo, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
}
defer cleanupVideo()
temporary, err := os.CreateTemp("", "analysis-frame-*.jpg")
if err != nil {
return "", nil, fmt.Errorf("create temporary frame: %w", err)
}
temporaryPath := temporary.Name()
if err := temporary.Close(); err != nil {
_ = os.Remove(temporaryPath)
return "", nil, err
}
frameCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-ss", "0", "-i", videoScratch, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath}
command := exec.CommandContext(frameCtx, s.cfg.FFmpeg, args...)
var stderr bytes.Buffer
command.Stderr = &stderr
if err := command.Run(); err != nil {
_ = os.Remove(temporaryPath)
detail := strings.TrimSpace(stderr.String())
if len(detail) > 300 {
detail = detail[len(detail)-300:]
}
if detail != "" {
return "", nil, fmt.Errorf("ffmpeg: %s", detail)
}
return "", nil, err
}
return temporaryPath, func() { _ = os.Remove(temporaryPath) }, nil
}
type analysisSidecarRequest struct {
Task string `json:"task"`
Model string `json:"model"`
Path string `json:"path"`
}
// callAnalyzerModelsService calls the AnalyzerModels sidecar (a separate process in the same
// container, not baked into this binary - see ANALYZER_MODELS_URL and Lookout/Dockerfile),
// the same way executeGeneration already calls out to ComfyUI for image generation. Video frames
// are analyzed through the image endpoint since by the time this runs the video has already been
// reduced to a still frame.
func (s *Server) callAnalyzerModelsService(ctx context.Context, mediaType, task, model, path string) (map[string]any, error) {
endpoint, ok := map[string]string{"image": "/analyze/image", "video": "/analyze/image", "audio": "/analyze/audio"}[mediaType]
if !ok {
return nil, fmt.Errorf("unsupported media type for AI analysis: %s", mediaType)
}
body, err := json.Marshal(analysisSidecarRequest{Task: task, Model: model, Path: path})
if err != nil {
return nil, err
}
// Some models (florence2 especially) run several seconds per file on CPU - generous timeout
// so a slow model doesn't get mistaken for a hung one.
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, s.cfg.AnalyzerModelsURL+endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, fmt.Errorf("analyzer models service request failed: %w", err)
}
defer response.Body.Close()
var payload struct {
Result map[string]any `json:"result"`
// FastAPI's HTTPException serializes as {"detail": "..."} , not {"error": "..."}.
Detail string `json:"detail"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil {
return nil, fmt.Errorf("invalid analyzer models response: %w", err)
}
if response.StatusCode >= 300 {
if payload.Detail == "" {
payload.Detail = response.Status
}
return nil, fmt.Errorf("analyzer models service: %s", payload.Detail)
}
return payload.Result, nil
}
// applyAnalysisResult writes a completed task's output into the tables the rest of the app
// actually reads, not just the analyzer's own history - tags into media_tags (user_id NULL marks
// them as AI-attributed), title/description onto media (never overwriting a value that's already
// set, whether user-edited or from an earlier analysis run), everything else into media.metadata.
func (s *Server) applyAnalysisResult(ctx context.Context, mediaKey string, result map[string]any) {
if result == nil {
return
}
if tagsRaw, ok := result["tags"].([]any); ok {
for _, tagValue := range tagsRaw {
tag, ok := tagValue.(string)
tag = strings.ToLower(strings.TrimSpace(tag))
if !ok || tag == "" {
continue
}
_, _ = s.db.Exec(ctx, `
INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, NULL)
ON CONFLICT (media_key, tag) WHERE user_id IS NULL DO NOTHING`, mediaKey, tag)
}
}
title, _ := result["title"].(string)
description, _ := result["description"].(string)
if strings.TrimSpace(title) != "" || strings.TrimSpace(description) != "" {
_, _ = s.db.Exec(ctx, `
UPDATE media SET
title = COALESCE(NULLIF(media.title, ''), NULLIF($2, '')),
description = COALESCE(NULLIF(media.description, ''), NULLIF($3, ''))
WHERE media_key = $1`, mediaKey, title, description)
}
extra := map[string]any{}
for _, key := range []string{"age", "gender", "nsfwLabel", "nsfwScore", "quality"} {
if value, ok := result[key]; ok {
extra[key] = value
}
}
if len(extra) > 0 {
_, _ = s.db.Exec(ctx, `UPDATE media SET metadata = metadata || $2::jsonb WHERE media_key = $1`, mediaKey, mustJSON(extra))
}
}
// computeLaplacianVariance measures image sharpness/blur without any external model: convert to
// grayscale, convolve with the standard 4-neighbor Laplacian kernel, and take the variance of the
// result - a low variance means a flat/blurry image, a high variance means a lot of sharp edges.
// Only the image formats Go's standard library can decode (JPEG/PNG/GIF) are supported; anything
// else surfaces as a normal per-file error rather than silently skipping.
func computeLaplacianVariance(fullPath string) (float64, error) {
file, err := os.Open(fullPath)
if err != nil {
return 0, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return 0, fmt.Errorf("decode image: %w", err)
}
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width < 3 || height < 3 {
return 0, fmt.Errorf("image too small for quality analysis")
}
gray := make([]float64, width*height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, _ := img.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
gray[y*width+x] = 0.299*float64(r>>8) + 0.587*float64(g>>8) + 0.114*float64(b>>8)
}
}
at := func(x, y int) float64 {
if x < 0 {
x = 0
} else if x >= width {
x = width - 1
}
if y < 0 {
y = 0
} else if y >= height {
y = height - 1
}
return gray[y*width+x]
}
var sum, sumSquares float64
count := float64(width * height)
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
laplacian := at(x-1, y) + at(x+1, y) + at(x, y-1) + at(x, y+1) - 4*at(x, y)
sum += laplacian
sumSquares += laplacian * laplacian
}
}
mean := sum / count
return sumSquares/count - mean*mean, nil
}
// retryPipelineErrors resets one media type's failed items for one stage back onto the queue and
// immediately re-runs that stage for just that type, rather than requiring a full "Run pipeline".
func (s *Server) retryPipelineErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
log.Printf("analyzer: retry errors requested (mediaType=%s, stage=%s)", mediaType, stage)
switch stage {
case "metadata":
go s.retryMetadataErrors(mediaType)
case "thumbnails":
go s.retryThumbnailErrors(mediaType)
case "analyze":
go s.runAiAnalysis(context.Background(), []string{mediaType})
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
_ = ctx
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "started": true})
}
// mediaTypeErrorCondition returns a media_worker_jobs WHERE fragment for one media type, and the
// single arg it needs (if any) - the same "funscript" special-case analyzerHistory and
// parseMediaTypesPayload use, since it isn't a real media_type value on that table, just the
// has_funscript flag on a video/audio row.
func mediaTypeErrorCondition(mediaType string) (string, []any) {
if mediaType == "funscript" {
return "has_funscript = TRUE", nil
}
return "LOWER(COALESCE(media_type, '')) = $1", []any{mediaType}
}
type pipelineStageError struct {
FilePath string `json:"filePath"`
Error string `json:"error"`
}
// pipelineStageErrors returns the most recent error messages recorded for one media type's one
// pipeline stage, so the "Show errors" button next to Retry (see PipelineFlowDiagram.svelte) can
// display what's actually failing instead of just the count already shown in the breakdown.
func (s *Server) pipelineStageErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
ctx := r.Context()
limit := optionalInt(r.URL.Query().Get("limit"), 20, 1, 100)
items := make([]pipelineStageError, 0)
var query string
var args []any
switch stage {
case "metadata":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(metadata_error, '') FROM media_worker_jobs
WHERE metadata_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "thumbnails":
condition, condArgs := mediaTypeErrorCondition(mediaType)
query = fmt.Sprintf(`SELECT file_path, COALESCE(thumbnail_error, '') FROM media_worker_jobs
WHERE thumbnail_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
args = append(condArgs, limit)
case "analyze":
query = `SELECT media_key, COALESCE(error_message, '') FROM media_analysis_tasks
WHERE status = 'error' AND LOWER(media_type) = $1 ORDER BY finished_at DESC NULLS LAST LIMIT $2`
args = []any{mediaType, limit}
default:
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
return
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
writeError(w, http.StatusInternalServerError, "pipeline errors unavailable")
return
}
defer rows.Close()
for rows.Next() {
var item pipelineStageError
if rows.Scan(&item.FilePath, &item.Error) == nil && item.Error != "" {
items = append(items, item)
}
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "errors": items})
}
func (s *Server) retryMetadataErrors(mediaType string) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
rows, err := s.db.Query(ctx, `
SELECT file_path FROM media_worker_jobs
WHERE LOWER(COALESCE(media_type, '')) = $1 AND metadata_status = 'error'`, mediaType)
if err != nil {
return
}
filePaths := make([]string, 0)
for rows.Next() {
var filePath string
if rows.Scan(&filePath) == nil {
filePaths = append(filePaths, filePath)
}
}
rows.Close()
for _, filePath := range filePaths {
if ctx.Err() != nil {
return
}
if probe, probeErr := s.servantProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
} else {
duration := nullableInt64(probe.DurationMs)
width, height := probe.Width, probe.Height
_, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path = $1`, filePath, duration, nullableInt(width), nullableInt(height))
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, filePath)
}
}
}
func (s *Server) retryThumbnailErrors(mediaType string) {
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return
}
ctx, cancel := context.WithCancel(context.Background())
now := time.Now().UTC()
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
candidates, err := s.thumbnailCandidatesWithErrors(ctx, mediaType)
if err != nil {
s.finishThumbnailGeneration(err)
return
}
s.runThumbnailCandidates(ctx, candidates)
}
@@ -0,0 +1,139 @@
package server
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
)
// runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's
// deliberately a simple poll loop rather than a precise cron: schedules only ever run on
// minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler
// than tracking individual timers per schedule.
func (s *Server) runAnalyzerScheduler(ctx context.Context) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.runDueAnalyzerSchedules(ctx)
}
}
}
func (s *Server) runDueAnalyzerSchedules(ctx context.Context) {
rows, err := s.db.Query(ctx, `
SELECT id, tool, settings
FROM workflow_schedules
WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName)
if err != nil {
log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err)
return
}
type due struct {
id, tool string
settings []byte
}
items := make([]due, 0)
for rows.Next() {
var item due
if rows.Scan(&item.id, &item.tool, &item.settings) == nil {
items = append(items, item)
}
}
rows.Close()
for _, item := range items {
if ctx.Err() != nil {
return
}
var parsed struct {
Types []string `json:"types"`
}
_ = json.Unmarshal(item.settings, &parsed)
types := normalizeMediaTypes(parsed.Types, true)
status := "started"
started, err := s.startAnalyzerScheduledRun(item.tool, types)
switch {
case err != nil:
status = "error: " + err.Error()
case !started:
status = "skipped: busy"
}
log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status)
// Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule
// doesn't get retried on every single tick - it just waits for its normal interval instead.
_, _ = s.db.Exec(ctx, `
UPDATE workflow_schedules
SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW()
WHERE id = $1`, item.id, status)
}
}
// startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding
// manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same
// background worker function used everywhere else. "started" is false (not an error) when that
// slot was already busy - the schedule just waits for its next tick rather than queuing up or
// failing loudly, mirroring how the dashboard's own buttons behave under the same condition.
func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) {
now := time.Now().UTC()
switch tool {
case "discover":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
s.scanMu.Unlock()
go s.scanMediaFiles(types)
case "metadata":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now}
s.scanMu.Unlock()
go s.refreshMetadataForTypes(types)
case "cleanup":
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
return false, nil
}
s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now}
s.scanMu.Unlock()
go s.cleanupStaleMedia()
case "thumbnails":
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
s.thumbnailCancel = cancel
s.thumbnailMu.Unlock()
go s.generateThumbnails(runCtx, types)
case "analyze":
s.analysisMu.Lock()
if s.analysis.Running {
s.analysisMu.Unlock()
return false, nil
}
runCtx, cancel := context.WithCancel(context.Background())
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
s.analysisCancel = cancel
s.analysisMu.Unlock()
go s.runAiAnalysis(runCtx, mediaTypesList(types))
default:
return false, fmt.Errorf("unsupported schedule action: %s", tool)
}
return true, nil
}
+195
View File
@@ -0,0 +1,195 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
)
type kioskMessage struct {
Type string `json:"type"`
QueueMode string `json:"queueMode,omitempty"`
DisplayDuration int64 `json:"displayDuration,omitempty"`
}
func (s *Server) kioskWebsocket(w http.ResponseWriter, r *http.Request) {
options := s.websocketAcceptOptions(r)
conn, err := websocket.Accept(w, r, options)
if err != nil {
return
}
defer conn.Close(websocket.StatusNormalClosure, "")
updates := make(chan []byte, 16)
s.kioskMu.Lock()
s.kioskClients[updates] = struct{}{}
latest := s.kioskLatest
s.kioskMu.Unlock()
defer func() {
s.kioskMu.Lock()
delete(s.kioskClients, updates)
s.kioskMu.Unlock()
}()
if latest != "" {
s.kioskSend(updates, map[string]any{"type": "new-image", "path": latest})
}
s.kioskSend(updates, map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(r.Context(), "server_display_duration", "5000")),
})
ctx := r.Context()
writeCtx, cancelWrite := context.WithCancel(ctx)
defer cancelWrite()
go func() {
for {
select {
case <-writeCtx.Done():
return
case data := <-updates:
if err := conn.Write(writeCtx, websocket.MessageText, data); err != nil {
return
}
}
}
}()
s.startKioskPoll()
for {
messageType, payload, readErr := conn.Read(ctx)
if readErr != nil {
return
}
if messageType != websocket.MessageText {
continue
}
var message kioskMessage
if json.Unmarshal(payload, &message) != nil || message.Type != "update-settings" {
continue
}
if message.QueueMode != "" && (message.QueueMode == "client" || message.QueueMode == "server") {
_ = s.saveSetting(ctx, "kiosk_queue_mode", message.QueueMode)
}
if message.DisplayDuration >= 0 && message.DisplayDuration <= 24*60*60*1000 {
_ = s.saveSetting(ctx, "server_display_duration", formatInt(message.DisplayDuration))
}
s.kioskBroadcast(map[string]any{
"type": "settings-updated",
"queueMode": s.settingValue(ctx, "kiosk_queue_mode", "client"),
"serverDisplayDuration": kioskDuration(s.settingValue(ctx, "server_display_duration", "5000")),
})
}
}
func (s *Server) startKioskPoll() {
s.kioskMu.Lock()
if s.kioskPolling {
s.kioskMu.Unlock()
return
}
s.kioskPolling = true
s.kioskMu.Unlock()
go s.kioskPoll(context.Background())
}
func (s *Server) kioskPoll(ctx context.Context) {
if s.cfg.Service != config.Kiosk {
return
}
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
s.kioskPollOnce(ctx)
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
func (s *Server) kioskPollOnce(ctx context.Context) {
files, err := s.servantListFiles(ctx, "", false, 0)
if err != nil {
return
}
images := make([]fileEntry, 0, len(files))
for _, file := range files {
if file.Type == "image" {
images = append(images, file)
}
}
if len(images) == 0 {
return
}
sort.Slice(images, func(i, j int) bool { return images[i].Mtime > images[j].Mtime })
latest := images[0].Rel
s.kioskMu.Lock()
changed := latest != s.kioskLatest
s.kioskLatest = latest
s.kioskMu.Unlock()
if changed {
s.kioskBroadcast(map[string]any{"type": "new-image", "path": latest})
}
}
func (s *Server) kioskBroadcast(message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
s.kioskMu.Lock()
defer s.kioskMu.Unlock()
for client := range s.kioskClients {
select {
case client <- data:
default:
}
}
}
func (s *Server) kioskSend(client chan []byte, message any) {
data, err := json.Marshal(message)
if err != nil {
return
}
select {
case client <- data:
default:
}
}
func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/api/images/")
}
if !safeRelative(relative) || !isImagePath(relative) {
writeError(w, http.StatusNotFound, "image not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(relative))
}
func kioskDuration(value string) int64 {
var duration int64
if _, err := fmt.Sscanf(value, "%d", &duration); err != nil || duration < 0 {
return 5000
}
return duration
}
func formatInt(value int64) string {
return strconv.FormatInt(value, 10)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,83 @@
package server
import (
"net"
"os"
"path/filepath"
"strings"
"testing"
)
func TestSafeRelativeRejectsTraversal(t *testing.T) {
for _, value := range []string{"", ".", "..", "../secret", `..\secret`, `/etc/passwd`, "a/../../b"} {
if safeRelative(value) {
t.Errorf("safeRelative(%q) = true", value)
}
}
for _, value := range []string{"video.mp4", "nested/image.webp", "funscript.json"} {
if !safeRelative(value) {
t.Errorf("safeRelative(%q) = false", value)
}
}
}
func TestSameRealRootRejectsSymlinkEscape(t *testing.T) {
root := t.TempDir()
inside := filepath.Join(root, "inside.txt")
if err := os.WriteFile(inside, []byte("ok"), 0o600); err != nil {
t.Fatal(err)
}
if !sameRealRoot(root, inside) {
t.Fatal("sameRealRoot rejected a file inside the root")
}
outside := t.TempDir()
outsideFile := filepath.Join(outside, "outside.txt")
if err := os.WriteFile(outsideFile, []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(root, "link.txt")
if err := os.Symlink(outsideFile, link); err != nil {
t.Skipf("symlink unavailable: %v", err)
}
if sameRealRoot(root, link) {
t.Fatal("sameRealRoot accepted a symlink outside the root")
}
}
func TestConversionArgsDoNotAcceptArbitraryEncoderFlags(t *testing.T) {
args := strings.Join(conversionArgs("input.mp4", "output.mp4", "mp4", "-filter_complex malicious"), " ")
if strings.Contains(args, "malicious") || !strings.Contains(args, "libx264") {
t.Fatalf("conversion args = %q", args)
}
}
func TestHasFunscriptSidecar(t *testing.T) {
root := t.TempDir()
mediaPath := filepath.Join(root, "clip.mp4")
if os.WriteFile(mediaPath, []byte("media"), 0o600) != nil {
t.Fatal("could not create media fixture")
}
if hasFunscriptSidecar(mediaPath) {
t.Fatal("media without a sidecar was marked as having a funscript")
}
if os.WriteFile(filepath.Join(root, "clip.funscript"), []byte("{}"), 0o600) != nil {
t.Fatal("could not create funscript fixture")
}
if !hasFunscriptSidecar(mediaPath) {
t.Fatal("funscript sidecar was not detected")
}
}
func TestDownloadURLValidation(t *testing.T) {
for _, value := range []string{"file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/", "https://user:pass@example.com/x"} {
if err := validateDownloadURL(value); err == nil {
t.Errorf("validateDownloadURL(%q) succeeded", value)
}
}
if err := validateDownloadURL("https://example.com/video"); err != nil {
t.Fatalf("public URL rejected: %v", err)
}
if !isPrivateIP(net.ParseIP("127.0.0.1")) {
t.Fatal("loopback was not classified as private")
}
}
@@ -0,0 +1,331 @@
package server
// Servant client: every non-Servant service serves and stores media by calling Porter's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// servantHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var servantHTTPClient = &http.Client{}
func (s *Server) servantClient() *http.Client {
return servantHTTPClient
}
// servantBaseURL is configured in MediaConfig and stored in the settings table (key
// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in MediaConfig takes
// effect on every service's very next request without a restart. SERVANT_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) servantBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/")
}
func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyServant streams a Servant response straight through to the original client, preserving
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
// http.ServeContent on this side.
func (s *Server) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) {
request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range servantForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.servantClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range servantForwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
}
// probeServant checks whether a Servant-served path exists without fetching its bytes.
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
// problems are surfaced as errors.
func (s *Server) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) {
request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return false, 0, time.Time{}, err
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return false, 0, time.Time{}, nil
}
if response.StatusCode >= 400 {
return false, 0, time.Time{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
return true, size, modTime, nil
}
// fetchServantToScratch downloads a Servant-served path into an ephemeral temp file for local
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
// returned cleanup once done; it removes the scratch file unconditionally.
func (s *Server) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) {
request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil)
if err != nil {
return "", nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "servant-src-*"+suffix)
if err != nil {
return "", nil, err
}
cleanup := func() { _ = os.Remove(scratch.Name()) }
if _, err := io.Copy(scratch, response.Body); err != nil {
scratch.Close()
cleanup()
return "", nil, err
}
if err := scratch.Close(); err != nil {
cleanup()
return "", nil, err
}
return scratch.Name(), cleanup, nil
}
// pushToServant streams a local file as the request body without buffering it in memory.
func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newServantRequest(ctx, method, servantPath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
response.Body.Close()
return nil, fmt.Errorf("servant push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func servantPushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.servantClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("servant delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
if err != nil {
return nil, err
}
defer response.Body.Close()
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantStoreDownload catalogs an already-uploaded file into Servant's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) servantStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
if err != nil {
return nil, err
}
request, err := s.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return nil, fmt.Errorf("servant store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) servantListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
endpoint := "/api/files"
if recent {
endpoint = "/api/files/recent"
}
query := url.Values{}
if relative != "" {
query.Set("path", relative)
}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if encoded := query.Encode(); encoded != "" {
endpoint += "?" + encoded
}
request, err := s.newServantRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("servant file listing failed: %s", response.Status)
}
var payload struct {
Files []fileEntry `json:"files"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
return nil, err
}
return payload.Files, nil
}
type servantProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave Servant, unlike every other helper in this file.
func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return servantProbeResult{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return servantProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
var result servantProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return servantProbeResult{}, err
}
return result, nil
}
+433
View File
@@ -0,0 +1,433 @@
package server
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/auth"
"mediacollection/internal/config"
)
type Server struct {
cfg *config.Config
db *pgxpool.Pool
auth *auth.Service
startedAt time.Time
mediaMu sync.RWMutex
media map[string]MediaRecord
jobsMu sync.RWMutex
jobs map[string]*WorkflowJob
workflowSem chan struct{}
sync *syncHub
thumbnailMu sync.Mutex
thumbnail thumbnailGenerationState
thumbnailCancel context.CancelFunc
clearMu sync.Mutex
clear databaseClearState
scanMu sync.Mutex
scan scanState
scanCancel context.CancelFunc
analysisMu sync.Mutex
analysis analysisState
analysisCancel context.CancelFunc
kioskMu sync.Mutex
kioskClients map[chan []byte]struct{}
kioskLatest string
kioskPolling bool
}
type MediaRecord struct {
ID int64
MediaKey string
MediaType string
Title *string
Description *string
FilePath string
OriginalName string
Source string
Width *int
Height *int
DurationMs *int64
SizeBytes *int64
IsVR bool
HasFunscript bool
Speed *float32
ModifiedAt time.Time
}
type WorkflowJob struct {
ID string `json:"id"`
Service string `json:"service"`
Tool string `json:"tool"`
Status string `json:"status"`
Progress int `json:"progress"`
Request map[string]any `json:"request,omitempty"`
Result map[string]any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"createdAt"`
StartedAt *time.Time `json:"startedAt,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
}
type thumbnailGenerationState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the
// same live status endpoint as the analyzer workers. The reset itself is deliberately kept
// synchronous from the HTTP caller's perspective, but large libraries still need an honest state
// while their thumbnail files and database rows are being removed.
type databaseClearState struct {
Running bool
State string
Total int
Completed int
Failed int
Current string
CurrentType string
StartedAt *time.Time
FinishedAt *time.Time
LastError string
}
// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show
// which media type is actively being indexed right now - scanMediaFiles has no separate queue,
// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as
// it's found, so "active" here is the closest honest signal to a live "processing" state.
type scanState struct {
Running bool
Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep)
CurrentType string
CurrentFile string
FilesIndexed int64
// Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before
// looping. discover has no total (a live filesystem walk doesn't know its own size in advance)
// and leaves this at zero, which the UI treats as "not available".
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. Porter unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
func New(cfg *config.Config, db *pgxpool.Pool) *Server {
return &Server{
cfg: cfg,
db: db,
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
startedAt: time.Now(),
media: make(map[string]MediaRecord),
jobs: make(map[string]*WorkflowJob),
workflowSem: make(chan struct{}, 2),
sync: newSyncHub(),
thumbnail: thumbnailGenerationState{State: "idle"},
analysis: analysisState{State: "idle"},
kioskClients: make(map[chan []byte]struct{}),
}
}
func (s *Server) Handler() http.Handler {
router := chi.NewRouter()
router.Use(chimiddleware.RequestID)
router.Use(chimiddleware.Recoverer)
router.Use(s.securityHeadersMiddleware)
router.Use(s.cors)
router.Get("/healthz", s.health)
router.Get("/health", s.health)
router.Get("/ready", s.ready)
router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack)
router.Get("/__cache-policy", s.cachePolicy)
router.Route("/auth", func(r chi.Router) {
r.Post("/signup", s.auth.Signup)
r.Post("/login", s.auth.Login)
r.Post("/logout", s.auth.Logout)
r.Post("/reset/request", s.auth.RequestAdminReset)
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
r.Get("/me", s.auth.Me)
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
r.Get("/status", s.auth.Status)
r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded)
})
router.Route("/api/auth", func(r chi.Router) {
manager := r.With(s.auth.RequireUserManager)
manager.Get("/access", s.auth.AccessSettings)
manager.Put("/access", s.auth.UpdateAccessSettings)
manager.Get("/users", s.auth.ManagedUsers)
manager.Post("/users", s.auth.ManagedCreateUser)
manager.Put("/users/{id}", s.auth.ManagedUpdateUser)
manager.Patch("/users/{id}", s.auth.ManagedUpdateUser)
manager.Delete("/users/{id}", s.auth.ManagedDeleteUser)
})
router.Route("/api", func(r chi.Router) {
s.mountServiceRoutes(r)
})
if s.cfg.Service == config.Kiosk {
s.mountKioskSocket(router)
}
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.Servant {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
}
router.NotFound(s.staticHandler)
return router
}
func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountSharedRoutes(r)
switch s.cfg.Service {
case config.Viewer:
s.mountViewerRoutes(r)
case config.Tools:
s.mountToolsRoutes(r)
case config.Analyzer:
s.mountAnalyzerRoutes(r)
case config.ConfigService:
s.mountConfigRoutes(r)
case config.Moderator:
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.Desktop:
s.mountDesktopRoutes(r)
}
}
func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "same-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:")
next.ServeHTTP(w, r)
})
}
func (s *Server) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Add("Vary", "Origin")
}
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())})
}
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
if s.db == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.db.Ping(ctx); err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName})
}
func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) {
appVersion := os.Getenv("APP_VERSION")
if appVersion == "" {
appVersion = "go-rewrite"
}
writeJSON(w, http.StatusOK, map[string]any{
"appVersion": appVersion,
"stack": []map[string]string{
{"label": "Runtime", "value": runtime.Version()},
{"label": "HTTP", "value": "net/http + chi"},
{"label": "Database", "value": "PostgreSQL + pgx"},
{"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"},
},
})
}
func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}})
}
func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) {
root := os.DirFS(s.cfg.WebRoot)
if _, err := fs.Stat(root, "."); err != nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"})
return
}
requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
if requested == "." || requested == "" {
requested = "index.html"
}
if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() {
http.FileServer(http.FS(root)).ServeHTTP(w, r)
return
}
if path.Ext(requested) != "" {
http.NotFound(w, r)
return
}
index, err := fs.ReadFile(root, "index.html")
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(index)
}
func (s *Server) listenAndServe(ctx context.Context) error {
server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port)
if s.cfg.TLSCertFile != "" {
return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile)
}
return server.ListenAndServe()
}
func (s *Server) Run(ctx context.Context) error {
go s.resumeWorkflowJobs(ctx)
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
return s.listenAndServe(ctx)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func intValue(value *int) any {
if value == nil {
return nil
}
return *value
}
func int64Value(value *int64) any {
if value == nil {
return nil
}
return *value
}
func floatValue(value *float32) any {
if value == nil {
return nil
}
return *value
}
func boolQuery(value string) *bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "1", "true", "yes", "on":
result := true
return &result
case "0", "false", "no", "off":
result := false
return &result
default:
return nil
}
}
func (s *Server) internalServiceAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret {
writeError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) {
next.ServeHTTP(w, r)
return
}
writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required")
})
}
func optionalInt(value string, fallback, minimum, maximum int) int {
var parsed int
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil {
return fallback
}
if parsed < minimum {
return minimum
}
if parsed > maximum {
return maximum
}
return parsed
}
+541
View File
@@ -0,0 +1,541 @@
package server
import (
"context"
"encoding/json"
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coder/websocket"
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
)
type syncPeer struct {
conn *websocket.Conn
writeMu sync.Mutex
clientID string
sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool
uiView string
uiMediaID any
uiMediaIDSet bool
}
type syncHub struct {
mu sync.Mutex
peers map[*syncPeer]struct{}
states map[string]map[string]any
playAt map[string]string
playAtLocalMs map[string]int64
capturedAtMs map[string]int64
controlOwners map[string]string
}
func newSyncHub() *syncHub {
return &syncHub{
peers: make(map[*syncPeer]struct{}),
states: make(map[string]map[string]any),
playAt: make(map[string]string),
playAtLocalMs: make(map[string]int64),
capturedAtMs: make(map[string]int64),
controlOwners: make(map[string]string),
}
}
func (h *syncHub) add(peer *syncPeer) {
h.mu.Lock()
h.peers[peer] = struct{}{}
h.mu.Unlock()
}
func (h *syncHub) remove(peer *syncPeer) string {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.peers, peer)
if peer.clientID != "" && !h.hasClientLocked(peer.clientID) {
delete(h.controlOwners, peer.clientID)
for targetID, ownerID := range h.controlOwners {
if ownerID == peer.clientID {
delete(h.controlOwners, targetID)
}
}
}
return peer.sessionID
}
func (h *syncHub) hasClientLocked(clientID string) bool {
for peer := range h.peers {
if peer.clientID == clientID {
return true
}
}
return false
}
func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) {
h.mu.Lock()
if clientID != "" {
peer.clientID = clientID
}
if sessionID != "" {
peer.sessionID = sessionID
}
h.mu.Unlock()
}
func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
h.mu.Lock()
defer h.mu.Unlock()
if sessionID != "" {
peer.sessionID = sessionID
}
if view != "" {
peer.uiView = view
}
if mediaIDSet {
peer.uiMediaID = mediaID
peer.uiMediaIDSet = true
}
if remoteSet {
peer.remoteControlEnabled = remote
if !remote && h.controlOwners[peer.clientID] != "" {
delete(h.controlOwners, peer.clientID)
}
}
}
func (h *syncHub) clientsLocked(sessionID string) []map[string]any {
byID := make(map[string]map[string]any)
for peer := range h.peers {
if peer.sessionID != sessionID || peer.clientID == "" {
continue
}
entry, exists := byID[peer.clientID]
if !exists {
entry = map[string]any{
"clientId": peer.clientID,
"userAgent": peer.userAgent,
"ipAddress": peer.ipAddress,
"remoteControlEnabled": peer.remoteControlEnabled,
"controlOwnerClientId": nil,
}
byID[peer.clientID] = entry
} else if peer.remoteControlEnabled {
entry["remoteControlEnabled"] = true
}
if peer.uiView != "" {
entry["uiView"] = peer.uiView
}
if peer.uiMediaIDSet {
entry["uiMediaId"] = peer.uiMediaID
}
}
for clientID, entry := range byID {
if owner := h.controlOwners[clientID]; owner != "" {
entry["controlOwnerClientId"] = owner
}
}
clients := make([]map[string]any, 0, len(byID))
for _, entry := range byID {
clients = append(clients, entry)
}
return clients
}
func (h *syncHub) stateLocked(sessionID string) map[string]any {
state, ok := h.states[sessionID]
if !ok {
return map[string]any{
"sessionId": sessionID,
"mediaId": nil,
"timeMs": int64(0),
"paused": true,
"fps": 30,
"frame": int64(0),
"fromClientId": "",
"updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano),
}
}
return cloneMap(state)
}
func (h *syncHub) httpState(sessionID string) map[string]any {
h.mu.Lock()
defer h.mu.Unlock()
return h.timingLocked(sessionID, h.stateLocked(sessionID))
}
func (h *syncHub) setHTTPState(sessionID string, state map[string]any) {
h.mu.Lock()
defer h.mu.Unlock()
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
for key := range h.states {
delete(h.states, key)
break
}
}
}
func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[string]any {
paused, _ := state["paused"].(bool)
if !paused {
if value := h.playAt[sessionID]; value != "" {
state["playAt"] = value
}
}
if value, ok := h.playAtLocalMs[sessionID]; ok {
state["playAtLocalMs"] = value
}
if value, ok := h.capturedAtMs[sessionID]; ok {
state["capturedAtLocalMs"] = value
}
return state
}
func (h *syncHub) broadcast(sessionID string) {
h.mu.Lock()
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
clients := h.clientsLocked(sessionID)
peers := make([]*syncPeer, 0)
for peer := range h.peers {
if peer.sessionID == sessionID {
peers = append(peers, peer)
}
}
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
for _, peer := range peers {
if err := peer.send(message); err != nil {
_ = peer.conn.Close(websocket.StatusGoingAway, "write failed")
}
}
}
func (peer *syncPeer) send(message any) error {
data, err := json.Marshal(message)
if err != nil {
return err
}
peer.writeMu.Lock()
defer peer.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return peer.conn.Write(ctx, websocket.MessageText, data)
}
func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{}
if s.cfg.AllowedOrigin == "*" {
options.InsecureSkipVerify = true
return options
}
patterns := make([]string, 0, 2)
addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value))
if err == nil && parsed.Scheme != "" && parsed.Host != "" {
patterns = append(patterns, parsed.Scheme+"://"+parsed.Host)
}
}
addOrigin(s.cfg.AllowedOrigin)
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
addOrigin(scheme + "://" + r.Host)
options.OriginPatterns = patterns
return options
}
func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r))
if err != nil {
return
}
peer := &syncPeer{
conn: conn,
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
}
s.sync.add(peer)
defer func() {
sessionID := s.sync.remove(peer)
_ = conn.Close(websocket.StatusNormalClosure, "")
if sessionID != "" {
s.sync.broadcast(sessionID)
}
}()
_ = peer.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
for {
messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil {
return
}
if messageType != websocket.MessageText {
continue
}
var message map[string]any
if json.Unmarshal(payload, &message) != nil {
continue
}
s.handleSyncMessage(peer, message)
}
}
func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) {
typ, _ := message["type"].(string)
switch typ {
case "ws:ping":
_ = peer.send(map[string]any{
"type": "ws:pong",
"nonce": syncString(message, "nonce"),
"clientSentAt": syncNumberValue(message, "clientSentAt"),
"serverReceivedAt": time.Now().UnixMilli(),
})
case "sync:hello":
clientID := boundedSyncString(syncString(message, "clientId"))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if clientID == "" || sessionID == "" {
return
}
s.sync.updatePeer(peer, clientID, sessionID)
s.sync.broadcast(sessionID)
case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
if clientID == "" {
return
}
s.sync.updatePeer(peer, clientID, sessionID)
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
s.sync.clientStatus(peer, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
s.sync.broadcast(sessionID)
case "control:claim", "control:release":
s.handleControlMessage(peer, typ, message)
case "sync:update":
s.handleSyncUpdate(peer, message)
}
}
func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != peer.clientID {
return
}
s.sync.mu.Lock()
owner := s.sync.controlOwners[targetID]
ok := false
reason := ""
if typ == "control:claim" {
enabled := false
for candidate := range s.sync.peers {
if candidate.clientID == targetID && candidate.remoteControlEnabled {
enabled = true
break
}
}
switch {
case !enabled:
reason = "disabled"
case owner != "" && owner != requesterID:
reason = "busy"
default:
s.sync.controlOwners[targetID] = requesterID
owner = requesterID
ok = true
}
} else if owner != "" && owner != requesterID {
reason = "not-owner"
} else {
delete(s.sync.controlOwners, targetID)
owner = ""
ok = true
}
s.sync.mu.Unlock()
_ = peer.send(map[string]any{
"type": "control:ack",
"ok": ok,
"action": strings.TrimPrefix(typ, "control:"),
"targetClientId": targetID,
"ownerClientId": nullableString(owner),
"reason": nullableString(reason),
})
s.sync.broadcast(sessionID)
}
func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
if clientID == "" || clientID != peer.clientID {
return
}
mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused")
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(message, "timeMs", 0),
"paused": paused,
"fps": syncFPS(message),
"frame": syncInt(message, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} {
if value, ok := message[key]; ok {
state[key] = value
}
}
toClientID := boundedSyncString(syncString(message, "toClientId"))
playAtRaw, hasPlayAt := message["playAt"]
s.sync.mu.Lock()
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
delete(s.sync.playAt, sessionID)
delete(s.sync.playAtLocalMs, sessionID)
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
s.sync.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
s.sync.playAtLocalMs[sessionID] = local
} else {
delete(s.sync.playAtLocalMs, sessionID)
}
}
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
s.sync.capturedAtMs[sessionID] = captured
}
if toClientID == "" {
s.sync.states[sessionID] = cloneMap(state)
if len(s.sync.states) > maxSyncSessions {
for key := range s.sync.states {
delete(s.sync.states, key)
break
}
}
}
state = s.sync.timingLocked(sessionID, state)
clients := s.sync.clientsLocked(sessionID)
peers := make([]*syncPeer, 0)
if toClientID != "" {
for candidate := range s.sync.peers {
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
peers = append(peers, candidate)
}
}
}
s.sync.mu.Unlock()
messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients}
if toClientID != "" {
for _, target := range peers {
if err := target.send(messageOut); err != nil {
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
}
}
return
}
s.sync.broadcast(sessionID)
}
func syncMediaID(message map[string]any) (any, bool) {
value, ok := message["mediaId"]
if !ok {
return nil, false
}
if value == nil {
return nil, true
}
return boundedSyncString(syncStringValue(value)), true
}
func syncString(message map[string]any, key string) string {
return syncStringValue(message[key])
}
func syncStringValue(value any) string {
if value == nil {
return ""
}
if text, ok := value.(string); ok {
return strings.TrimSpace(text)
}
return ""
}
func boundedSyncString(value string) string {
value = strings.TrimSpace(value)
if len(value) > maxSyncIdentifier {
return value[:maxSyncIdentifier]
}
return value
}
func syncBool(message map[string]any, key string) bool {
value, _ := message[key].(bool)
return value
}
func syncNumberValue(message map[string]any, key string) any {
if value, ok := message[key]; ok {
return value
}
return nil
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok || math.IsNaN(value) || math.IsInf(value, 0) {
return fallback
}
if value < 0 {
return 0
}
if value > float64(^uint64(0)>>1) {
return int64(^uint64(0) >> 1)
}
return int64(math.Round(value))
}
func syncFPS(message map[string]any) int64 {
fps := syncInt(message, "fps", 30)
if fps < 1 {
return 1
}
if fps > 240 {
return 240
}
return fps
}
func nullableString(value string) any {
if value == "" {
return nil
}
return value
}
func cloneMap(value map[string]any) map[string]any {
result := make(map[string]any, len(value))
for key, item := range value {
result[key] = item
}
return result
}
File diff suppressed because it is too large. Load diff