Files
shared/media-backend/internal/server/analyzer.go
T

2182 lines
81 KiB
Go
Raw Normal View History

package server
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
)
func (s *Server) mountAnalyzerRoutes(r chi.Router) {
r.Get("/status", s.analyzerStatus)
r.Get("/stats", s.analyzerStats)
r.Get("/history", s.analyzerHistory)
r.Get("/extract/count", s.analyzerExtractCount)
r.Get("/generate/status", s.analyzerGenerateStatus)
r.Get("/events", s.analyzerEvents)
r.Get("/media", s.listMedia)
r.Get("/thumb", s.analyzerThumb)
r.Get("/model-config", s.modelConfig)
r.With(s.auth.RequireIfLoginRequired).Post("/model-config", s.saveModelConfig)
r.With(s.auth.RequireIfLoginRequired).Post("/model-config/order", s.saveModelOrder)
r.Get("/pipeline-config", s.pipelineConfig)
r.With(s.auth.RequireIfLoginRequired).Post("/pipeline-config", s.savePipelineConfig)
r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/{mediaType}/clear", s.clearMediaTypePipeline)
r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/clear", s.clearPipelineSelection)
r.With(s.auth.RequireIfLoginRequired).Post("/pipeline/{mediaType}/retry-errors/{stage}", func(w http.ResponseWriter, req *http.Request) {
s.retryPipelineErrors(w, req, strings.ToLower(chi.URLParam(req, "mediaType")), strings.ToLower(chi.URLParam(req, "stage")))
})
r.Get("/pipeline/{mediaType}/errors/{stage}", func(w http.ResponseWriter, req *http.Request) {
s.pipelineStageErrors(w, req, strings.ToLower(chi.URLParam(req, "mediaType")), strings.ToLower(chi.URLParam(req, "stage")))
})
r.Get("/automation-schedules", s.analyzerSchedules)
r.With(s.auth.RequireIfLoginRequired).Post("/automation-schedules", s.createAnalyzerSchedule)
r.With(s.auth.RequireIfLoginRequired).Post("/automation-schedules/{id}/run", s.runAnalyzerSchedule)
r.With(s.auth.RequireIfLoginRequired).Delete("/automation-schedules/{id}", s.deleteAnalyzerSchedule)
r.Get("/conversion-settings", s.conversionSettings)
r.With(s.auth.RequireIfLoginRequired).Post("/conversion-settings", s.saveConversionSettings)
r.With(s.auth.RequireIfLoginRequired).Post("/extract/discover", s.analyzerDiscover)
r.With(s.auth.RequireIfLoginRequired).Post("/metadata/start", s.analyzerMetadataStart)
r.With(s.auth.RequireIfLoginRequired).Post("/cleanup/start", s.analyzerCleanupStart)
r.With(s.auth.RequireIfLoginRequired).Post("/scan/stop", s.analyzerScanStop)
for _, action := range []string{"extract/start", "extract/queued/start", "retry-errors/start", "reprocess-all/start", "convert/start", "convert/start-group", "convert/start-discovered", "watcher/enable", "watcher/disable", "extract/stop", "extract/pause", "extract/resume"} {
actionPath := action
r.With(s.auth.RequireIfLoginRequired).Post("/"+actionPath, func(w http.ResponseWriter, req *http.Request) { s.analyzerAction(w, req, actionPath) })
}
r.With(s.auth.RequireIfLoginRequired).Post("/generate/start", s.analyzerGenerateStart)
r.With(s.auth.RequireIfLoginRequired).Post("/generate/stop", s.analyzerGenerateStop)
r.Get("/analyze/status", s.analyzerAnalyzeStatus)
r.With(s.auth.RequireIfLoginRequired).Post("/analyze/start", s.analyzerAnalyzeStart)
r.With(s.auth.RequireIfLoginRequired).Post("/analyze/stop", s.analyzerAnalyzeStop)
r.With(s.auth.RequireIfLoginRequired).Post("/analyze/queued/start", s.analyzerAnalyzeStart)
r.With(s.auth.RequireIfLoginRequired).Post("/redo-analysis/start", s.analyzerAnalyzeStart)
}
// analyzerStatus reports the analyzer's overall live state for the dashboard, schedules, and
// discover pages. media_worker_jobs rows never actually sit in "processing" - scanMediaFiles
// indexes each file synchronously straight to "done" - so job-table counts alone can't tell the
// UI a discovery walk, thumbnail pass, AI analysis run, or database clear is active. The in-memory
// scan/thumbnail/analysis/clear state (also used by analyzerPipelineBreakdown) is the only honest
// source for that, so it takes priority here and the job counts are just a fallback for outside
// consumers of "queue".
func (s *Server) analyzerStatus(w http.ResponseWriter, r *http.Request) {
// One query (four counts via FILTER) instead of four, run concurrently with the paused-setting
// lookup instead of after it - two round trips total instead of five, one after another.
var queued, processing, done, failed int64
var paused bool
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
_ = s.db.QueryRow(r.Context(), `
SELECT
COUNT(*) FILTER (WHERE status = 'queued'),
COUNT(*) FILTER (WHERE status = 'processing'),
COUNT(*) FILTER (WHERE status IN ('done', 'completed')),
COUNT(*) FILTER (WHERE status IN ('error', 'failed'))
FROM media_worker_jobs`).Scan(&queued, &processing, &done, &failed)
}()
go func() {
defer wg.Done()
paused = s.settingBool(r.Context(), "analyzer_paused", false)
}()
wg.Wait()
s.scanMu.Lock()
scan := s.scan
s.scanMu.Unlock()
s.thumbnailMu.Lock()
thumbnail := s.thumbnail
s.thumbnailMu.Unlock()
s.analysisMu.Lock()
analysis := s.analysis
s.analysisMu.Unlock()
s.clearMu.Lock()
clear := s.clear
s.clearMu.Unlock()
state, worker, current, currentType := "idle", "", "", ""
total, completed, jobFailed := 0, int(done), int(failed)
switch {
case clear.Running:
state, worker, current, currentType = "clearing", "Database cleanup", clear.Current, clear.CurrentType
total, completed, jobFailed = clear.Total, clear.Completed, clear.Failed
case scan.Running:
switch scan.Mode {
case "metadata":
state, worker = "extracting", "Metadata extraction"
case "cleanup":
state, worker = "cleaning", "Cleanup"
default:
state, worker = "discovering", "Discovery"
}
current, currentType = scan.CurrentFile, scan.CurrentType
completed = int(scan.FilesIndexed)
total = int(scan.Total) // only metadata/cleanup pre-fetch their row list; discover leaves this 0 (unknown)
// FilesIndexed counts every item touched this run, success or failure, so it alone already
// reaches Total when done - the default jobFailed above is a stale, unrelated, all-time
// count from the job-table query at the top of this function, not this run's failures. Left
// in, completed+failed could exceed Total and make the progress bar look wrong/stuck.
jobFailed = 0
case thumbnail.Running:
state, worker, current, currentType = "generating", "Thumbnail generation", thumbnail.Current, thumbnail.CurrentType
total, completed, jobFailed = thumbnail.Total, thumbnail.Completed, thumbnail.Failed
case analysis.Running:
state, worker, current, currentType = "analyzing", "AI analysis", analysis.Current, analysis.CurrentType
total, completed, jobFailed = analysis.Total, analysis.Completed, analysis.Failed
case paused:
state = "paused"
case processing > 0:
state, worker = "processing", "Extraction"
}
running := clear.Running || scan.Running || thumbnail.Running || analysis.Running || processing > 0
// scan/clear have no dedicated status endpoint of their own (thumbnail/analysis do, via
// generate/status and analyze/status) - this is the only place their LastError ever reaches
// the UI, so a discover/metadata/cleanup run that fails fast (e.g. Porter unreachable)
// is reported here instead of just looking like it silently reverted to idle.
lastError := firstNonEmpty(scan.LastError, clear.LastError)
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "running": running, "paused": paused, "state": state,
"worker": worker, "current": current, "currentType": currentType,
"total": total, "completed": completed, "failed": jobFailed,
"lastError": lastError,
"updatedAt": time.Now().UTC(),
"queue": map[string]any{"queued": queued, "processing": processing, "done": done, "failed": failed},
"extractionProgress": map[string]any{
"queued": queued, "processing": processing, "completed": done, "failed": failed, "paused": paused,
},
})
}
func (s *Server) analyzerStats(w http.ResponseWriter, r *http.Request) {
result := map[string]any{}
// Three round trips (media counts, job total, breakdown) run concurrently instead of one after
// another - the media counts used to be five separate single-purpose queries on top of that,
// now folded into the one below via FILTER. Loading this page used to mean seven-plus
// sequential DB round trips; it's now effectively the cost of the single slowest query.
var wg sync.WaitGroup
var pipeline map[string]analyzerPipelineMedia
var jobTotal int64
wg.Add(1)
go func() {
defer wg.Done()
var media, images, videos, audio, funscripts int64
err := s.db.QueryRow(r.Context(), `
SELECT
COUNT(*) FILTER (WHERE active = TRUE),
COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'image'),
COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'video'),
COUNT(*) FILTER (WHERE active = TRUE AND LOWER(COALESCE(media_type, '')) = 'audio'),
COUNT(*) FILTER (WHERE active = TRUE AND has_funscript = TRUE)
FROM media`).Scan(&media, &images, &videos, &audio, &funscripts)
if err != nil {
return
}
result["media"] = media
result["images"] = images
result["videos"] = videos
result["audio"] = audio
result["funscripts"] = funscripts
}()
wg.Add(1)
go func() {
defer wg.Done()
_ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_worker_jobs`).Scan(&jobTotal)
}()
wg.Add(1)
go func() {
defer wg.Done()
pipeline = s.analyzerPipelineBreakdown(r.Context())
}()
wg.Wait()
result["total"] = jobTotal
for _, key := range []string{"media", "images", "videos", "audio", "funscripts"} {
if _, ok := result[key]; !ok {
result[key] = int64(0)
}
}
queued, processing, completed, errors := summarizePipelineBreakdown(pipeline)
// Top-level totals are the sum of the exact same per-stage, per-media-type buckets the
// pipeline breakdown card renders below them (see summarizePipelineBreakdown), rather than a
// separate media_worker_jobs-only query - that query only ever reflects the "discover" stage
// (and media_worker_jobs rows go straight to "done" on discovery, never "processing"), so it
// silently ignored every file still queued/processing/erroring in metadata, thumbnails, or AI
// analysis and could never agree with what the breakdown showed underneath it.
result["queued"] = queued
result["processing"] = processing
result["completed"] = completed
result["errors"] = errors
result["failed"] = errors
result["pipeline"] = pipeline
writeJSON(w, http.StatusOK, result)
}
// summarizePipelineBreakdown sums queued/processing/completed/errors across every stage and media
// type the pipeline breakdown actually shows, mirroring AnalyzerPipelineBreakdown.svelte's
// stagesFor() filtering: thumbnails only ever run for images/videos, and funscript has no AI
// analysis stage, so those combinations (which the breakdown map still carries, always zero-ish
// but not meaningfully so - see the thumbnail/analysis queries) are excluded here exactly as they
// are from the rendered table, keeping the dashboard totals and the breakdown card in agreement.
func summarizePipelineBreakdown(breakdown map[string]analyzerPipelineMedia) (queued, processing, completed, errors int64) {
for _, stage := range []string{"discover", "extract", "generate", "analyze"} {
for _, mediaType := range []string{"image", "video", "audio", "funscript"} {
if stage == "generate" && mediaType != "image" && mediaType != "video" {
continue
}
if stage == "analyze" && mediaType == "funscript" {
continue
}
counts, ok := breakdown[stage][mediaType]
if !ok {
continue
}
queued += counts["queued"]
processing += counts["processing"]
completed += counts["completed"]
errors += counts["errors"]
}
}
return
}
type analyzerPipelineCounts map[string]int64
type analyzerPipelineMedia map[string]analyzerPipelineCounts
func newAnalyzerPipelineBreakdown() map[string]analyzerPipelineMedia {
breakdown := make(map[string]analyzerPipelineMedia)
for _, stage := range []string{"discover", "convert", "extract", "generate", "analyze"} {
breakdown[stage] = make(analyzerPipelineMedia)
for _, mediaType := range []string{"image", "video", "audio", "funscript"} {
breakdown[stage][mediaType] = analyzerPipelineCounts{"queued": 0, "processing": 0, "completed": 0, "errors": 0, "active": 0}
}
}
return breakdown
}
// analyzerPipelineBreakdown runs six independent queries against three different tables. They used
// to run one after another - six sequential DB round trips just to load the dashboard - so they
// now run concurrently and each only takes the mutex to apply its own (already-fetched) rows into
// the shared breakdown map. Total latency drops from the sum of all six queries to roughly the
// slowest single one.
func (s *Server) analyzerPipelineBreakdown(ctx context.Context) map[string]analyzerPipelineMedia {
breakdown := newAnalyzerPipelineBreakdown()
var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
mediaRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(media_type, '')), COUNT(*), COUNT(*) FILTER (WHERE has_funscript = TRUE)
FROM media
WHERE active = TRUE
GROUP BY LOWER(COALESCE(media_type, ''))`)
if err != nil {
return
}
type mediaTotals struct {
mediaType string
total, funscripts int64
}
results := make([]mediaTotals, 0)
for mediaRows.Next() {
var row mediaTotals
if mediaRows.Scan(&row.mediaType, &row.total, &row.funscripts) == nil {
results = append(results, row)
}
}
mediaRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
if counts, ok := breakdown["discover"][row.mediaType]; ok {
counts["completed"] = row.total
}
breakdown["discover"]["funscript"]["completed"] += row.funscripts
}
}()
// Drives the "discover" bucket only - the legacy status column tracks the overall discovery
// row, not any one stage, so it's kept separate from the per-stage queries below.
wg.Add(1)
go func() {
defer wg.Done()
jobRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, '')), COUNT(*)
FROM media_worker_jobs
GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, ''))`)
if err != nil {
return
}
type jobTotals struct {
mediaType, status string
total int64
}
results := make([]jobTotals, 0)
for jobRows.Next() {
var row jobTotals
if jobRows.Scan(&row.mediaType, &row.status, &row.total) == nil {
results = append(results, row)
}
}
jobRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
discoverCounts, ok := breakdown["discover"][row.mediaType]
if !ok {
continue
}
switch row.status {
case "queued":
discoverCounts["queued"] += row.total
case "error", "failed":
discoverCounts["errors"] += row.total
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
metadataRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(metadata_status, '')), COUNT(*)
FROM media_worker_jobs
GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(metadata_status, ''))`)
if err != nil {
return
}
type metadataTotals struct {
mediaType, status string
total int64
}
results := make([]metadataTotals, 0)
for metadataRows.Next() {
var row metadataTotals
if metadataRows.Scan(&row.mediaType, &row.status, &row.total) == nil {
results = append(results, row)
}
}
metadataRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
counts, ok := breakdown["extract"][row.mediaType]
if !ok {
continue
}
switch row.status {
case "queued":
counts["queued"] += row.total
case "completed":
counts["completed"] += row.total
case "error":
counts["errors"] += row.total
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
funscriptRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(status, '')), COUNT(*)
FROM media_worker_jobs
WHERE has_funscript = TRUE
GROUP BY LOWER(COALESCE(status, ''))`)
if err != nil {
return
}
type funscriptTotals struct {
status string
total int64
}
results := make([]funscriptTotals, 0)
for funscriptRows.Next() {
var row funscriptTotals
if funscriptRows.Scan(&row.status, &row.total) == nil {
results = append(results, row)
}
}
funscriptRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
counts := breakdown["extract"]["funscript"]
switch row.status {
case "queued":
counts["queued"] += row.total
breakdown["discover"]["funscript"]["queued"] += row.total
case "done", "completed":
counts["completed"] += row.total
case "error", "failed":
counts["errors"] += row.total
breakdown["discover"]["funscript"]["errors"] += row.total
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
thumbnailRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(m.media_type, '')),
COUNT(*) FILTER (WHERE t.id IS NULL AND COALESCE(j.thumbnail_status, 'queued') <> 'error'),
COUNT(*) FILTER (WHERE t.id IS NOT NULL),
COUNT(*) FILTER (WHERE t.id IS NULL AND j.thumbnail_status = 'error')
FROM media m
LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
LEFT JOIN media_worker_jobs j ON j.file_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.active = TRUE
GROUP BY LOWER(COALESCE(m.media_type, ''))`)
if err != nil {
return
}
type thumbnailTotals struct {
mediaType string
missing, generated, errored int64
}
results := make([]thumbnailTotals, 0)
for thumbnailRows.Next() {
var row thumbnailTotals
if thumbnailRows.Scan(&row.mediaType, &row.missing, &row.generated, &row.errored) == nil {
results = append(results, row)
}
}
thumbnailRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
if counts, ok := breakdown["generate"][row.mediaType]; ok {
counts["queued"] = row.missing
counts["completed"] = row.generated
counts["errors"] = row.errored
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
analysisRows, err := s.db.Query(ctx, `
SELECT LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, '')), COUNT(*)
FROM media_analysis_tasks
GROUP BY LOWER(COALESCE(media_type, '')), LOWER(COALESCE(status, ''))`)
if err != nil {
return
}
type analysisTotals struct {
mediaType, status string
total int64
}
results := make([]analysisTotals, 0)
for analysisRows.Next() {
var row analysisTotals
if analysisRows.Scan(&row.mediaType, &row.status, &row.total) == nil {
results = append(results, row)
}
}
analysisRows.Close()
mu.Lock()
defer mu.Unlock()
for _, row := range results {
counts, ok := breakdown["analyze"][row.mediaType]
if !ok {
continue
}
switch row.status {
case "queued":
counts["queued"] += row.total
case "processing":
counts["processing"] += row.total
case "completed":
counts["completed"] += row.total
case "error":
counts["errors"] += row.total
}
}
}()
wg.Wait()
s.scanMu.Lock()
scanning, scanType := s.scan.Running, s.scan.CurrentType
s.scanMu.Unlock()
if scanning {
for _, stage := range []string{"discover", "extract"} {
if counts, ok := breakdown[stage][scanType]; ok {
markActive(counts)
}
}
// Sidecar detection runs inline for every file the scan visits, not just videos/audios,
// so the funscript stage counts as active for the whole scan rather than one media type.
markActive(breakdown["extract"]["funscript"])
}
s.thumbnailMu.Lock()
generating, generatingType := s.thumbnail.Running, s.thumbnail.CurrentType
s.thumbnailMu.Unlock()
if generating {
if counts, ok := breakdown["generate"][generatingType]; ok {
markActive(counts)
}
}
s.analysisMu.Lock()
analyzing, analyzingType := s.analysis.Running, s.analysis.CurrentType
s.analysisMu.Unlock()
if analyzing {
if counts, ok := breakdown["analyze"][analyzingType]; ok {
markActive(counts)
}
}
return breakdown
}
// markActive flags a stage/media-type bucket as currently being worked on, moving one unit from
// queued into processing when there's a pending item to attribute the active work to.
func markActive(counts analyzerPipelineCounts) {
counts["active"] = 1
if counts["queued"] > 0 {
counts["queued"]--
}
counts["processing"] = 1
}
// analyzerHistory supports the shared pagination + media type/status filtering the processing
// history card offers everywhere except the per-media-type tabs (which pass a fixed mediaType and
// hide the type filter instead of exposing it). "funscript" isn't a real media_type value - it's
// the has_funscript flag on a video/audio row - so it's translated to that condition instead of an
// equality check, matching how discovery/metadata already treat it. total comes back via a window
// function so listing a page never costs a second round trip for the count.
func (s *Server) analyzerHistory(w http.ResponseWriter, r *http.Request) {
limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 200)
offset := optionalInt(r.URL.Query().Get("offset"), 0, 0, 1_000_000_000)
mediaType := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("mediaType")))
status := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("status")))
conditions := make([]string, 0, 2)
args := make([]any, 0, 4)
switch mediaType {
case "", "all":
case "funscript":
conditions = append(conditions, "has_funscript = TRUE")
default:
args = append(args, mediaType)
conditions = append(conditions, fmt.Sprintf("LOWER(COALESCE(media_type, '')) = $%d", len(args)))
}
switch status {
case "", "all":
case "done":
conditions = append(conditions, "LOWER(COALESCE(status, '')) IN ('done', 'completed')")
case "error":
conditions = append(conditions, "LOWER(COALESCE(status, '')) IN ('error', 'failed')")
default:
args = append(args, status)
conditions = append(conditions, fmt.Sprintf("LOWER(COALESCE(status, '')) = $%d", len(args)))
}
where := "TRUE"
if len(conditions) > 0 {
where = strings.Join(conditions, " AND ")
}
args = append(args, limit, offset)
query := fmt.Sprintf(`
SELECT id, file_path, file_name, media_type, status, progress, queued_at, started_at, finished_at, COALESCE(error_message, ''), has_funscript, COUNT(*) OVER()
FROM media_worker_jobs
WHERE %s
ORDER BY queued_at DESC
LIMIT $%d OFFSET $%d`, where, len(args)-1, len(args))
rows, err := s.db.Query(r.Context(), query, args...)
if err != nil {
writeError(w, http.StatusInternalServerError, "analyzer history unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
var total int64
for rows.Next() {
var id int64
var filePath, fileName, mediaType, status, message string
var progress int
var queued time.Time
var started, finished *time.Time
var hasFunscript bool
if rows.Scan(&id, &filePath, &fileName, &mediaType, &status, &progress, &queued, &started, &finished, &message, &hasFunscript, &total) != nil {
continue
}
items = append(items, map[string]any{"id": id, "file_path": filePath, "file_name": fileName, "media_type": mediaType, "status": status, "progress": progress, "queued_at": queued, "started_at": started, "finished_at": finished, "error": message, "has_funscript": hasFunscript})
}
writeJSON(w, http.StatusOK, map[string]any{"items": items, "history": items, "jobs": items, "total": total, "limit": limit, "offset": offset})
}
func (s *Server) analyzerExtractCount(w http.ResponseWriter, r *http.Request) {
var queued, processing int64
if err := s.db.QueryRow(r.Context(), `
SELECT
COUNT(*) FILTER (WHERE status = 'queued'),
COUNT(*) FILTER (WHERE status = 'processing')
FROM media_worker_jobs`).Scan(&queued, &processing); err != nil {
writeError(w, http.StatusInternalServerError, "queue count unavailable")
return
}
var images, videos, audios, funscripts int64
if err := s.db.QueryRow(r.Context(), `
SELECT
COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'image'),
COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'video'),
COUNT(*) FILTER (WHERE LOWER(COALESCE(media_type, '')) = 'audio'),
COUNT(*) FILTER (WHERE has_funscript = TRUE)
FROM media
WHERE active = TRUE`).Scan(&images, &videos, &audios, &funscripts); err != nil {
writeError(w, http.StatusInternalServerError, "media count unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"count": queued + processing,
"queued": queued,
"processing": processing,
"counts": map[string]any{
"image": images,
"video": videos,
"audio": audios,
"funscript": funscripts,
"queued": queued,
},
})
}
type thumbnailCandidate struct {
mediaKey string
filePath string
mediaType string
}
func (s *Server) analyzerGenerateStatus(w http.ResponseWriter, r *http.Request) {
counts, err := s.thumbnailCounts(r.Context())
if err != nil {
writeError(w, http.StatusInternalServerError, "thumbnail status unavailable")
return
}
s.thumbnailMu.Lock()
state := s.thumbnail
s.thumbnailMu.Unlock()
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,
}
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"status": status,
"counts": counts,
})
}
func (s *Server) analyzerGenerateStart(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, false)
s.thumbnailMu.Lock()
if s.thumbnail.Running {
s.thumbnailMu.Unlock()
writeError(w, http.StatusConflict, "thumbnail generation is already running")
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()
go s.generateThumbnails(ctx, selected)
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"})
}
func (s *Server) analyzerGenerateStop(w http.ResponseWriter, r *http.Request) {
s.thumbnailMu.Lock()
cancel := s.thumbnailCancel
running := s.thumbnail.Running
s.thumbnailMu.Unlock()
if !running || cancel == nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
return
}
log.Printf("analyzer: thumbnail generation stop requested")
cancel()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
}
func (s *Server) thumbnailCounts(ctx context.Context) (map[string]int64, error) {
var total, missing, generated int64
err := s.db.QueryRow(ctx, `
SELECT
COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video')),
COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video') AND t.id IS NULL),
COUNT(*) FILTER (WHERE LOWER(COALESCE(m.media_type, '')) IN ('image', 'video') AND t.id IS NOT NULL)
FROM media m
LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.active = TRUE`).Scan(&total, &missing, &generated)
if err != nil {
return nil, err
}
return map[string]int64{"total": total, "missing": missing, "generated": generated}, nil
}
// thumbnailCandidates lists files still missing a thumbnail. selectedTypes restricts the result to
// those media types (empty/nil means every eligible type) - thumbnails only ever exist for images
// and videos, so a selection of just "audio"/"funscript" legitimately yields zero candidates.
func (s *Server) thumbnailCandidates(ctx context.Context, selectedTypes map[string]bool) ([]thumbnailCandidate, error) {
query := `
SELECT m.media_key, COALESCE(NULLIF(m.file_path, ''), m.media_key), LOWER(COALESCE(m.media_type, 'unknown'))
FROM media m
LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.active = TRUE
AND LOWER(COALESCE(m.media_type, '')) IN ('image', 'video')
AND t.id IS NULL`
args := []any{}
if len(selectedTypes) > 0 {
types := mediaTypesList(selectedTypes)
query += ` AND LOWER(COALESCE(m.media_type, '')) = ANY($1)`
args = append(args, types)
}
query += ` ORDER BY m.id ASC`
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
candidates := make([]thumbnailCandidate, 0)
for rows.Next() {
var candidate thumbnailCandidate
if err := rows.Scan(&candidate.mediaKey, &candidate.filePath, &candidate.mediaType); err != nil {
return nil, err
}
candidates = append(candidates, candidate)
}
if err := rows.Err(); err != nil {
return nil, err
}
return candidates, nil
}
func (s *Server) generateThumbnails(ctx context.Context, selectedTypes map[string]bool) {
candidates, err := s.thumbnailCandidates(ctx, selectedTypes)
if err != nil {
if ctx.Err() != nil {
s.finishThumbnailGeneration(nil)
} else {
s.finishThumbnailGeneration(err)
}
return
}
// Filtered here rather than in the SQL so the pipeline config (which can change between
// runs) is read fresh every time this actually executes, not just at query-build time.
enabled := make([]thumbnailCandidate, 0, len(candidates))
for _, candidate := range candidates {
if s.pipelineStageEnabled(ctx, candidate.mediaType, "thumbnails") {
enabled = append(enabled, candidate)
}
}
s.runThumbnailCandidates(ctx, enabled)
}
// thumbnailCandidatesWithErrors is the same shape as thumbnailCandidates but scoped to one media
// type and only the files whose last attempt actually failed - used by the per-stage retry-errors
// action rather than a full "Run pipeline" pass.
func (s *Server) thumbnailCandidatesWithErrors(ctx context.Context, mediaType string) ([]thumbnailCandidate, error) {
rows, err := s.db.Query(ctx, `
SELECT m.media_key, COALESCE(NULLIF(m.file_path, ''), m.media_key), LOWER(COALESCE(m.media_type, 'unknown'))
FROM media m
JOIN media_worker_jobs j ON j.file_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
LEFT JOIN thumbnails t ON t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.active = TRUE
AND LOWER(COALESCE(m.media_type, '')) = $1
AND t.id IS NULL
AND j.thumbnail_status = 'error'
ORDER BY m.id ASC`, mediaType)
if err != nil {
return nil, err
}
defer rows.Close()
candidates := make([]thumbnailCandidate, 0)
for rows.Next() {
var candidate thumbnailCandidate
if err := rows.Scan(&candidate.mediaKey, &candidate.filePath, &candidate.mediaType); err != nil {
return nil, err
}
candidates = append(candidates, candidate)
}
if err := rows.Err(); err != nil {
return nil, err
}
return candidates, nil
}
func (s *Server) runThumbnailCandidates(ctx context.Context, candidates []thumbnailCandidate) {
log.Printf("analyzer: thumbnail generation started: %d candidates", len(candidates))
s.thumbnailMu.Lock()
s.thumbnail.Total = len(candidates)
s.thumbnailMu.Unlock()
for _, candidate := range candidates {
if ctx.Err() != nil {
s.finishThumbnailGeneration(nil)
return
}
s.thumbnailMu.Lock()
s.thumbnail.Current = candidate.filePath
s.thumbnail.CurrentType = candidate.mediaType
s.thumbnailMu.Unlock()
_, err := s.createThumbnail(ctx, candidate)
if ctx.Err() == nil {
if err != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status='error', thumbnail_error=$2 WHERE file_path=$1`, candidate.filePath, err.Error())
} else {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status='completed', thumbnail_error=NULL WHERE file_path=$1`, candidate.filePath)
}
}
s.thumbnailMu.Lock()
if err != nil {
if ctx.Err() == nil {
s.thumbnail.Failed++
s.thumbnail.LastError = err.Error()
}
} else {
s.thumbnail.Completed++
}
s.thumbnailMu.Unlock()
}
s.finishThumbnailGeneration(nil)
}
func (s *Server) finishThumbnailGeneration(runErr error) {
now := time.Now().UTC()
s.thumbnailMu.Lock()
defer s.thumbnailMu.Unlock()
s.thumbnail.Running = false
s.thumbnailCancel = nil
s.thumbnail.Current = ""
s.thumbnail.CurrentType = ""
s.thumbnail.FinishedAt = &now
if runErr != nil {
s.thumbnail.State = "error"
s.thumbnail.LastError = runErr.Error()
} else if s.thumbnail.Completed+s.thumbnail.Failed < s.thumbnail.Total {
s.thumbnail.State = "stopped"
} else if s.thumbnail.Failed > 0 {
s.thumbnail.State = "completed_with_errors"
} else {
s.thumbnail.State = "completed"
s.thumbnail.LastError = ""
}
log.Printf("analyzer: thumbnail generation finished: %d/%d done, %d failed, state=%s", s.thumbnail.Completed, s.thumbnail.Total, s.thumbnail.Failed, s.thumbnail.State)
if s.thumbnail.LastError != "" {
log.Printf("analyzer: thumbnail generation last error: %s", s.thumbnail.LastError)
}
}
func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandidate) (string, error) {
sourcePath := filepath.ToSlash(candidate.filePath)
if !supportedMediaPath(sourcePath) {
return "", fmt.Errorf("unsupported media type for %s", sourcePath)
}
sourceScratch, cleanupSource, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", fmt.Errorf("fetch %s: %w", sourcePath, err)
}
defer cleanupSource()
thumbnailID, err := newThumbnailID()
if err != nil {
return "", err
}
temporary, err := os.CreateTemp("", ".thumbnail-*.jpg")
if err != nil {
return "", fmt.Errorf("create thumbnail temporary file: %w", err)
}
temporaryPath := temporary.Name()
if err := temporary.Close(); err != nil {
_ = os.Remove(temporaryPath)
return "", err
}
defer os.Remove(temporaryPath)
args := []string{"-hide_banner", "-loglevel", "error", "-y"}
if candidate.mediaType == "video" {
args = append(args, "-ss", "0")
}
args = append(args, "-i", sourceScratch)
args = append(args, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath)
fileContext, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
command := exec.CommandContext(fileContext, s.cfg.FFmpeg, args...)
var stderr bytes.Buffer
command.Stderr = &stderr
if err := command.Run(); err != nil {
detail := strings.TrimSpace(stderr.String())
if len(detail) > 300 {
detail = detail[len(detail)-300:]
}
if detail != "" {
return "", fmt.Errorf("ffmpeg: %s", detail)
}
return "", err
}
info, err := os.Stat(temporaryPath)
if err != nil || info.Size() == 0 {
return "", fmt.Errorf("ffmpeg produced no thumbnail")
}
size, err := s.servantPushThumbnail(ctx, thumbnailID, temporaryPath)
if err != nil {
return "", fmt.Errorf("store thumbnail: %w", err)
}
insertTag, err := s.db.Exec(ctx, `
INSERT INTO thumbnails (id, source_path, file_size_bytes)
VALUES ($1, $2, $3)
ON CONFLICT (source_path) DO NOTHING`, thumbnailID, sourcePath, size)
if err != nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
return "", fmt.Errorf("save thumbnail record: %w", err)
}
if insertTag.RowsAffected() == 0 {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
return "", nil
}
return thumbnailID, nil
}
func newThumbnailID() (string, error) {
var value [16]byte
if _, err := rand.Read(value[:]); err != nil {
return "", err
}
value[6] = (value[6] & 0x0f) | 0x40
value[8] = (value[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", value[0:4], value[4:6], value[6:8], value[8:10], value[10:16]), nil
}
func (s *Server) analyzerEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
_, _ = fmt.Fprintf(w, "event: status\ndata: %s\n\n", string(mustJSON(map[string]any{"ok": true})))
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
}
func (s *Server) analyzerThumb(w http.ResponseWriter, r *http.Request) {
id := strings.TrimSpace(r.URL.Query().Get("id"))
if !safeRelative(id) || len(id) > 100 {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
return
}
s.proxyServant(w, r, "/thumbnails/"+id+".jpg")
}
func (s *Server) analyzerAction(w http.ResponseWriter, r *http.Request, action string) {
if action == "extract/pause" {
log.Printf("analyzer: extraction paused")
_ = s.saveSetting(r.Context(), "analyzer_paused", "true")
}
if action == "extract/resume" {
log.Printf("analyzer: extraction resumed")
_ = s.saveSetting(r.Context(), "analyzer_paused", "false")
}
if action == "extract/stop" {
log.Printf("analyzer: extraction stop requested (cancelling queued/processing jobs)")
_, _ = s.db.Exec(r.Context(), `UPDATE media_worker_jobs SET status='cancelled', finished_at=NOW() WHERE status IN ('queued','processing')`)
}
if strings.HasSuffix(action, "start") || action == "reprocess-all/start" {
// Same Running-set-before-dispatch ordering as analyzerDiscover, and for the same reason:
// setting it inside scanMediaFiles itself left a window where this response (and the
// client's own immediate status poll right after) could land before the goroutine got
// scheduled, reading back "idle" for an action that had, in fact, just started.
now := time.Now().UTC()
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
writeError(w, http.StatusConflict, "a discovery or metadata run is already active")
return
}
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
s.scanMu.Unlock()
go s.scanMediaFiles(nil)
}
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": action, "started": true})
}
// parseMediaTypesPayload decodes {"types": [...]} the same way for every analyzer action that can
// be scoped to a subset of media types. An empty/missing list (including the plain no-body POST
// every existing caller already sends), an "all" entry, or a list that resolves to nothing all
// mean "no filter" - callers treat an empty map as "everything", matching the pre-existing
// discover behavior. mapFunscriptToVideo controls what a "funscript" entry resolves to: discovery
// and metadata refresh walk/probe video files and check each one for its sidecar, so it maps to
// "video" there; thumbnails and AI analysis have no such indirection, so it's kept literal there
// (a funscript-only selection for those correctly yields no candidates).
func parseMediaTypesPayload(r *http.Request, mapFunscriptToVideo bool) map[string]bool {
var payload struct {
Types []string `json:"types"`
}
_ = decodeRequestJSON(r, &payload)
return normalizeMediaTypes(payload.Types, mapFunscriptToVideo)
}
// normalizeMediaTypes is parseMediaTypesPayload's actual logic, split out so a schedule's stored
// settings (already decoded from JSONB, not sitting in a live *http.Request body) can go through
// the exact same rules a live discover/metadata/generate/analyze request would.
func normalizeMediaTypes(raw []string, mapFunscriptToVideo bool) map[string]bool {
selected := map[string]bool{}
for _, item := range raw {
switch strings.ToLower(strings.TrimSpace(item)) {
case "image", "video", "audio":
selected[strings.ToLower(strings.TrimSpace(item))] = true
case "funscript":
if mapFunscriptToVideo {
selected["video"] = true
} else {
selected["funscript"] = true
}
case "all":
return map[string]bool{}
}
}
return selected
}
func mediaTypesList(selected map[string]bool) []string {
return analyzerSelectionList(selected, analyzerMediaTypeOrder)
}
// analyzerTypesLabel renders a media-type selection for a log line - "all" for an empty selection
// (no filter) rather than the empty-list "[]" mediaTypesList would otherwise print.
func analyzerTypesLabel(selected map[string]bool) string {
if len(selected) == 0 {
return "all"
}
return strings.Join(mediaTypesList(selected), ",")
}
func analyzerSelectionList(selected map[string]bool, order []string) []string {
values := make([]string, 0, len(selected))
for _, value := range order {
if selected[value] {
values = append(values, value)
}
}
return values
}
// analyzerDiscover kicks off a scan, optionally restricted to a subset of media types. An empty
// or missing "types" list (including the plain no-body POST every existing caller already sends)
// means "discover everything", matching the previous unconditional behavior.
//
// The Running flag is set here, synchronously, before the goroutine is even dispatched - not
// inside scanMediaFiles itself. thumbnails/analysis already worked this way (see
// analyzerGenerateStart/analyzerAnalyzeStart); this one didn't, which left a real window where the
// HTTP response had already gone out (so the client's own immediate status poll could land) before
// the goroutine got scheduled and flipped s.scan.Running - long enough, especially with the
// paused-setting DB lookup that used to run first inside scanMediaFiles, for "Start discover" to
// read back "idle" right after starting.
func (s *Server) analyzerDiscover(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, true)
now := time.Now().UTC()
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
writeError(w, http.StatusConflict, "a discovery or metadata run is already active")
return
}
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
s.scanMu.Unlock()
go s.scanMediaFiles(selected)
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "extract/discover", "started": true})
}
// analyzerMetadataStart refreshes ffprobe metadata (and the funscript sidecar flag) for every
// already-known active media row matching the selected types, without walking the filesystem for
// brand-new files the way discovery does. It shares discovery's scan slot/state since both are the
// same kind of synchronous per-file walk and can't sensibly run at the same time. Running is set
// here for the same reason as analyzerDiscover above - before the goroutine starts, not inside it.
func (s *Server) analyzerMetadataStart(w http.ResponseWriter, r *http.Request) {
selected := parseMediaTypesPayload(r, true)
now := time.Now().UTC()
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
writeError(w, http.StatusConflict, "a discovery or metadata run is already active")
return
}
s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now}
s.scanMu.Unlock()
go s.refreshMetadataForTypes(selected)
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "metadata/start", "started": true})
}
// analyzerCleanupStart removes active media rows (and their worker-job, thumbnail, and AI-analysis
// records) whose underlying file no longer resolves under any configured media root - the actual
// "stale entry" work discovery/metadata never do, since a filesystem walk only ever visits files
// that still exist and so can never notice one that's been deleted. Shares discovery's scan slot
// for the same reason analyzerMetadataStart does: both are a synchronous per-file walk.
func (s *Server) analyzerCleanupStart(w http.ResponseWriter, r *http.Request) {
now := time.Now().UTC()
s.scanMu.Lock()
if s.scan.Running {
s.scanMu.Unlock()
writeError(w, http.StatusConflict, "a discovery or metadata run is already active")
return
}
s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now}
s.scanMu.Unlock()
go s.cleanupStaleMedia()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "action": "cleanup/start", "started": true})
}
// analyzerScanStop cancels whichever scan-based run (discover/metadata/cleanup) is currently
// active - they share one scan slot/cancel func since only one can ever run at a time (see
// analyzerDiscover/analyzerMetadataStart/analyzerCleanupStart). Mirrors analyzerGenerateStop and
// analyzerAnalyzeStop's cancel-func pattern.
func (s *Server) analyzerScanStop(w http.ResponseWriter, r *http.Request) {
s.scanMu.Lock()
cancel := s.scanCancel
running := s.scan.Running
s.scanMu.Unlock()
if !running || cancel == nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
return
}
log.Printf("analyzer: scan stop requested")
cancel()
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
}
// cleanupStaleMedia does the actual sweep. s.scan is already set to Running by the caller
// (analyzerCleanupStart) before this goroutine was even dispatched - this only clears it when done.
func (s *Server) cleanupStaleMedia() {
log.Printf("analyzer: cleanup sweep started")
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
s.scanMu.Lock()
s.scanCancel = cancel
s.scanMu.Unlock()
removed := 0
var runErr error
defer func() {
s.scanMu.Lock()
checked := s.scan.FilesIndexed
lastError := ""
if runErr != nil {
lastError = runErr.Error()
}
s.scan = scanState{LastError: lastError}
s.scanCancel = nil
s.scanMu.Unlock()
log.Printf("analyzer: cleanup sweep finished: %d checked, %d marked stale", checked, removed)
}()
rows, err := s.db.Query(ctx, `SELECT media_key, LOWER(COALESCE(media_type, '')), COALESCE(NULLIF(file_path, ''), media_key) FROM media WHERE active = TRUE`)
if err != nil {
log.Printf("analyzer: cleanup sweep: failed to load media rows: %v", err)
runErr = fmt.Errorf("failed to load media rows: %w", err)
return
}
type mediaItem struct{ key, mediaType, filePath string }
items := make([]mediaItem, 0)
for rows.Next() {
var item mediaItem
if rows.Scan(&item.key, &item.mediaType, &item.filePath) == nil {
items = append(items, item)
}
}
rows.Close()
s.scanMu.Lock()
s.scan.Total = int64(len(items))
s.scanMu.Unlock()
for _, item := range items {
if ctx.Err() != nil {
return
}
s.scanMu.Lock()
s.scan.CurrentType = item.mediaType
s.scan.CurrentFile = item.filePath
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists {
continue // file still exists on disk - nothing stale about this one
}
removed++
_, _ = s.db.Exec(ctx, `UPDATE media SET active = FALSE WHERE media_key = $1`, item.key)
var thumbnailID string
if s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, item.filePath).Scan(&thumbnailID) == nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_, _ = s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = $1`, thumbnailID)
}
_, _ = s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE file_path = $1`, item.filePath)
_, _ = s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE media_key = $1`, item.key)
}
}
// scanMediaFiles does the actual walk. s.scan is already set to Running by the caller
// (analyzerDiscover) before this goroutine was even dispatched - this only clears it when done.
func (s *Server) scanMediaFiles(selectedTypes map[string]bool) {
log.Printf("analyzer: discovery scan started (types=%s)", analyzerTypesLabel(selectedTypes))
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
s.scanMu.Lock()
s.scanCancel = cancel
s.scanMu.Unlock()
var runErr error
defer func() {
s.scanMu.Lock()
indexed := s.scan.FilesIndexed
lastError := ""
if runErr != nil {
lastError = runErr.Error()
}
s.scan = scanState{LastError: lastError}
s.scanCancel = nil
s.scanMu.Unlock()
log.Printf("analyzer: discovery scan finished: %d files indexed", indexed)
}()
batch := time.Now().UTC().Format("20060102T150405.000000000Z")
files, err := s.servantListFiles(ctx, "", false, 0)
if err != nil {
log.Printf("analyzer: discovery scan: failed to list files: %v", err)
runErr = fmt.Errorf("could not reach Porter to list files: %w", err)
return
}
// Porter reachable but reporting an empty library is otherwise indistinguishable from
// a successful no-op run - every existing file re-indexes (and increments FilesIndexed) on
// every scan, so a real library can never legitimately finish at zero. Flag it instead of
// letting "discovery started" silently revert to idle with nothing to show for it.
if len(files) == 0 {
log.Printf("analyzer: discovery scan: Porter reported zero files")
runErr = fmt.Errorf("Porter reported no files under its configured media root(s) - check the Mounts settings in MediaConfig")
return
}
for _, file := range files {
if ctx.Err() != nil {
return
}
if !supportedMediaPath(file.Rel) {
continue
}
if len(selectedTypes) > 0 && !selectedTypes[inferMediaType(file.Rel)] {
continue
}
s.indexMediaFile(ctx, file.Rel, file.Size, time.UnixMilli(file.Mtime).UTC(), batch)
}
}
func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, modified time.Time, batch string) {
if !safeRelative(key) {
return
}
key = filepath.ToSlash(key)
mediaType := inferMediaType(key)
s.scanMu.Lock()
s.scan.CurrentType = mediaType
s.scan.CurrentFile = key
s.scan.FilesIndexed++
s.scanMu.Unlock()
// ffprobe reads images too (just dimensions, no duration), so metadata extraction now
// covers every type - previously images silently never got width/height populated at all.
metadataAttempted := (mediaType == "video" || mediaType == "audio" || mediaType == "image") && s.pipelineStageEnabled(ctx, mediaType, "metadata")
var duration any
var width, height int
var probeErr error
var hasFunscript bool
// Servant has the storage mounted and can probe/stat locally; every other service goes
// through Servant's HTTP API instead of touching MediaRoots itself (see servant_client.go).
if s.cfg.Service == config.Servant {
fullPath, resolveErr := s.resolveAnyMediaPath(ctx, key)
if metadataAttempted && resolveErr == nil {
var probe map[string]any
probe, probeErr = s.probeWithFFprobe(ctx, fullPath)
if probe != nil {
duration = probe["durationMs"]
width = probeInt(probe, "width")
height = probeInt(probe, "height")
}
}
hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && resolveErr == nil && hasFunscriptSidecar(fullPath)
} else {
if metadataAttempted {
var probe servantProbeResult
probe, probeErr = s.servantProbe(ctx, key)
duration = nullableInt64(probe.DurationMs)
width, height = probe.Width, probe.Height
}
hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && s.funscriptSidecarExists(ctx, key)
}
_, _ = s.db.Exec(ctx, `INSERT INTO media (media_key, media_type, source, file_path, original_filename, size_bytes, duration_ms, width, height, modified_at, has_funscript, active) VALUES ($1,$2,'Filesystem',$3,$4,$5,$6,$7,$8,$9,$10,TRUE) ON CONFLICT (media_key) DO UPDATE SET file_path=EXCLUDED.file_path, original_filename=EXCLUDED.original_filename, size_bytes=EXCLUDED.size_bytes, duration_ms=COALESCE(EXCLUDED.duration_ms, media.duration_ms), width=COALESCE(EXCLUDED.width, media.width), height=COALESCE(EXCLUDED.height, media.height), modified_at=EXCLUDED.modified_at, has_funscript=EXCLUDED.has_funscript, active=TRUE`, key, mediaType, key, filepath.Base(key), size, duration, nullableInt(width), nullableInt(height), modified, hasFunscript)
_, _ = s.db.Exec(ctx, `INSERT INTO media_worker_jobs (media_key, file_path, file_name, media_type, status, progress, file_size_bytes, scan_batch_id, finished_at, has_funscript) VALUES ($1,$2,$3,$4,'done',100,$5,$6,NOW(),$7) ON CONFLICT (file_path) DO UPDATE SET file_name=EXCLUDED.file_name, media_type=EXCLUDED.media_type, file_size_bytes=EXCLUDED.file_size_bytes, scan_batch_id=EXCLUDED.scan_batch_id, has_funscript=EXCLUDED.has_funscript, status=CASE WHEN media_worker_jobs.status IN ('error','failed') THEN 'queued' ELSE media_worker_jobs.status END`, key, key, filepath.Base(key), mediaType, size, batch, hasFunscript)
// Only touch metadata_status/metadata_error when metadata extraction actually ran for this
// file this pass - when the stage is disabled (or unsupported for this media type) the
// previous outcome is left untouched rather than being reset to a misleading value.
if metadataAttempted {
if probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, key, probeErr.Error())
} else {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, key)
}
}
}
// refreshMetadataForTypes re-probes ffprobe metadata (and the funscript sidecar flag) for every
// already-known active media row matching selectedTypes (empty means every type), without walking
// the filesystem for brand-new files - that's discovery's job. It's the standalone "Metadata"
// pipeline action: useful for re-reading dimensions/duration (say, after a codec-aware ffprobe
// upgrade) without re-triggering a full rediscovery walk.
// refreshMetadataForTypes does the actual refresh. s.scan is already set to Running by the caller
// (analyzerMetadataStart) before this goroutine was even dispatched - this only clears it when done.
func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) {
log.Printf("analyzer: metadata refresh started (types=%s)", analyzerTypesLabel(selectedTypes))
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
s.scanMu.Lock()
s.scanCancel = cancel
s.scanMu.Unlock()
var runErr error
defer func() {
s.scanMu.Lock()
indexed := s.scan.FilesIndexed
lastError := ""
if runErr != nil {
lastError = runErr.Error()
}
s.scan = scanState{LastError: lastError}
s.scanCancel = nil
s.scanMu.Unlock()
log.Printf("analyzer: metadata refresh finished: %d files processed", indexed)
}()
query := `SELECT COALESCE(NULLIF(file_path, ''), media_key), LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE`
args := []any{}
if len(selectedTypes) > 0 {
query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)`
args = append(args, mediaTypesList(selectedTypes))
}
rows, err := s.db.Query(ctx, query, args...)
if err != nil {
log.Printf("analyzer: metadata refresh: failed to load media rows: %v", err)
runErr = fmt.Errorf("failed to load media rows: %w", err)
return
}
type mediaItem struct{ filePath, mediaType string }
items := make([]mediaItem, 0)
for rows.Next() {
var item mediaItem
if rows.Scan(&item.filePath, &item.mediaType) == nil {
items = append(items, item)
}
}
rows.Close()
s.scanMu.Lock()
s.scan.Total = int64(len(items))
s.scanMu.Unlock()
for _, item := range items {
if ctx.Err() != nil {
return
}
s.scanMu.Lock()
s.scan.CurrentType = item.mediaType
s.scan.CurrentFile = item.filePath
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists {
continue
}
if s.pipelineStageEnabled(ctx, "funscript", "metadata") {
hasFunscript := s.funscriptSidecarExists(ctx, item.filePath)
_, _ = s.db.Exec(ctx, `UPDATE media SET has_funscript=$2 WHERE file_path=$1`, item.filePath, hasFunscript)
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET has_funscript=$2 WHERE file_path=$1`, item.filePath, hasFunscript)
}
if item.mediaType != "video" && item.mediaType != "audio" && item.mediaType != "image" {
continue
}
if !s.pipelineStageEnabled(ctx, item.mediaType, "metadata") {
continue
}
probe, probeErr := s.servantProbe(ctx, item.filePath)
if probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, item.filePath, probeErr.Error())
continue
}
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`, item.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`, item.filePath)
}
}
func nullableInt(value int) any {
if value <= 0 {
return nil
}
return value
}
func nullableInt64(value int64) any {
if value <= 0 {
return nil
}
return value
}
func hasFunscriptSidecar(filePath string) bool {
base := strings.TrimSuffix(filePath, filepath.Ext(filePath))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
info, err := os.Stat(candidate)
if err == nil && !info.IsDir() {
return true
}
}
return false
}
// funscriptSidecarExists is hasFunscriptSidecar for callers without local filesystem access
// (Lookout) - it checks for the sidecar on Servant instead of statting a local path.
func (s *Server) funscriptSidecarExists(ctx context.Context, key string) bool {
base := strings.TrimSuffix(key, filepath.Ext(key))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(candidate)); err == nil && exists {
return true
}
}
return false
}
func (s *Server) probeWithFFprobe(ctx context.Context, filePath string) (map[string]any, error) {
probeCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
command := exec.CommandContext(probeCtx, s.cfg.FFprobe, "-v", "error", "-show_entries", "format=duration:stream=width,height", "-of", "json", filePath)
var output, stderr bytes.Buffer
command.Stdout = &output
command.Stderr = &stderr
if err := command.Run(); err != nil {
detail := strings.TrimSpace(stderr.String())
if len(detail) > 300 {
detail = detail[len(detail)-300:]
}
if detail != "" {
return nil, fmt.Errorf("ffprobe: %s", detail)
}
return nil, err
}
var payload struct {
Format struct {
Duration string `json:"duration"`
} `json:"format"`
Streams []struct {
Width int `json:"width"`
Height int `json:"height"`
} `json:"streams"`
}
if err := json.Unmarshal(output.Bytes(), &payload); err != nil {
return nil, fmt.Errorf("parse ffprobe output: %w", err)
}
result := map[string]any{}
if duration, err := time.ParseDuration(payload.Format.Duration + "s"); err == nil {
result["durationMs"] = duration.Milliseconds()
}
for _, stream := range payload.Streams {
if stream.Width > 0 || stream.Height > 0 {
result["width"], result["height"] = stream.Width, stream.Height
break
}
}
return result, nil
}
func probeInt(values map[string]any, key string) int {
if value, ok := values[key].(int); ok {
return value
}
return 0
}
func (s *Server) modelConfig(w http.ResponseWriter, r *http.Request) {
value := s.settingValue(r.Context(), "analyzer_model_config", "{}")
var parsed any
if json.Unmarshal([]byte(value), &parsed) != nil {
parsed = map[string]any{}
}
writeJSON(w, http.StatusOK, map[string]any{"config": parsed, "options": analyzerModelOptions()})
}
func (s *Server) saveModelConfig(w http.ResponseWriter, r *http.Request) {
var payload map[string]any
if err := decodeRequestJSON(r, &payload); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if value, ok := payload["config"]; ok {
payload = map[string]any{"config": value}
}
if err := s.saveSetting(r.Context(), "analyzer_model_config", string(mustJSON(payload))); err != nil {
writeError(w, http.StatusInternalServerError, "model configuration could not be saved")
return
}
log.Printf("analyzer: model configuration saved")
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "config": payload})
}
func (s *Server) saveModelOrder(w http.ResponseWriter, r *http.Request) {
var payload map[string]any
if err := decodeRequestJSON(r, &payload); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if err := s.saveSetting(r.Context(), "analyzer_category_order", string(mustJSON(payload))); err != nil {
writeError(w, http.StatusInternalServerError, "model order could not be saved")
return
}
log.Printf("analyzer: model category order saved")
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
type pipelineStageConfig struct {
Thumbnails bool `json:"thumbnails"`
Metadata bool `json:"metadata"`
}
// Every media type defaults to fully enabled so existing installs (which predate this setting
// entirely) keep behaving exactly as they did before it existed. Thumbnails are only ever
// generated for images and videos (see thumbnailCandidates), so audio and funscript default to
// disabled there rather than advertising a toggle that can't do anything.
func defaultPipelineConfig() map[string]pipelineStageConfig {
return map[string]pipelineStageConfig{
"image": {Thumbnails: true, Metadata: true},
"video": {Thumbnails: true, Metadata: true},
"audio": {Thumbnails: false, Metadata: true},
"funscript": {Thumbnails: false, Metadata: true},
}
}
func loadPipelineConfig(value string) map[string]pipelineStageConfig {
config := defaultPipelineConfig()
if value == "" {
return config
}
var stored map[string]pipelineStageConfig
if json.Unmarshal([]byte(value), &stored) != nil {
return config
}
for mediaType, stage := range stored {
if _, ok := config[mediaType]; ok {
config[mediaType] = stage
}
}
return config
}
func (s *Server) pipelineConfig(w http.ResponseWriter, r *http.Request) {
config := loadPipelineConfig(s.settingValue(r.Context(), "analyzer_pipeline_config", ""))
writeJSON(w, http.StatusOK, map[string]any{"config": config})
}
func (s *Server) savePipelineConfig(w http.ResponseWriter, r *http.Request) {
var payload map[string]any
if err := decodeRequestJSON(r, &payload); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
raw := payload["config"]
if raw == nil {
raw = payload
}
encoded, err := json.Marshal(raw)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid pipeline configuration")
return
}
var partial map[string]pipelineStageConfig
if json.Unmarshal(encoded, &partial) != nil {
writeError(w, http.StatusBadRequest, "invalid pipeline configuration")
return
}
// Merges onto whatever's already stored (not just today's request) so saving one media
// type's tab - which only ever sends that one type's section - can never clobber the
// other three types' settings back to their defaults.
config := loadPipelineConfig(s.settingValue(r.Context(), "analyzer_pipeline_config", ""))
for mediaType, stage := range partial {
if _, ok := config[mediaType]; ok {
config[mediaType] = stage
}
}
if err := s.saveSetting(r.Context(), "analyzer_pipeline_config", string(mustJSON(config))); err != nil {
writeError(w, http.StatusInternalServerError, "pipeline configuration could not be saved")
return
}
log.Printf("analyzer: pipeline configuration saved")
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "config": config})
}
// clearMediaTypePipeline resets one media type's processed state so the next discover/generate
// run redoes it from scratch - it doesn't kick off that run itself, mirroring how "clear" and
// "reprocess" are two separate stages the frontend chains together (clear, then the same
// discover+generate calls the existing "Run pipeline" button already uses).
func (s *Server) clearMediaTypePipeline(w http.ResponseWriter, r *http.Request) {
mediaType := strings.ToLower(chi.URLParam(r, "mediaType"))
if !map[string]bool{"image": true, "video": true, "audio": true, "funscript": true}[mediaType] {
writeError(w, http.StatusBadRequest, "unknown media type")
return
}
types := map[string]bool{mediaType: true}
stages := map[string]bool{"metadata": true, "thumbnails": true, "analyze": true}
if err := s.startDatabaseClear(clearStageTotal(types, stages)); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
log.Printf("analyzer: database clear started (mediaType=%s, clear & reprocess)", mediaType)
clearCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
err := s.clearPipelineData(clearCtx, types, stages)
if err == nil {
// The per-type endpoint is the legacy "clear & reprocess" flow. Keep its historical
// behavior of putting the discovery job back into the queue before the follow-up scan;
// the dashboard endpoint intentionally leaves this discovery status untouched when only
// metadata, thumbnails, or analysis was selected.
_, err = s.db.Exec(clearCtx, `UPDATE media_worker_jobs SET status = 'queued', progress = 0, finished_at = NULL, error_message = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType)
if err != nil {
err = fmt.Errorf("reset %s worker status: %w", mediaType, err)
}
}
s.finishDatabaseClear(err)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType})
}
// deleteThumbnailsForType removes both the thumbnail files on disk and their DB rows for every
// media row of one type - shared by the per-type "Clear & reprocess" button above and the
// dashboard's stage-scoped "Clear database" button below, so there's one place that knows how a
// thumbnail actually gets deleted.
func (s *Server) deleteThumbnailsForType(ctx context.Context, mediaType string) error {
rows, err := s.db.Query(ctx, `
SELECT DISTINCT t.id
FROM thumbnails t
JOIN media m ON t.media_id = m.id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE LOWER(COALESCE(m.media_type, '')) = $1`, mediaType)
if err != nil {
return fmt.Errorf("list %s thumbnails: %w", mediaType, err)
}
ids := make([]string, 0)
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
rows.Close()
return fmt.Errorf("scan %s thumbnail: %w", mediaType, err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
rows.Close()
return fmt.Errorf("read %s thumbnails: %w", mediaType, err)
}
rows.Close()
for _, id := range ids {
_ = s.servantDeleteThumbnail(ctx, id)
}
if len(ids) > 0 {
if _, err := s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = ANY($1::uuid[])`, ids); err != nil {
return fmt.Errorf("delete %s thumbnail records: %w", mediaType, err)
}
}
return nil
}
// clearFunscriptFlag resets the has_funscript sidecar flag - funscripts aren't their own media
// rows, so clearing them only touches that flag, leaving the parent video/audio file's own
// metadata and thumbnail untouched.
func (s *Server) clearFunscriptFlag(ctx context.Context) error {
if _, err := s.db.Exec(ctx, `UPDATE media SET has_funscript = FALSE WHERE has_funscript = TRUE`); err != nil {
return fmt.Errorf("clear funscript media flags: %w", err)
}
if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET has_funscript = FALSE, status = 'queued', progress = 0, finished_at = NULL, error_message = NULL WHERE has_funscript = TRUE`); err != nil {
return fmt.Errorf("clear funscript job flags: %w", err)
}
return nil
}
// clearPipelineSelection is the dashboard's "Clear database" action: unlike clearMediaTypePipeline
// (which always clears everything for one type), this clears exactly the selected stages for
// exactly the selected media types - e.g. "reset only thumbnails for images and videos" without
// touching their metadata or AI analysis results. Clearing "discover" is the most destructive
// option: since every other stage's data hangs off the media row itself, forgetting discovery means
// deleting that row entirely (thumbnails, worker job, analysis tasks included) - the file is
// picked back up fresh on the next discovery run.
func (s *Server) clearPipelineSelection(w http.ResponseWriter, r *http.Request) {
var payload struct {
Types []string `json:"types"`
Stages []string `json:"stages"`
}
if err := decodeRequestJSON(r, &payload); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
types := normalizeMediaTypes(payload.Types, false)
if len(types) == 0 {
types = map[string]bool{"image": true, "video": true, "audio": true, "funscript": true}
}
stages := map[string]bool{}
for _, raw := range payload.Stages {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "discover", "metadata", "thumbnails", "analyze":
stages[strings.ToLower(strings.TrimSpace(raw))] = true
}
}
if len(stages) == 0 {
writeError(w, http.StatusBadRequest, "select at least one stage to clear")
return
}
if err := s.startDatabaseClear(clearStageTotal(types, stages)); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
log.Printf("analyzer: database clear started (types=%s, stages=%s)", analyzerTypesLabel(types), strings.Join(analyzerSelectionList(stages, []string{"discover", "metadata", "thumbnails", "analyze"}), ","))
clearCtx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
err := s.clearPipelineData(clearCtx, types, stages)
s.finishDatabaseClear(err)
if err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "types": mediaTypesList(types), "stages": analyzerSelectionList(stages, []string{"discover", "metadata", "thumbnails", "analyze"}),
"progress": map[string]any{"total": clearStageTotal(types, stages), "completed": clearStageTotal(types, stages)},
})
}
var analyzerMediaTypeOrder = []string{"image", "video", "audio", "funscript"}
// clearStageTotal counts the concrete reset operations represented in the live status progress
// bar. Discovery subsumes all other resets for a media type because removing its row removes all
// derived pipeline data with it. Funscript is a sidecar flag rather than a standalone media row,
// and therefore only has meaningful discover/metadata work.
func clearStageTotal(types map[string]bool, stages map[string]bool) int {
total := 0
for _, mediaType := range analyzerMediaTypeOrder {
if !types[mediaType] {
continue
}
if stages["discover"] {
total++
continue
}
if mediaType == "funscript" {
if stages["metadata"] {
total++
}
continue
}
for _, stage := range []string{"metadata", "thumbnails", "analyze"} {
if stages[stage] {
total++
}
}
}
return total
}
func (s *Server) startDatabaseClear(total int) error {
s.clearMu.Lock()
defer s.clearMu.Unlock()
if s.clear.Running {
return fmt.Errorf("a database clear is already running")
}
s.scanMu.Lock()
scanning := s.scan.Running
s.scanMu.Unlock()
s.thumbnailMu.Lock()
generating := s.thumbnail.Running
s.thumbnailMu.Unlock()
s.analysisMu.Lock()
analyzing := s.analysis.Running
s.analysisMu.Unlock()
if scanning || generating || analyzing {
return fmt.Errorf("analyzer work is already running")
}
now := time.Now().UTC()
s.clear = databaseClearState{Running: true, State: "clearing", Total: total, StartedAt: &now}
return nil
}
func (s *Server) setDatabaseClearCurrent(mediaType, stage string) {
s.clearMu.Lock()
s.clear.CurrentType = mediaType
s.clear.Current = fmt.Sprintf("%s (%s)", stage, mediaType)
s.clearMu.Unlock()
}
func (s *Server) completeDatabaseClearStage() {
s.clearMu.Lock()
s.clear.Completed++
s.clearMu.Unlock()
}
func (s *Server) finishDatabaseClear(clearErr error) {
now := time.Now().UTC()
s.clearMu.Lock()
defer s.clearMu.Unlock()
s.clear.Running = false
s.clear.Current = ""
s.clear.CurrentType = ""
s.clear.FinishedAt = &now
if clearErr != nil {
s.clear.Failed++
s.clear.State = "error"
s.clear.LastError = clearErr.Error()
log.Printf("analyzer: database clear failed: %v", clearErr)
} else {
s.clear.State = "completed"
s.clear.LastError = ""
log.Printf("analyzer: database clear finished: %d/%d stages completed", s.clear.Completed, s.clear.Total)
}
}
func (s *Server) clearPipelineStage(mediaType, stage string, action func() error) error {
s.setDatabaseClearCurrent(mediaType, stage)
if err := action(); err != nil {
return err
}
s.completeDatabaseClearStage()
return nil
}
// clearPipelineData performs the durable reset for the selected media types and stages. Every
// database operation is checked so a failed statement cannot be reported to the UI as a
// successful clear, and each logical stage updates the live status progress state.
func (s *Server) clearPipelineData(ctx context.Context, types map[string]bool, stages map[string]bool) error {
for _, mediaType := range analyzerMediaTypeOrder {
if !types[mediaType] {
continue
}
if stages["discover"] {
err := s.clearPipelineStage(mediaType, "discover", func() error {
if err := s.deleteThumbnailsForType(ctx, mediaType); err != nil {
return err
}
if mediaType == "funscript" {
return s.clearFunscriptFlag(ctx)
}
if err := s.deleteMediaArtifactsForType(ctx, mediaType); err != nil {
return err
}
if _, err := s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("delete %s analysis tasks: %w", mediaType, err)
}
if _, err := s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("delete %s worker jobs: %w", mediaType, err)
}
if _, err := s.db.Exec(ctx, `DELETE FROM media WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("delete %s media rows: %w", mediaType, err)
}
return nil
})
if err != nil {
return fmt.Errorf("clear %s discovery: %w", mediaType, err)
}
continue
}
if mediaType == "funscript" {
if stages["metadata"] {
if err := s.clearPipelineStage(mediaType, "metadata", func() error { return s.clearFunscriptFlag(ctx) }); err != nil {
return fmt.Errorf("clear funscript metadata: %w", err)
}
}
continue
}
if stages["metadata"] {
err := s.clearPipelineStage(mediaType, "metadata", func() error {
if _, err := s.db.Exec(ctx, `UPDATE media SET duration_ms = NULL, width = NULL, height = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("clear %s metadata: %w", mediaType, err)
}
if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status = 'queued', metadata_error = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("reset %s metadata status: %w", mediaType, err)
}
return nil
})
if err != nil {
return err
}
}
if stages["thumbnails"] {
err := s.clearPipelineStage(mediaType, "thumbnails", func() error {
if err := s.deleteThumbnailsForType(ctx, mediaType); err != nil {
return err
}
if _, err := s.db.Exec(ctx, `UPDATE media_worker_jobs SET thumbnail_status = 'queued', thumbnail_error = NULL WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("reset %s thumbnail status: %w", mediaType, err)
}
return nil
})
if err != nil {
return err
}
}
if stages["analyze"] {
err := s.clearPipelineStage(mediaType, "analyze", func() error {
if _, err := s.db.Exec(ctx, `DELETE FROM media_analysis_tasks WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("delete %s analysis tasks: %w", mediaType, err)
}
if _, err := s.db.Exec(ctx, `DELETE FROM media_tags WHERE user_id IS NULL AND media_key IN (SELECT media_key FROM media WHERE LOWER(COALESCE(media_type, '')) = $1)`, mediaType); err != nil {
return fmt.Errorf("delete %s AI tags: %w", mediaType, err)
}
if _, err := s.db.Exec(ctx, `UPDATE media SET metadata = metadata - ARRAY['age', 'gender', 'nsfwLabel', 'nsfwScore', 'quality']::text[] WHERE LOWER(COALESCE(media_type, '')) = $1`, mediaType); err != nil {
return fmt.Errorf("clear %s AI metadata: %w", mediaType, err)
}
return nil
})
if err != nil {
return err
}
}
}
return nil
}
// Deleting a discovery row must also remove records keyed only by media_key. Several legacy
// tables allow media_id to be NULL, so relying on foreign-key cascades alone leaves orphaned
// tags/history behind after a clear.
func (s *Server) deleteMediaArtifactsForType(ctx context.Context, mediaType string) error {
for _, table := range []string{"media_tag_votes", "media_tags", "media_stats", "media_view_sessions", "media_metrics", "playlist_items"} {
query := fmt.Sprintf(`DELETE FROM %s WHERE media_key IN (SELECT media_key FROM media WHERE LOWER(COALESCE(media_type, '')) = $1)`, table)
if _, err := s.db.Exec(ctx, query, mediaType); err != nil {
return fmt.Errorf("delete %s records: %w", table, err)
}
}
return nil
}
// Read fresh on every scan/generation run (rather than cached) so a save takes effect on the
// very next run without requiring a server restart.
func (s *Server) pipelineStageEnabled(ctx context.Context, mediaType, stage string) bool {
config := loadPipelineConfig(s.settingValue(ctx, "analyzer_pipeline_config", ""))
section, ok := config[mediaType]
if !ok {
return true
}
switch stage {
case "thumbnails":
return section.Thumbnails
case "metadata":
return section.Metadata
default:
return true
}
}
// analyzerScheduleTools are the only actions runAnalyzerScheduledRun (see analyzer_schedule.go)
// knows how to execute - one per real pipeline stage, matching the dashboard's own action list.
var analyzerScheduleTools = map[string]bool{
"discover": true,
"metadata": true,
"thumbnails": true,
"analyze": true,
"cleanup": true,
}
func (s *Server) analyzerSchedules(w http.ResponseWriter, r *http.Request) {
s.workflowSchedules(w, r)
}
// createAnalyzerSchedule validates the tool against the five real analyzer actions before
// delegating to the shared workflow_schedules insert - createWorkflowSchedule accepts any tool
// string as-is (it's also used by the Tools app for converter/downloader/generator schedules), so
// this is what stops an analyzer schedule from being created for an action nothing can ever run.
func (s *Server) createAnalyzerSchedule(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
var probe struct {
Tool string `json:"tool"`
}
_ = json.Unmarshal(body, &probe)
if !analyzerScheduleTools[strings.ToLower(strings.TrimSpace(probe.Tool))] {
writeError(w, http.StatusBadRequest, "unsupported schedule action")
return
}
log.Printf("analyzer: automation schedule created (tool=%s)", probe.Tool)
r.Body = io.NopCloser(bytes.NewReader(body))
s.createWorkflowSchedule(w, r)
}
// runAnalyzerSchedule is the manual "Run now" trigger, dispatching through the exact same
// scan/thumbnail/analysis busy-state guards the dashboard buttons use (see
// startAnalyzerScheduledRun) rather than the generic converter/downloader/generator job queue
// runWorkflowSchedule uses - that queue's executeWorkflow has no case for any analyzer action.
func (s *Server) runAnalyzerSchedule(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
var tool string
var settings []byte
if err := s.db.QueryRow(r.Context(), `SELECT tool, settings FROM workflow_schedules WHERE id=$1 AND service=$2`, id, s.cfg.ServiceName).Scan(&tool, &settings); err != nil {
writeError(w, http.StatusNotFound, "schedule not found")
return
}
var parsedSettings struct {
Types []string `json:"types"`
}
_ = json.Unmarshal(settings, &parsedSettings)
types := normalizeMediaTypes(parsedSettings.Types, true)
started, err := s.startAnalyzerScheduledRun(tool, types)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if !started {
writeError(w, http.StatusConflict, "that stage is already running")
return
}
log.Printf("analyzer: automation schedule %s run manually (tool=%s)", id, tool)
_, _ = s.db.Exec(r.Context(), `
UPDATE workflow_schedules
SET last_run_at = NOW(), last_status = 'started', next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW()
WHERE id = $1`, id)
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "started": true})
}
func (s *Server) deleteAnalyzerSchedule(w http.ResponseWriter, r *http.Request) {
log.Printf("analyzer: automation schedule %s deleted", chi.URLParam(r, "id"))
s.deleteWorkflowSchedule(w, r)
}
func (s *Server) conversionSettings(w http.ResponseWriter, r *http.Request) {
value := s.settingValue(r.Context(), "conversion_settings", "{}")
var parsed any
_ = json.Unmarshal([]byte(value), &parsed)
writeJSON(w, http.StatusOK, map[string]any{"settings": parsed})
}
func (s *Server) saveConversionSettings(w http.ResponseWriter, r *http.Request) {
var payload map[string]any
if err := decodeRequestJSON(r, &payload); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if err := s.saveSetting(r.Context(), "conversion_settings", string(mustJSON(payload))); err != nil {
writeError(w, http.StatusInternalServerError, "conversion settings could not be saved")
return
}
log.Printf("analyzer: conversion settings saved")
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func supportedMediaPath(value string) bool {
switch strings.ToLower(filepath.Ext(value)) {
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg", ".mp4", ".mkv", ".mov", ".avi", ".webm", ".m4v", ".mpg", ".mpeg", ".ts", ".flv", ".wmv", ".3gp", ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", ".wma":
return true
default:
return false
}
}
func analyzerModelOptions() map[string]any {
return map[string]any{
"image": []string{"nsfwjs", "wdtagger", "faceapi", "onnxage", "florence2", "laplacian"},
"video": []string{"nsfwjs", "wdtagger", "florence2"},
"audio": []string{"whisper", "clap", "florence2"},
// No model in this codebase analyzes funscript motion data yet - "Disabled" is the
// only real option, exposed for symmetry with the other three media types.
"funscript": []string{},
}
}
func (s *Server) settingValue(ctx context.Context, key, fallback string) string {
var value string
if err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" {
return fallback
}
return value
}
func (s *Server) settingBool(ctx context.Context, key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(s.settingValue(ctx, key, "")))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
func (s *Server) saveSetting(ctx context.Context, key, value string) error {
_, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value)
return err
}