2026-08-31 22:06:29 +02:00
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
2026-08-31 22:19:58 +02:00
// container, not baked into this binary - see ANALYZER_MODELS_URL and MediaAnalyzer/Dockerfile),
2026-08-31 22:06:29 +02:00
// 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 )
}