2026-11-01 21:48:05 +01:00
// Package media is the shared media library API: media likes, saves and view stats, tags and tag
// votes, playlists, and the stream and thumbnail routes. A service that serves media from its own
// library mounts these routes with Mount. A service without a media library mounts none of them.
2026-09-07 16:00:08 +02:00
//
// A service wires this up as:
//
2026-11-01 21:48:05 +01:00
// svc := media.New(media.Config{
2026-09-07 16:00:08 +02:00
// DB: pool,
// Auth: authService,
// CarrierNode: carrierNodeClient,
// ServiceName: "CarrierNode", // cfg.ServiceName
// })
2026-11-01 21:48:05 +01:00
// if err := svc.Migrate(ctx); err != nil { ... }
2026-09-07 16:00:08 +02:00
// router.Route("/api", func(r chi.Router) {
2026-11-01 21:48:05 +01:00
// svc.Mount(r)
2026-09-07 16:00:08 +02:00
// // ... the service's own routes ...
// })
2026-11-01 21:48:05 +01:00
package media
2026-09-01 08:43:25 +02:00
import (
"context"
"encoding/json"
"io"
2026-11-01 21:48:05 +01:00
"math"
2026-09-01 08:43:25 +02:00
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/go-chi/chi/v5"
2026-09-23 15:48:17 +02:00
"github.com/jackc/pgx/v5/pgtype"
2026-09-07 16:00:08 +02:00
"github.com/jackc/pgx/v5/pgxpool"
2026-09-01 08:43:25 +02:00
2026-09-13 18:43:16 +02:00
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
2026-09-07 16:00:08 +02:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient"
2026-11-01 21:48:05 +01:00
"repos.gfranz.ch/Gabriel20xx/shared/backend/files"
2026-09-01 08:43:25 +02:00
)
2026-10-19 21:46:52 +00:00
// maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the
// cap bounds its size; a playlist longer than this is reordered in more than one request.
const maxPlaylistReorderItems = 10000
2026-11-01 21:48:05 +01:00
// Config wires a Service to the rest of one service's dependencies.
2026-09-07 16:00:08 +02:00
type Config struct {
DB * pgxpool . Pool
2026-09-13 18:43:16 +02:00
Auth * sharedauth . Service
2026-09-07 16:00:08 +02:00
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
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
// Service mounts the shared media routes and holds what they need to run.
type Service struct {
2026-09-07 16:00:08 +02:00
db * pgxpool . Pool
2026-09-13 18:43:16 +02:00
auth * sharedauth . Service
2026-09-07 16:00:08 +02:00
carrierNode * carriernodeclient . Client
serviceName string
}
2026-11-01 21:48:05 +01:00
// New returns a Service ready to Mount and Migrate.
func New ( cfg Config ) * Service {
return & Service { db : cfg . DB , auth : cfg . Auth , carrierNode : cfg . CarrierNode , serviceName : cfg . ServiceName }
2026-09-07 16:00:08 +02:00
}
2026-11-01 21:48:05 +01:00
// Mount wires the media routes onto r. Sync, profile and the TOTP routes are not media routes:
// mount them with syncsocket.MountRoutes and auth.Service.MountAccountRoutes.
func ( c * Service ) Mount ( r chi . Router ) {
2026-09-07 16:00:08 +02:00
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 )
2026-10-19 07:48:07 +00:00
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 )
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
// 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
2026-11-13 19:23:02 +01:00
Rating string
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) streamMediaByQuery ( w http . ResponseWriter , r * http . Request ) {
2026-09-07 16:00:08 +02:00
c . streamMediaIdentifier ( w , r , firstNonEmpty ( r . URL . Query (). Get ( "mediaKey" ), r . URL . Query (). Get ( "id" )))
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) streamMediaIdentifier ( w http . ResponseWriter , r * http . Request , identifier string ) {
2026-10-19 07:48:07 +00:00
record , err := c . findMedia ( r . Context (), identifier , canSeeHidden ( r ))
2026-09-01 08:43:25 +02:00
if err != nil {
writeError ( w , http . StatusNotFound , "media not found" )
return
}
2026-10-19 21:46:52 +00:00
upstream , ok := upstreamMediaPath ( record . FilePath )
if ! ok {
writeError ( w , http . StatusNotFound , "media not found" )
return
}
2026-11-18 14:00:13 +01:00
c . carrierNode . Proxy ( w , r , streamUpstreamPath ( upstream , r . URL . Query ()))
}
// streamUpstreamPath is the CarrierNode request path for a stream. CarrierNode answers with a live
// H.264 copy when the query carries quality (a height) and start (seconds), which is how browsers get
// containers they cannot decode. Those two parameters are the only ones forwarded.
func streamUpstreamPath ( upstream string , query url . Values ) string {
forward := url . Values {}
for _ , key := range [] string { "quality" , "start" } {
if value := strings . TrimSpace ( query . Get ( key )); value != "" {
forward . Set ( key , value )
}
}
if len ( forward ) == 0 {
return "/media/" + upstream
}
return "/media/" + upstream + "?" + forward . Encode ()
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) thumbnailMediaByQuery ( w http . ResponseWriter , r * http . Request ) {
2026-09-07 16:00:08 +02:00
c . thumbnailMediaIdentifier ( w , r , firstNonEmpty ( r . URL . Query (). Get ( "mediaKey" ), r . URL . Query (). Get ( "id" )))
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) thumbnailMediaIdentifier ( w http . ResponseWriter , r * http . Request , identifier string ) {
2026-09-01 08:43:25 +02:00
id := identifier
2026-11-01 21:48:05 +01:00
if ! files . SafeRelative ( id ) {
2026-09-01 08:43:25 +02:00
writeError ( w , http . StatusBadRequest , "invalid media id" )
return
}
2026-10-19 07:48:07 +00:00
includeHidden := canSeeHidden ( r )
if ! includeHidden && c . isHiddenMedia ( r . Context (), id ) {
writeError ( w , http . StatusNotFound , "thumbnail not found" )
return
}
2026-09-01 08:43:25 +02:00
if ! strings . Contains ( id , string ( filepath . Separator )) && ! strings . Contains ( id , "/" ) {
2026-10-15 13:56:24 +00:00
if c . carrierNode . ProxyThumbnail ( w , r , c . serviceName , id ) {
2026-09-01 08:43:25 +02:00
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)
2026-10-19 21:46:52 +00:00
WHERE m.media_key=$1 OR m.id=$2
2026-09-18 15:58:57 +02:00
ORDER BY t.created_at DESC
2026-11-01 21:48:05 +01:00
LIMIT 1` , id , mediaIDArg ( id )). Scan ( & thumbnailID ); err == nil && files . SafeRelative ( thumbnailID ) {
2026-10-15 13:56:24 +00:00
// 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
}
2026-10-19 07:48:07 +00:00
record , err := c . findMedia ( r . Context (), id , includeHidden )
2026-09-01 08:43:25 +02:00
if err != nil || ! isImagePath ( record . FilePath ) {
writeError ( w , http . StatusNotFound , "thumbnail not found" )
return
}
2026-10-19 21:46:52 +00:00
upstream , ok := upstreamMediaPath ( record . FilePath )
if ! ok {
writeError ( w , http . StatusNotFound , "thumbnail not found" )
return
}
c . carrierNode . Proxy ( w , r , "/media/" + upstream )
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaState ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 08:43:25 +02:00
key := strings . TrimSpace ( firstNonEmpty ( r . URL . Query (). Get ( "mediaKey" ), chi . URLParam ( r , "id" )))
if key == "" {
writeError ( w , http . StatusBadRequest , "missing mediaKey" )
return
}
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
var likes , saves , views int64
2026-09-07 16:00:08 +02:00
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 {
2026-09-01 08:43:25 +02:00
writeError ( w , http . StatusInternalServerError , "media state unavailable" )
return
}
2026-09-07 16:00:08 +02:00
_ = 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 )
2026-09-01 08:43:25 +02:00
liked , saved := false , false
if user != nil {
2026-09-07 16:00:08 +02:00
_ = 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 )
2026-09-01 08:43:25 +02:00
}
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 })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaLike ( w http . ResponseWriter , r * http . Request ) {
2026-09-07 16:00:08 +02:00
c . mediaStatMutation ( w , r , "like" )
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaSave ( w http . ResponseWriter , r * http . Request ) {
2026-09-07 16:00:08 +02:00
c . mediaStatMutation ( w , r , "save" )
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaStatMutation ( w http . ResponseWriter , r * http . Request , statType string ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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 {
2026-09-07 16:00:08 +02:00
_ , 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 )
2026-09-01 08:43:25 +02:00
if err != nil {
writeError ( w , http . StatusInternalServerError , "media state update failed" )
return
}
} else {
2026-09-07 16:00:08 +02:00
_ , _ = 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 )
2026-09-01 08:43:25 +02:00
}
writeJSON ( w , http . StatusOK , map [ string ] any { "success" : true , "data" : map [ string ] any { "mediaKey" : key , "enabled" : enabled }})
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaView ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
var input struct {
MediaKey string `json:"mediaKey"`
}
if r . Body != nil && r . ContentLength != 0 {
2026-10-20 15:27:53 +00:00
if err := decodeRequestJSON ( r , & input ); err != nil {
writeError ( w , http . StatusBadRequest , "invalid JSON body" )
return
}
2026-09-01 08:43:25 +02:00
}
key := strings . TrimSpace ( firstNonEmpty ( input . MediaKey , r . URL . Query (). Get ( "mediaKey" )))
if key == "" {
writeError ( w , http . StatusBadRequest , "missing mediaKey" )
return
}
2026-10-20 15:27:53 +00:00
exists , err := c . mediaExists ( r . Context (), key )
if err != nil {
writeError ( w , http . StatusInternalServerError , "media lookup failed" )
return
}
if ! exists {
writeError ( w , http . StatusNotFound , "media not found" )
return
}
2026-09-01 08:43:25 +02:00
var userID any
if user != nil {
userID = user . ID
}
2026-09-07 16:00:08 +02:00
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 {
2026-09-01 08:43:25 +02:00
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 }})
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaViewSession ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
}
2026-10-20 15:27:53 +00:00
key := strings . TrimSpace ( input . MediaKey )
if key == "" || duration <= 0 || duration > maxViewSessionDurationMs {
writeError ( w , http . StatusBadRequest , "mediaKey and duration between 1ms and 24h are required" )
return
}
exists , err := c . mediaExists ( r . Context (), key )
if err != nil {
writeError ( w , http . StatusInternalServerError , "media lookup failed" )
return
}
if ! exists {
writeError ( w , http . StatusNotFound , "media not found" )
2026-09-01 08:43:25 +02:00
return
}
var userID any
if user != nil {
userID = user . ID
}
2026-10-20 15:27:53 +00:00
_ , err = c . db . Exec ( r . Context (), `INSERT INTO media_view_sessions (media_key, user_id, duration_ms) VALUES ($1, $2, $3)` , key , userID , duration )
2026-09-01 08:43:25 +02:00
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 }})
}
2026-10-20 15:27:53 +00:00
const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaExists ( ctx context . Context , identifier string ) ( bool , error ) {
2026-10-20 15:27:53 +00:00
var exists bool
err := c . db . QueryRow ( ctx , `SELECT EXISTS (SELECT 1 FROM media WHERE media_key=$1 OR id=$2)` ,
identifier , mediaIDArg ( identifier )). Scan ( & exists )
return exists , err
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaLiked ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
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 })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) mediaTags ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 08:43:25 +02:00
key := strings . TrimSpace ( chi . URLParam ( r , "id" ))
2026-09-07 16:00:08 +02:00
rows , err := c . db . Query ( r . Context (), `
2026-10-19 21:46:52 +00:00
SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score
2026-09-01 08:43:25 +02:00
FROM media_tags mt LEFT JOIN media_tag_votes mv ON mv.media_key = mt.media_key AND LOWER(mv.tag) = LOWER(mt.tag)
2026-10-19 21:46:52 +00:00
WHERE mt.media_key = $1 GROUP BY mt.tag ORDER BY score DESC, LOWER(mt.tag)` , key )
2026-09-01 08:43:25 +02:00
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 })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) addMediaTag ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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" ))
2026-09-07 16:00:08 +02:00
_ , 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 )
2026-09-01 08:43:25 +02:00
if err != nil {
writeError ( w , http . StatusInternalServerError , "tag could not be added" )
return
}
writeJSON ( w , http . StatusCreated , map [ string ] any { "tag" : tag })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) voteMediaTag ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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 {
2026-09-07 16:00:08 +02:00
_ , _ = 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 )
2026-09-01 08:43:25 +02:00
} else {
2026-09-07 16:00:08 +02:00
_ , 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 )
2026-09-01 08:43:25 +02:00
if err != nil {
writeError ( w , http . StatusInternalServerError , "tag vote failed" )
return
}
}
writeJSON ( w , http . StatusOK , map [ string ] any { "tag" : tag , "vote" : input . Vote })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) tagSuggestions ( w http . ResponseWriter , r * http . Request ) {
// Without a limit every tag comes back. A NULL LIMIT is no limit in Postgres.
var limit any
if value := r . URL . Query (). Get ( "limit" ); value != "" {
limit = optionalInt ( value , 50 , 1 , math . MaxInt )
}
2026-11-13 19:23:02 +01:00
// 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 )
2026-09-01 08:43:25 +02:00
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 })
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) tagMedia ( w http . ResponseWriter , r * http . Request ) {
2026-09-01 08:43:25 +02:00
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
2026-11-01 21:48:05 +01:00
// Only media the library lists. A tag keeps its rows after its media is hidden or leaves the
// library, and a hidden item's thumbnail is not found for a viewer, so those would show as
// broken tag examples.
const libraryMedia = `FROM media_tags mt JOIN media m ON m.media_key = mt.media_key
WHERE LOWER(mt.tag) = $1 AND m.active AND m.content_scanner_processed`
var total int64
if err := c . db . QueryRow ( r . Context (), `SELECT COUNT(DISTINCT m.media_key) ` + libraryMedia , tag ). Scan ( & total ); err != nil {
writeError ( w , http . StatusInternalServerError , "tag media unavailable" )
return
}
rows , err := c . db . Query ( r . Context (), `SELECT DISTINCT m.media_key ` + libraryMedia + ` ORDER BY m.media_key LIMIT $2 OFFSET $3` , tag , limit , offset )
2026-09-01 08:43:25 +02:00
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 ))})
}
}
2026-11-01 21:48:05 +01:00
totalPages := max ( 1 , int (( total + int64 ( limit ) - 1 ) / int64 ( limit )))
pagination := map [ string ] any { "page" : pageNumber , "pageSize" : limit , "total" : total , "totalPages" : totalPages }
writeJSON ( w , http . StatusOK , map [ string ] any { "data" : items , "items" : items , "media" : items , "page" : pageNumber , "pagination" : pagination })
2026-09-01 08:43:25 +02:00
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) playlists ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) playlistSummary ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
if user == nil {
writeJSON ( w , http . StatusOK , success ( map [ string ] any { "playlists" : [] any {}}, "No playlists" ))
return
}
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) playlist ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
2026-09-07 16:00:08 +02:00
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 {
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) createPlaylist ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
}
2026-09-07 16:00:08 +02:00
_ , _ = c . db . Exec ( r . Context (), `INSERT INTO playlists (user_id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING` , user . ID , name )
2026-09-01 08:43:25 +02:00
var id int64
var created time . Time
2026-09-07 16:00:08 +02:00
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 {
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) deletePlaylist ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
id , err := strconv . ParseInt ( chi . URLParam ( r , "id" ), 10 , 64 )
if err != nil {
writeError ( w , http . StatusBadRequest , "invalid playlist id" )
return
}
2026-09-07 16:00:08 +02:00
result , err := c . db . Exec ( r . Context (), `DELETE FROM playlists WHERE id=$1 AND user_id=$2` , id , user . ID )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) playlistItems ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
2026-09-07 16:00:08 +02:00
if err := c . db . QueryRow ( r . Context (), `SELECT user_id FROM playlists WHERE id=$1` , id ). Scan ( & owner ); err != nil || owner != user . ID {
2026-09-01 08:43:25 +02:00
writeError ( w , http . StatusNotFound , "playlist not found" )
return
}
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) addPlaylistItem ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
id , err := strconv . ParseInt ( chi . URLParam ( r , "id" ), 10 , 64 )
if err != nil {
writeError ( w , http . StatusBadRequest , "invalid playlist id" )
return
}
var owner int64
2026-09-07 16:00:08 +02:00
if err := c . db . QueryRow ( r . Context (), `SELECT user_id FROM playlists WHERE id=$1` , id ). Scan ( & owner ); err != nil || owner != user . ID {
2026-09-01 08:43:25 +02:00
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
}
2026-09-07 16:00:08 +02:00
_ , err = c . db . Exec ( r . Context (), `INSERT INTO playlist_items (playlist_id, media_key) VALUES ($1, $2) ON CONFLICT DO NOTHING` , id , key )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) deletePlaylistItem ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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 ))
2026-09-07 16:00:08 +02:00
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 )
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) randomPlaylistItem ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
2026-09-07 16:00:08 +02:00
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 {
2026-09-01 08:43:25 +02:00
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" ))
}
2026-11-01 21:48:05 +01:00
func ( c * Service ) reorderPlaylist ( w http . ResponseWriter , r * http . Request ) {
2026-09-13 18:43:16 +02:00
user := sharedauth . UserFromContext ( r . Context ())
2026-09-01 08:43:25 +02:00
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
}
2026-10-19 21:46:52 +00:00
if len ( ids ) > maxPlaylistReorderItems {
writeError ( w , http . StatusBadRequest , "too many items to reorder" )
return
}
positions := make ([] int32 , len ( ids ))
for position := range ids {
positions [ position ] = int32 ( position )
}
tx , err := c . db . Begin ( r . Context ())
if err != nil {
writeError ( w , http . StatusInternalServerError , "could not reorder playlist" )
return
}
defer func () { _ = tx . Rollback ( r . Context ()) }()
if _ , err := tx . Exec ( r . Context (), `
UPDATE playlist_items AS i SET position=v.position
FROM unnest($1::bigint[], $2::int[]) AS v(item_id, position)
WHERE i.id=v.item_id AND i.playlist_id=$3
AND EXISTS (SELECT 1 FROM playlists WHERE id=$3 AND user_id=$4)` , ids , positions , id , user . ID ); err != nil {
writeError ( w , http . StatusInternalServerError , "could not reorder playlist" )
return
}
if err := tx . Commit ( r . Context ()); err != nil {
writeError ( w , http . StatusInternalServerError , "could not reorder playlist" )
return
2026-09-01 08:43:25 +02:00
}
writeJSON ( w , http . StatusOK , success ( map [ string ] any { "ok" : true }, "Playlist reordered" ))
}
2026-10-19 07:48:07 +00:00
// 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.
2026-11-01 21:48:05 +01:00
func ( c * Service ) isHiddenMedia ( ctx context . Context , identifier string ) bool {
2026-10-19 07:48:07 +00:00
var hidden bool
err := c . db . QueryRow ( ctx , `
2026-10-19 21:46:52 +00:00
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR id=$2))` ,
strings . TrimSpace ( identifier ), mediaIDArg ( strings . TrimSpace ( identifier ))). Scan ( & hidden )
2026-10-19 07:48:07 +00:00
return err != nil || hidden
}
2026-10-20 15:27:53 +00:00
// MediaLookupOptions controls which otherwise-hidden records a media lookup may return.
type MediaLookupOptions struct {
// IncludeHidden lets moderators look up media with active = FALSE.
IncludeHidden bool
// RequireContentScannerProcessed limits the result to items imported by ContentScanner.
RequireContentScannerProcessed bool
}
// FindMedia looks up one media item by media key or numeric id. Shared media routes
// preserve moderator access to hidden items; ContentScanner-backed consumers can also
// request the same processed-only filtering used by MediaViewer's library routes.
2026-11-01 21:48:05 +01:00
func ( c * Service ) FindMedia ( ctx context . Context , identifier string , options MediaLookupOptions ) ( MediaRecord , error ) {
2026-09-01 08:43:25 +02:00
identifier = strings . TrimSpace ( identifier )
var record MediaRecord
2026-09-07 16:00:08 +02:00
row := c . db . QueryRow ( ctx , `
2026-09-01 08:43:25 +02:00
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,
2026-11-13 19:23:02 +01:00
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at),
COALESCE(rating, '')
2026-10-20 15:27:53 +00:00
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 )
2026-09-01 08:43:25 +02:00
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
2026-09-01 08:43:25 +02:00
var speed float32
2026-11-13 19:23:02 +01: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 , & record . Rating ); err != nil {
2026-09-01 08:43:25 +02:00
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
}
2026-09-01 08:43:25 +02:00
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
}
2026-11-01 21:48:05 +01:00
// findMedia keeps the media routes on the same lookup implementation used by
// applications that need ContentScanner's processed-only filter.
func ( c * Service ) findMedia ( ctx context . Context , identifier string , includeHidden bool ) ( MediaRecord , error ) {
2026-10-20 15:27:53 +00:00
return c . FindMedia ( ctx , identifier , MediaLookupOptions { IncludeHidden : includeHidden })
}
2026-09-07 16:00:08 +02:00
// ToJSON is the shared wire shape for a media record, matching every
2026-11-01 21:48:05 +01:00
// media route's own response shape (id/mediaKey/filename/url/thumbnail/
2026-09-07 16:00:08 +02:00
// 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 {
2026-09-01 08:43:25 +02:00
filename := record . OriginalName
if filename == "" {
filename = filepath . Base ( urlPath ( record . FilePath ))
}
mediaType := record . MediaType
if mediaType == "unknown" || mediaType == "" {
2026-09-07 16:00:08 +02:00
mediaType = InferMediaType ( filename )
2026-09-01 08:43:25 +02:00
}
2026-11-13 19:23:02 +01:00
result := map [ string ] any {
2026-09-01 08:43:25 +02:00
"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 ),
2026-09-01 08:43:25 +02:00
"modifiedAt" : record . ModifiedAt ,
}
2026-11-13 19:23:02 +01:00
if record . Rating != "" {
result [ "rating" ] = record . Rating
}
return result
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
// --- path-safety helpers (generic, no Core dependency) ---
// 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"
2026-09-01 08:43:25 +02:00
}
}
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
}
2026-11-18 14:00:13 +01:00
// upstreamMediaPath returns the CarrierNode path for a stored file path. It reports false only when
// the stored path is not a safe relative path.
//
// url.PathEscape would write a comma as %2C, and the request then keeps that escape as a raw path.
// CarrierNode's router matches a raw path literally, so "Hello, World.mp4" would never be found. A
// URL built from Path alone leaves no raw path, so the name reaches CarrierNode decoded. Query and
// fragment markers are escaped the same way, so they no longer need refusing.
2026-10-19 21:46:52 +00:00
func upstreamMediaPath ( filePath string ) ( string , bool ) {
relative := urlPath ( filePath )
2026-11-18 14:00:13 +01:00
if ! files . SafeRelative ( relative ) {
2026-10-19 21:46:52 +00:00
return "" , false
}
2026-11-18 14:00:13 +01:00
return ( & url . URL { Path : relative }). EscapedPath (), true
2026-10-19 21:46:52 +00:00
}
// canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs
// and whitespace are not canonical, so they never match an id.
func canonicalMediaID ( identifier string ) ( int64 , bool ) {
if identifier == "" || strings . Trim ( identifier , "0123456789" ) != "" {
return 0 , false
}
id , err := strconv . ParseInt ( identifier , 10 , 64 )
if err != nil || strconv . FormatInt ( id , 10 ) != identifier {
return 0 , false
}
return id , true
}
// mediaIDArg is the id query argument for identifier: the id when identifier is a canonical number,
// otherwise NULL, which matches no row. Comparing the id column directly, instead of casting it to
// text, lets the planner use the primary-key index for the id arm.
func mediaIDArg ( identifier string ) any {
if id , ok := canonicalMediaID ( identifier ); ok {
return id
}
return nil
}
2026-09-01 08:43:25 +02:00
func firstNonEmpty ( values ... string ) string {
for _ , value := range values {
if strings . TrimSpace ( value ) != "" {
return value
}
}
return ""
}
2026-09-07 16:00:08 +02:00
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 })
}