feat: extend media library controls and playback
Security / Secrets (gitleaks) (push) Successful in 1m49s
Security / Code (Semgrep) (push) Successful in 2m41s
Security / Dependencies (Trivy) (push) Successful in 1m9s
Docker / Docker Build & Push (push) Successful in 8m48s

- Add safe CarrierNode media deletion and rating support
- Count tag suggestions across visible, processed media
- Support muted autoplay in MediaPlayer
This commit is contained in:
Gabriel20xx committed 2026-11-13 19:23:02 +01:00
1 parent 5d9e3063c5
commit 0c4dc3aacb
5 files changed
+161 -4

No files matched your search

@@ -467,6 +467,47 @@ func (c *Client) DeleteMountFile(ctx context.Context, project, mountType, relati
return nil return nil
} }
// DeleteMedia removes one library file from the primary CarrierNode. carrierNodePath is the
// "/media/..." request path the caller probed, so the delete targets the same file the probe
// found. It reports whether CarrierNode removed a file: a 404 is a clean "not there" and returns
// false with a nil error, so a caller can tell a removal apart from a file that was already gone.
func (c *Client) DeleteMedia(ctx context.Context, carrierNodePath string) (bool, error) {
if !validMediaRequestPath(carrierNodePath) {
return false, fmt.Errorf("invalid media path")
}
request, err := c.newRequest(ctx, c.primaryBaseURL(ctx), http.MethodDelete, carrierNodePath, nil)
if err != nil {
return false, err
}
response, err := httpClient.Do(request)
if err != nil {
return false, err
}
defer response.Body.Close()
switch {
case response.StatusCode == http.StatusNotFound:
return false, nil
case response.StatusCode >= 400:
return false, fmt.Errorf("carriernode media delete failed: %s", response.Status)
}
return true, nil
}
// validMediaRequestPath accepts only a /media/ request path with no ".." segment after
// unescaping, so a delete cannot name a path outside the media route.
func validMediaRequestPath(carrierNodePath string) bool {
if !strings.HasPrefix(carrierNodePath, "/media/") {
return false
}
for _, segment := range strings.Split(carrierNodePath, "/") {
decoded, err := url.PathUnescape(segment)
if err != nil || decoded == ".." {
return false
}
}
return true
}
// ThumbnailMountType is the mount type ProjectConfigurator configures for a project's // ThumbnailMountType is the mount type ProjectConfigurator configures for a project's
// generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount. // generated thumbnails. Each thumbnail is one "<id>.jpg" file under that mount.
const ThumbnailMountType = "thumbnails" const ThumbnailMountType = "thumbnails"
@@ -0,0 +1,94 @@
package carriernodeclient
import (
"context"
"net/http"
"net/http/httptest"
"slices"
"sync"
"testing"
)
// mediaDeleteServer answers DELETE /media/... with the status for each path (default 404) and records
// every request so a test can see what reached CarrierNode. A path answered with 200 is removed by that
// delete, so a later request for it gets 404, as it would from a real CarrierNode.
type mediaDeleteServer struct {
mu sync.Mutex
statuses map[string]int
requests []string
}
func (n *mediaDeleteServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.EscapedPath()
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+path)
status, ok := n.statuses[path]
if !ok {
status = http.StatusNotFound
}
if r.Method == http.MethodDelete && status == http.StatusOK {
n.statuses[path] = http.StatusNotFound
}
n.mu.Unlock()
w.WriteHeader(status)
}
func (n *mediaDeleteServer) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
func newMediaDeleteClient(t *testing.T, statuses map[string]int) (*Client, *mediaDeleteServer) {
t.Helper()
node := &mediaDeleteServer{statuses: statuses}
server := httptest.NewServer(node)
t.Cleanup(server.Close)
return New("cn-secret", func(context.Context) string { return server.URL }), node
}
func TestDeleteMediaReportsRemovalAndAlreadyMissing(t *testing.T) {
client, node := newMediaDeleteClient(t, map[string]int{"/media/Videos/clip.mp4": http.StatusOK})
removed, err := client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err != nil || !removed {
t.Fatalf("first delete = (%v, %v), want (true, nil)", removed, err)
}
removed, err = client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err != nil || removed {
t.Fatalf("second delete = (%v, %v), want (false, nil) for a file already gone", removed, err)
}
want := []string{"DELETE /media/Videos/clip.mp4", "DELETE /media/Videos/clip.mp4"}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestDeleteMediaReportsServerErrors(t *testing.T) {
client, _ := newMediaDeleteClient(t, map[string]int{"/media/Videos/clip.mp4": http.StatusInternalServerError})
removed, err := client.DeleteMedia(context.Background(), "/media/Videos/clip.mp4")
if err == nil || removed {
t.Fatalf("delete = (%v, %v), want (false, error) for a 500", removed, err)
}
}
func TestDeleteMediaRefusesPathsOutsideTheMediaRoute(t *testing.T) {
client, node := newMediaDeleteClient(t, nil)
for _, path := range []string{
"/api/media/Videos/clip.mp4",
"/mount/media/Videos/clip.mp4",
"media/Videos/clip.mp4",
"/media/../secret.mp4",
"/media/Videos/%2e%2e/%2e%2e/secret.mp4",
"",
} {
if removed, err := client.DeleteMedia(context.Background(), path); err == nil || removed {
t.Fatalf("DeleteMedia(%q) = (%v, %v), want (false, error)", path, removed, err)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("refused paths still reached CarrierNode: %v", got)
}
}
+19 -4
View File
@@ -117,6 +117,7 @@ type MediaRecord struct {
FunscriptMaxSpeed *float32 FunscriptMaxSpeed *float32
Speed *float32 Speed *float32
ModifiedAt time.Time ModifiedAt time.Time
Rating string
} }
func (c *Service) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { func (c *Service) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
@@ -440,7 +441,16 @@ func (c *Service) tagSuggestions(w http.ResponseWriter, r *http.Request) {
if value := r.URL.Query().Get("limit"); value != "" { if value := r.URL.Query().Get("limit"); value != "" {
limit = optionalInt(value, 50, 1, math.MaxInt) limit = optionalInt(value, 50, 1, math.MaxInt)
} }
rows, err := c.db.Query(r.Context(), `SELECT tag, COUNT(*) AS frequency FROM media_tags GROUP BY tag ORDER BY frequency DESC, LOWER(tag) LIMIT $1`, limit) // Match the library's visibility rules and count media items rather than tag rows:
// a tag can have contributions from multiple users, and old tags may outlive media.
rows, err := c.db.Query(r.Context(), `
SELECT MIN(mt.tag) AS tag, COUNT(DISTINCT m.media_key) AS frequency
FROM media_tags mt
JOIN media m ON m.media_key = mt.media_key
WHERE m.active = TRUE AND m.content_scanner_processed = TRUE
GROUP BY LOWER(mt.tag)
ORDER BY frequency DESC, LOWER(MIN(mt.tag))
LIMIT $1`, limit)
if err != nil { if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return return
@@ -779,7 +789,8 @@ func (c *Service) FindMedia(ctx context.Context, identifier string, options Medi
COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'), COALESCE(NULLIF(file_path, ''), media_key), COALESCE(original_filename, ''), COALESCE(source, 'Filesystem'),
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0), COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count, COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at) funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at),
COALESCE(rating, '')
FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`, FROM media WHERE (media_key=$1 OR id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`,
identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed) identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed)
var title, description string var title, description string
@@ -788,7 +799,7 @@ func (c *Service) FindMedia(ctx context.Context, identifier string, options Medi
var funscriptActionCount pgtype.Int4 var funscriptActionCount pgtype.Int4
var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4 var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4
var speed float32 var speed float32
if err := row.Scan(&record.ID, &record.MediaKey, &record.MediaType, &title, &description, &record.FilePath, &record.OriginalName, &record.Source, &width, &height, &duration, &size, &record.IsVR, &record.HasFunscript, &funscriptActionCount, &funscriptAvgSpeed, &funscriptMaxSpeed, &speed, &record.ModifiedAt); err != nil { if err := row.Scan(&record.ID, &record.MediaKey, &record.MediaType, &title, &description, &record.FilePath, &record.OriginalName, &record.Source, &width, &height, &duration, &size, &record.IsVR, &record.HasFunscript, &funscriptActionCount, &funscriptAvgSpeed, &funscriptMaxSpeed, &speed, &record.ModifiedAt, &record.Rating); err != nil {
return MediaRecord{}, err return MediaRecord{}, err
} }
if funscriptActionCount.Valid { if funscriptActionCount.Valid {
@@ -846,7 +857,7 @@ func (record MediaRecord) ToJSON() map[string]any {
if mediaType == "unknown" || mediaType == "" { if mediaType == "unknown" || mediaType == "" {
mediaType = InferMediaType(filename) mediaType = InferMediaType(filename)
} }
return map[string]any{ result := map[string]any{
"id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey, "id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey,
"filename": filename, "name": filename, "title": record.Title, "description": record.Description, "filename": filename, "name": filename, "title": record.Title, "description": record.Description,
"relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source, "relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source,
@@ -856,6 +867,10 @@ func (record MediaRecord) ToJSON() map[string]any {
"funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed), "funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed),
"modifiedAt": record.ModifiedAt, "modifiedAt": record.ModifiedAt,
} }
if record.Rating != "" {
result["rating"] = record.Rating
}
return result
} }
// --- path-safety helpers (generic, no Core dependency) --- // --- path-safety helpers (generic, no Core dependency) ---
+2
View File
@@ -74,6 +74,7 @@ var migrationStatements = []string{
size_bytes BIGINT, size_bytes BIGINT,
is_vr BOOLEAN NOT NULL DEFAULT FALSE, is_vr BOOLEAN NOT NULL DEFAULT FALSE,
has_funscript BOOLEAN NOT NULL DEFAULT FALSE, has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
rating TEXT,
funscript_action_count INT, funscript_action_count INT,
funscript_avg_speed REAL, funscript_avg_speed REAL,
funscript_max_speed REAL, funscript_max_speed REAL,
@@ -82,6 +83,7 @@ var migrationStatements = []string{
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW() modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`, )`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS rating TEXT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
@@ -13,6 +13,7 @@
poster = '', poster = '',
title = '', title = '',
autoplay = false, autoplay = false,
autoplayMuted = false,
class: className = '', class: className = '',
mediaClass = '', mediaClass = '',
showSeekButtons: _showSeekButtons = true, showSeekButtons: _showSeekButtons = true,
@@ -41,6 +42,8 @@
poster?: string poster?: string
title?: string title?: string
autoplay?: boolean autoplay?: boolean
/** Start autoplaying video muted, so browser autoplay policies allow playback. */
autoplayMuted?: boolean
class?: string class?: string
mediaClass?: string mediaClass?: string
/** @deprecated Seeking is available with the arrow keys and mobile double-tap. */ /** @deprecated Seeking is available with the arrow keys and mobile double-tap. */
@@ -291,6 +294,7 @@
$effect(() => { $effect(() => {
const nextSource = src const nextSource = src
if (!mediaElement || !nextSource) return if (!mediaElement || !nextSource) return
if (!audio && autoplay && autoplayMuted) mediaElement.muted = true
mediaElement.load() mediaElement.load()
if (autoplay) void mediaElement.play().catch(() => undefined) if (autoplay) void mediaElement.play().catch(() => undefined)
}) })
@@ -361,6 +365,7 @@
{src} {src}
{poster} {poster}
{autoplay} {autoplay}
muted={autoplay && autoplayMuted}
preload="auto" preload="auto"
playsinline playsinline
tabindex="0" tabindex="0"