Files
shared/backend/mediacore/mediacore.go
T

1154 lines
43 KiB
Go
Raw Normal View History

// Package mediacore is the media-backend family's cross-service HTTP surface:
// media like/save/view stats, tags, playlists, cross-device playback sync
// state, and profile - the routes every media-family service mounts
// regardless of its own specialty (MediaViewer's own library/browse routes,
// CraftStudio's generator/downloader/converter, ContentScanner's AI
// pipeline, etc. are NOT here; each service owns those itself).
//
// Promoted from each service's own internal/server mountSharedRoutes/media.go
// into this shared library so all 7 independent media-family backends use
// one copy instead of duplicating it. Behavior is unchanged from the
// pre-split monolith - this is a mechanical extraction, not a rewrite.
//
// A service wires this up as:
//
// core := mediacore.New(mediacore.Config{
// DB: pool,
// Auth: authService,
// Sync: syncsocket.NewHub(),
// CarrierNode: carrierNodeClient,
// ServiceName: "CarrierNode", // cfg.ServiceName
// MediaRoots: func(ctx context.Context) []string { return cfg.MediaRoots },
// })
// if err := core.Migrate(ctx); err != nil { ... }
// router.Route("/api", func(r chi.Router) {
// core.Mount(r)
// // ... the service's own routes ...
// })
package mediacore
import (
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
2026-09-23 15:48:17 +02:00
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket"
)
// Config wires a Core to the rest of one service's dependencies.
type Config struct {
DB *pgxpool.Pool
Auth *sharedauth.Service
Sync *syncsocket.Hub
CarrierNode *carriernodeclient.Client
// ServiceName is recorded on mutations that track which app produced
// them (e.g. media_stats.app) - a service's own cfg.ServiceName.
ServiceName string
}
// Core mounts the shared media/tags/playlists/sync/profile routes and holds
// what they need to run.
type Core struct {
db *pgxpool.Pool
auth *sharedauth.Service
sync *syncsocket.Hub
carrierNode *carriernodeclient.Client
serviceName string
}
// New returns a Core ready to Mount and Migrate.
func New(cfg Config) *Core {
return &Core{db: cfg.DB, auth: cfg.Auth, sync: cfg.Sync, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName}
}
// Mount wires the shared routes onto r, exactly matching the pre-split
// monolith's mountSharedRoutes route table.
func (c *Core) Mount(r chi.Router) {
r.With(c.auth.Require).Get("/security/totp/status", c.auth.TOTPStatus)
r.With(c.auth.Require).Get("/security/totp/initiate", c.auth.TOTPInitiate)
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
r.With(c.auth.Require).Put("/sync", c.putSyncState)
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
r.With(c.auth.Require).Post("/media/{id}/tags/{tag}/vote", c.voteMediaTag)
r.Get("/tags/suggestions", c.tagSuggestions)
r.Get("/tags/{tag}/media", c.tagMedia)
r.With(c.auth.Require).Get("/playlists", c.playlists)
r.With(c.auth.Optional).Get("/playlists/summary", c.playlistSummary)
r.With(c.auth.Optional).Get("/playlists/{id}", c.playlist)
r.With(c.auth.Require).Post("/playlists", c.createPlaylist)
r.With(c.auth.Require).Delete("/playlists/{id}", c.deletePlaylist)
r.With(c.auth.Optional).Get("/playlists/{id}/items", c.playlistItems)
r.With(c.auth.Require).Post("/playlists/{id}/items", c.addPlaylistItem)
r.With(c.auth.Require).Delete("/playlists/{id}/items", c.deletePlaylistItem)
r.With(c.auth.Optional).Get("/playlists/{id}/random", c.randomPlaylistItem)
r.With(c.auth.Require).Patch("/playlists/{id}/items/reorder", c.reorderPlaylist)
r.With(c.auth.Optional).Get("/profile", c.profile)
}
func (c *Core) getSyncState(w http.ResponseWriter, r *http.Request) {
sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default"))
writeJSON(w, http.StatusOK, c.sync.HTTPState(sessionID))
}
func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
clientID := boundedSyncString(syncString(input, "clientId"))
if clientID == "" {
writeError(w, http.StatusBadRequest, "clientId is required")
return
}
mediaID, ok := syncScalar(input["mediaId"])
if !ok {
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(input, "timeMs", 0),
"paused": syncBool(input, "paused"),
"fps": syncFPS(input),
"frame": syncInt(input, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
if value, ok := input["playAt"]; ok {
playAt, valid := syncScalar(value)
if !valid {
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
return
}
state["playAt"] = playAt
}
c.sync.SetHTTPState(sessionID, state)
c.sync.Broadcast(sessionID)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state})
}
// MediaRecord is one row of the shared `media` table.
type MediaRecord struct {
2026-09-23 15:48:17 +02:00
ID int64
MediaKey string
MediaType string
Title *string
Description *string
FilePath string
OriginalName string
Source string
Width *int
Height *int
DurationMs *int64
SizeBytes *int64
IsVR bool
HasFunscript bool
FunscriptActionCount *int
FunscriptAvgSpeed *float32
FunscriptMaxSpeed *float32
Speed *float32
ModifiedAt time.Time
}
func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id")))
}
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
if err != nil {
writeError(w, http.StatusNotFound, "media not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
}
func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) {
c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id")))
}
func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
id := identifier
if !SafeRelative(id) {
writeError(w, http.StatusBadRequest, "invalid media id")
return
}
includeHidden := canSeeHidden(r)
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
return
}
}
2026-09-18 15:58:57 +02:00
var thumbnailID string
if err := c.db.QueryRow(r.Context(), `
SELECT t.id::text
FROM thumbnails t
JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key)
WHERE m.media_key=$1 OR CAST(m.id AS TEXT)=$1
ORDER BY t.created_at DESC
LIMIT 1`, id).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) {
// A row whose file CarrierNode no longer has falls through to the original image below,
// rather than proxying CarrierNode's 404.
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) {
return
}
2026-09-18 15:58:57 +02:00
}
record, err := c.findMedia(r.Context(), id, includeHidden)
if err != nil || !isImagePath(record.FilePath) {
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
c.carrierNode.Proxy(w, r, "/media/"+urlPath(record.FilePath))
}
func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("mediaKey"), chi.URLParam(r, "id")))
if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey")
return
}
user := sharedauth.UserFromContext(r.Context())
var likes, saves, views int64
if err := c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'like'`, key).Scan(&likes); err != nil {
writeError(w, http.StatusInternalServerError, "media state unavailable")
return
}
_ = c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'save'`, key).Scan(&saves)
_ = c.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'view'`, key).Scan(&views)
liked, saved := false, false
if user != nil {
_ = c.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='like')`, user.ID, key).Scan(&liked)
_ = c.db.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM media_stats WHERE user_id=$1 AND media_key=$2 AND stat_type='save')`, user.ID, key).Scan(&saved)
}
data := map[string]any{"mediaKey": key, "likeCount": likes, "saveCount": saves, "viewCount": views, "likedByUser": liked, "savedByUser": saved}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": data, "mediaKey": key, "likes": likes, "saves": saves, "views": views})
}
func (c *Core) mediaLike(w http.ResponseWriter, r *http.Request) {
c.mediaStatMutation(w, r, "like")
}
func (c *Core) mediaSave(w http.ResponseWriter, r *http.Request) {
c.mediaStatMutation(w, r, "save")
}
func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
var input struct {
MediaKey string `json:"mediaKey"`
Like *bool `json:"like"`
Save *bool `json:"save"`
Value *bool `json:"value"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
key := strings.TrimSpace(input.MediaKey)
if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey")
return
}
enabled := true
if statType == "like" && input.Like != nil {
enabled = *input.Like
}
if statType == "save" && input.Save != nil {
enabled = *input.Save
}
if input.Value != nil {
enabled = *input.Value
}
if enabled {
_, err := c.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, key, user.ID, statType, c.serviceName)
if err != nil {
writeError(w, http.StatusInternalServerError, "media state update failed")
return
}
} else {
_, _ = c.db.Exec(r.Context(), `DELETE FROM media_stats WHERE media_key = $1 AND user_id = $2 AND stat_type = $3`, key, user.ID, statType)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"mediaKey": key, "enabled": enabled}})
}
func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
var input struct {
MediaKey string `json:"mediaKey"`
}
if r.Body != nil && r.ContentLength != 0 {
_ = decodeRequestJSON(r, &input)
}
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey")))
if key == "" {
writeError(w, http.StatusBadRequest, "missing mediaKey")
return
}
var userID any
if user != nil {
userID = user.ID
}
if _, err := c.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, 'view', $3)`, key, userID, c.serviceName); err != nil {
writeError(w, http.StatusInternalServerError, "view could not be recorded")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
}
func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
var input struct {
MediaKey string `json:"mediaKey"`
DurationMs int64 `json:"durationMs"`
Duration int64 `json:"duration"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
duration := input.DurationMs
if duration <= 0 {
duration = input.Duration
}
if strings.TrimSpace(input.MediaKey) == "" || duration <= 0 {
writeError(w, http.StatusBadRequest, "mediaKey and positive duration are required")
return
}
var userID any
if user != nil {
userID = user.ID
}
_, err := c.db.Exec(r.Context(), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)`, strings.TrimSpace(input.MediaKey), userID, duration)
if err != nil {
writeError(w, http.StatusInternalServerError, "view session could not be recorded")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}})
}
func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "liked media unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
for rows.Next() {
var key string
var created time.Time
if rows.Scan(&key, &created) == nil {
items = append(items, map[string]any{"mediaKey": key, "createdAt": created, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)})
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items})
}
func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) {
key := strings.TrimSpace(chi.URLParam(r, "id"))
rows, err := c.db.Query(r.Context(), `
SELECT tag, COALESCE(SUM(vote), 0) AS score
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
WHERE mt.media_key = $1 GROUP BY tag ORDER BY score DESC, LOWER(tag)`, key)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return
}
defer rows.Close()
tags := make([]map[string]any, 0)
for rows.Next() {
var tag string
var score int64
if rows.Scan(&tag, &score) == nil {
tags = append(tags, map[string]any{"tag": tag, "score": score, "myVote": 0})
}
}
writeJSON(w, http.StatusOK, map[string]any{"tags": tags})
}
func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
var input struct {
Tag string `json:"tag"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
tag := strings.TrimSpace(input.Tag)
if tag == "" || len([]rune(tag)) > 80 {
writeError(w, http.StatusBadRequest, "tag is invalid")
return
}
key := strings.TrimSpace(chi.URLParam(r, "id"))
_, err := c.db.Exec(r.Context(), `INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, key, tag, user.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "tag could not be added")
return
}
writeJSON(w, http.StatusCreated, map[string]any{"tag": tag})
}
func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
var input struct {
Vote int `json:"vote"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
if input.Vote != -1 && input.Vote != 0 && input.Vote != 1 {
writeError(w, http.StatusBadRequest, "vote must be -1, 0, or 1")
return
}
key, tag := strings.TrimSpace(chi.URLParam(r, "id")), strings.TrimSpace(chi.URLParam(r, "tag"))
if input.Vote == 0 {
_, _ = c.db.Exec(r.Context(), `DELETE FROM media_tag_votes WHERE media_key=$1 AND LOWER(tag)=LOWER($2) AND user_id=$3`, key, tag, user.ID)
} else {
_, err := c.db.Exec(r.Context(), `INSERT INTO media_tag_votes (media_key, tag, user_id, vote) VALUES ($1, $2, $3, $4) ON CONFLICT (media_key, tag, user_id) DO UPDATE SET vote = EXCLUDED.vote`, key, tag, user.ID, input.Vote)
if err != nil {
writeError(w, http.StatusInternalServerError, "tag vote failed")
return
}
}
writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote})
}
func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) {
limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 1000)
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)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}})
return
}
defer rows.Close()
tags := make([]map[string]any, 0)
for rows.Next() {
var tag string
var count int64
if rows.Scan(&tag, &count) == nil {
tags = append(tags, map[string]any{"tag": tag, "count": count})
}
}
writeJSON(w, http.StatusOK, map[string]any{"tags": tags})
}
func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) {
tag := strings.ToLower(strings.TrimSpace(chi.URLParam(r, "tag")))
pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000)
limit := optionalInt(r.URL.Query().Get("limit"), 24, 1, 100)
offset := (pageNumber - 1) * limit
rows, err := c.db.Query(r.Context(), `SELECT DISTINCT media_key FROM media_tags WHERE LOWER(tag) = $1 ORDER BY media_key LIMIT $2 OFFSET $3`, tag, limit, offset)
if err != nil {
writeError(w, http.StatusInternalServerError, "tag media unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
for rows.Next() {
var key string
if rows.Scan(&key) == nil {
items = append(items, map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key), "name": filepath.Base(urlPath(key))})
}
}
writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber})
}
func (c *Core) playlists(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "playlists unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
for rows.Next() {
var id int64
var name string
var created time.Time
if rows.Scan(&id, &name, &created) == nil {
items = append(items, map[string]any{"id": id, "name": name, "createdAt": created})
}
}
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists"))
}
func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists"))
return
}
rows, err := c.db.Query(r.Context(), `SELECT p.id, p.name, p.created_at, COUNT(i.id) FROM playlists p LEFT JOIN playlist_items i ON p.id=i.playlist_id WHERE p.user_id=$1 GROUP BY p.id ORDER BY p.created_at DESC`, user.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "playlist summary unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
for rows.Next() {
var id, count int64
var name string
var created time.Time
if rows.Scan(&id, &name, &created, &count) == nil {
items = append(items, map[string]any{"id": id, "name": name, "item_count": count, "createdAt": created})
}
}
writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists summary"))
}
func (c *Core) playlist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || user == nil {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
var name string
var created time.Time
if err := c.db.QueryRow(r.Context(), `SELECT name, created_at FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID).Scan(&name, &created); err != nil {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist"))
}
func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
var input struct {
Name string `json:"name"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
name := strings.TrimSpace(input.Name)
if name == "" || len([]rune(name)) > 120 {
writeError(w, http.StatusBadRequest, "playlist name is invalid")
return
}
_, _ = c.db.Exec(r.Context(), `INSERT INTO playlists (user_id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING`, user.ID, name)
var id int64
var created time.Time
if err := c.db.QueryRow(r.Context(), `SELECT id, created_at FROM playlists WHERE user_id=$1 AND LOWER(name)=LOWER($2)`, user.ID, name).Scan(&id, &created); err != nil {
writeError(w, http.StatusInternalServerError, "playlist could not be created")
return
}
writeJSON(w, http.StatusCreated, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist created"))
}
func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid playlist id")
return
}
result, err := c.db.Exec(r.Context(), `DELETE FROM playlists WHERE id=$1 AND user_id=$2`, id, user.ID)
if err != nil || result.RowsAffected() == 0 {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist deleted"))
}
func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil || user == nil {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
var owner int64
if err := c.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
rows, err := c.db.Query(r.Context(), `SELECT id, media_key, COALESCE(position, 0), created_at FROM playlist_items WHERE playlist_id=$1 ORDER BY COALESCE(position, 0), created_at`, id)
if err != nil {
writeError(w, http.StatusInternalServerError, "playlist items unavailable")
return
}
defer rows.Close()
items := make([]map[string]any, 0)
for rows.Next() {
var itemID int64
var key string
var position int
var created time.Time
if rows.Scan(&itemID, &key, &position, &created) == nil {
items = append(items, map[string]any{"id": itemID, "media_key": key, "mediaKey": key, "position": position, "createdAt": created, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)})
}
}
writeJSON(w, http.StatusOK, success(map[string]any{"items": items}, "Playlist items"))
}
func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid playlist id")
return
}
var owner int64
if err := c.db.QueryRow(r.Context(), `SELECT user_id FROM playlists WHERE id=$1`, id).Scan(&owner); err != nil || owner != user.ID {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
var input struct {
MediaKey string `json:"mediaKey"`
MediaKeySnake string `json:"media_key"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, input.MediaKeySnake))
if key == "" {
writeError(w, http.StatusBadRequest, "mediaKey is required")
return
}
_, err = c.db.Exec(r.Context(), `INSERT INTO playlist_items (playlist_id, media_key) VALUES ($1, $2) ON CONFLICT DO NOTHING`, id, key)
if err != nil {
writeError(w, http.StatusInternalServerError, "playlist item could not be added")
return
}
writeJSON(w, http.StatusCreated, success(map[string]any{"mediaKey": key}, "Playlist item added"))
}
func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid playlist id")
return
}
var input struct {
MediaKey string `json:"mediaKey"`
MediaKeySnake string `json:"media_key"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
key := strings.TrimSpace(firstNonEmpty(input.MediaKey, input.MediaKeySnake))
result, err := c.db.Exec(r.Context(), `DELETE FROM playlist_items WHERE playlist_id=$1 AND media_key=$2 AND EXISTS (SELECT 1 FROM playlists WHERE id=$1 AND user_id=$3)`, id, key, user.ID)
if err != nil || result.RowsAffected() == 0 {
writeError(w, http.StatusNotFound, "playlist item not found")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist item deleted"))
}
func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
writeError(w, http.StatusNotFound, "playlist not found")
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid playlist id")
return
}
var key string
if err := c.db.QueryRow(r.Context(), `SELECT i.media_key FROM playlist_items i JOIN playlists p ON p.id=i.playlist_id WHERE i.playlist_id=$1 AND p.user_id=$2 ORDER BY RANDOM() LIMIT 1`, id, user.ID).Scan(&key); err != nil {
writeError(w, http.StatusNotFound, "no media in playlist")
return
}
writeJSON(w, http.StatusOK, success(map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}, "Random playlist media"))
}
func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid playlist id")
return
}
var input struct {
IDs []int64 `json:"ids"`
ItemIDs []int64 `json:"itemIds"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
ids := input.IDs
if len(ids) == 0 {
ids = input.ItemIDs
}
for position, itemID := range ids {
_, _ = c.db.Exec(r.Context(), `UPDATE playlist_items SET position=$1 WHERE id=$2 AND playlist_id=$3 AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)`, position, itemID, id, user.ID)
}
writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered"))
}
func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
user := sharedauth.UserFromContext(r.Context())
if user == nil {
writeJSON(w, http.StatusOK, map[string]any{"user": nil})
return
}
writeJSON(w, http.StatusOK, map[string]any{"user": user})
}
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
func canSeeHidden(r *http.Request) bool {
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
}
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
// error counts as hidden, so a database fault never exposes hidden media.
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
var hidden bool
err := c.db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
strings.TrimSpace(identifier)).Scan(&hidden)
return err != nil || hidden
}
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
// when includeHidden is set.
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
identifier = strings.TrimSpace(identifier)
var record MediaRecord
row := c.db.QueryRow(ctx, `
SELECT id, media_key, COALESCE(media_type, 'unknown'), COALESCE(title, ''), COALESCE(description, ''),
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),
2026-09-23 15:48:17 +02:00
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)
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
var title, description string
var width, height int
var duration, size int64
2026-09-23 15:48:17 +02:00
var funscriptActionCount pgtype.Int4
var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4
var speed float32
2026-09-23 15:48:17 +02:00
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 {
return MediaRecord{}, err
}
2026-09-23 15:48:17 +02:00
if funscriptActionCount.Valid {
value := int(funscriptActionCount.Int32)
record.FunscriptActionCount = &value
}
if funscriptAvgSpeed.Valid {
value := funscriptAvgSpeed.Float32
record.FunscriptAvgSpeed = &value
}
if funscriptMaxSpeed.Valid {
value := funscriptMaxSpeed.Float32
record.FunscriptMaxSpeed = &value
}
if title != "" {
record.Title = &title
}
if description != "" {
record.Description = &description
}
if width > 0 {
record.Width = &width
}
if height > 0 {
record.Height = &height
}
if duration > 0 {
record.DurationMs = &duration
}
if size > 0 {
record.SizeBytes = &size
}
if speed > 0 {
record.Speed = &speed
}
return record, nil
}
// ToJSON is the shared wire shape for a media record, matching every
// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/
// etc.) - services with their own media listing routes (e.g. MediaViewer's
// mountViewerRoutes) should use this too, for a consistent shape.
func (record MediaRecord) ToJSON() map[string]any {
filename := record.OriginalName
if filename == "" {
filename = filepath.Base(urlPath(record.FilePath))
}
mediaType := record.MediaType
if mediaType == "unknown" || mediaType == "" {
mediaType = InferMediaType(filename)
}
return map[string]any{
"id": record.MediaKey, "numericId": record.ID, "mediaKey": record.MediaKey,
"filename": filename, "name": filename, "title": record.Title, "description": record.Description,
"relPath": urlPath(record.FilePath), "mediaType": mediaType, "source": record.Source,
"url": mediaStreamURL(record.MediaKey), "thumbnail": mediaThumbnailURL(record.MediaKey),
"width": intValue(record.Width), "height": intValue(record.Height), "durationMs": int64Value(record.DurationMs),
"sizeBytes": int64Value(record.SizeBytes), "isVr": record.IsVR, "hasFunscript": record.HasFunscript, "speed": floatValue(record.Speed),
2026-09-23 15:48:17 +02:00
"funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed),
"modifiedAt": record.ModifiedAt,
}
}
// SettingValue reads one key from the shared `settings` table, returning
// fallback if it is unset or the read fails.
func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) string {
var value string
if err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value); err != nil || value == "" {
return fallback
}
return value
}
// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true,
// anything else is fallback).
func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool {
value := strings.ToLower(strings.TrimSpace(SettingValue(ctx, db, key, "")))
if value == "" {
return fallback
}
return value == "1" || value == "true" || value == "yes" || value == "on"
}
// SaveSetting upserts one key in the shared `settings` table.
func SaveSetting(ctx context.Context, db *pgxpool.Pool, key, value string) error {
_, err := 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
}
// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the
// base "carriernode" itself, or a numbered peer like "carriernode_2" - see
// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in
// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of
// the same convention, not literally shared code).
var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`)
// CarrierNodeURLs returns every CarrierNode instance registered in ProjectConfigurator's Projects
// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared
// `settings` table in registration order, dropping any instance with no URL set. This is for the
// 7 MEDIA_SERVICE instances that share this database directly instead of going through
// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service
// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs:
//
// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string {
// return mediacore.CarrierNodeURLs(ctx, db, fallback)
// })
//
// Returns fallback if no carriernode* instance is registered (or none has a URL) yet.
func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string {
var registered []string
_ = json.Unmarshal([]byte(SettingValue(ctx, db, "configured_central", "")), &registered)
var urls []string
for _, project := range registered {
key := strings.ToLower(strings.TrimSpace(project))
if !carrierNodeInstancePattern.MatchString(key) {
continue
}
if url := strings.TrimSpace(SettingValue(ctx, db, key+"_url", "")); url != "" {
urls = append(urls, url)
}
}
if len(urls) == 0 {
if url := strings.TrimSpace(SettingValue(ctx, db, "carriernode_url", "")); url != "" {
urls = []string{url}
}
}
if len(urls) == 0 {
return fallback
}
return urls
}
// --- path-safety helpers (generic, no Core dependency) ---
// SafeRelative reports whether value is a relative path with no `..`
// traversal or absolute-path escape (Windows drive letters included).
func SafeRelative(value string) bool {
value = strings.TrimSpace(value)
windowsAbsolute := len(value) >= 2 && value[1] == ':'
return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`)
}
// WithinRoot reports whether candidate is (non-strictly) inside root.
func WithinRoot(root, candidate string) bool {
rel, err := filepath.Rel(root, candidate)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
}
// SameRealRoot reports whether candidate's symlink-resolved real path is
// still inside root's symlink-resolved real path (guards against a symlink
// planted inside root pointing outside it).
func SameRealRoot(root, candidate string) bool {
realRoot, err := filepath.EvalSymlinks(root)
if err != nil {
return false
}
realCandidate, err := filepath.EvalSymlinks(candidate)
if err != nil {
return false
}
realRoot, err = filepath.Abs(realRoot)
if err != nil {
return false
}
realCandidate, err = filepath.Abs(realCandidate)
return err == nil && WithinRoot(realRoot, realCandidate)
}
// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative
// path) against each of roots in order, returning the first root it
// actually exists under as a real file (not a directory, and not merely a
// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root
// matches.
func ResolveUnderRoots(value string, roots []string) (string, error) {
value = strings.TrimSpace(strings.TrimPrefix(value, "/media/"))
value = strings.TrimPrefix(value, "/")
if value == "" || strings.ContainsRune(value, 0) {
return "", errors.New("empty path")
}
for _, root := range roots {
rootAbs, err := filepath.Abs(root)
if err != nil {
continue
}
candidate := value
if !filepath.IsAbs(candidate) {
candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate))
}
candidate, err = filepath.Abs(candidate)
if err != nil || !WithinRoot(rootAbs, candidate) {
continue
}
info, err := os.Stat(candidate)
if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) {
return candidate, nil
}
}
return "", os.ErrNotExist
}
// ServeFile serves fullPath (an already-resolved, already-safety-checked
// path) with the correct Content-Type and range-request support.
func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) {
file, err := os.Open(fullPath)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
writeError(w, http.StatusNotFound, "file not found")
return
}
if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file)
}
// InferMediaType guesses a media type from a filename's extension.
func InferMediaType(value string) string {
switch strings.ToLower(filepath.Ext(value)) {
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg":
return "image"
case ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus", ".wma":
return "audio"
default:
return "video"
}
}
func isImagePath(value string) bool {
switch strings.ToLower(filepath.Ext(value)) {
case ".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".avif", ".svg":
return true
default:
return false
}
}
func mediaStreamURL(identifier string) string {
return "/api/media/stream?mediaKey=" + url.QueryEscape(strings.TrimSpace(identifier))
}
func mediaThumbnailURL(identifier string) string {
return "/api/media/thumb?mediaKey=" + url.QueryEscape(strings.TrimSpace(identifier))
}
func urlPath(value string) string {
value = strings.ReplaceAll(value, `\`, "/")
value = strings.TrimPrefix(value, "/")
value = strings.TrimPrefix(value, "media/")
return value
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func optionalInt(value string, fallback, minimum, maximum int) int {
parsed, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
return fallback
}
if parsed < minimum {
return minimum
}
if parsed > maximum {
return maximum
}
return parsed
}
func intValue(value *int) any {
if value == nil {
return nil
}
return *value
}
func int64Value(value *int64) any {
if value == nil {
return nil
}
return *value
}
func floatValue(value *float32) any {
if value == nil {
return nil
}
return *value
}
func success(data any, message string) map[string]any {
return map[string]any{"success": true, "data": data, "message": message}
}
func decodeRequestJSON(r *http.Request, target any) error {
defer r.Body.Close()
decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024))
decoder.DisallowUnknownFields()
return decoder.Decode(target)
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message, "message": message})
}
// --- sync-message helpers (shared with syncsocket's own copies; duplicated
// here rather than exported from syncsocket, since these are trivially small
// and this keeps mediacore and syncsocket independently buildable) ---
func syncString(message map[string]any, key string) string {
value, _ := message[key].(string)
return strings.TrimSpace(value)
}
func boundedSyncString(value string) string {
const maxSyncIdentifier = 128
value = strings.TrimSpace(value)
if len(value) > maxSyncIdentifier {
return value[:maxSyncIdentifier]
}
return value
}
func syncBool(message map[string]any, key string) bool {
value, _ := message[key].(bool)
return value
}
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
// shared session state.
func syncScalar(value any) (any, bool) {
switch typed := value.(type) {
case nil, float64:
return typed, true
case string:
return boundedSyncString(typed), true
default:
return nil, false
}
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok {
return fallback
}
if value < 0 {
return 0
}
return int64(value)
}
func syncFPS(message map[string]any) int64 {
fps := syncInt(message, "fps", 30)
if fps < 1 {
return 1
}
if fps > 240 {
return 240
}
return fps
}