// 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. // // A service wires this up as: // // svc := media.New(media.Config{ // DB: pool, // Auth: authService, // CarrierNode: carrierNodeClient, // ServiceName: "CarrierNode", // cfg.ServiceName // }) // if err := svc.Migrate(ctx); err != nil { ... } // router.Route("/api", func(r chi.Router) { // svc.Mount(r) // // ... the service's own routes ... // }) package media import ( "context" "encoding/json" "io" "math" "net/http" "net/url" "path/filepath" "strconv" "strings" "time" "github.com/go-chi/chi/v5" "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/files" ) // 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 // Config wires a Service to the rest of one service's dependencies. type Config struct { DB *pgxpool.Pool Auth *sharedauth.Service 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 } // Service mounts the shared media routes and holds what they need to run. type Service struct { db *pgxpool.Pool auth *sharedauth.Service carrierNode *carriernodeclient.Client serviceName string } // 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} } // 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) { 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) } // MediaRecord is one row of the shared `media` table. type MediaRecord struct { 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 *Service) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } func (c *Service) 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 } upstream, ok := upstreamMediaPath(record.FilePath) if !ok { writeError(w, http.StatusNotFound, "media not found") return } c.carrierNode.Proxy(w, r, "/media/"+upstream) } func (c *Service) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } func (c *Service) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { id := identifier if !files.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 } } 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 m.id=$2 ORDER BY t.created_at DESC LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && files.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 } } record, err := c.findMedia(r.Context(), id, includeHidden) if err != nil || !isImagePath(record.FilePath) { writeError(w, http.StatusNotFound, "thumbnail not found") return } upstream, ok := upstreamMediaPath(record.FilePath) if !ok { writeError(w, http.StatusNotFound, "thumbnail not found") return } c.carrierNode.Proxy(w, r, "/media/"+upstream) } func (c *Service) 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 *Service) mediaLike(w http.ResponseWriter, r *http.Request) { c.mediaStatMutation(w, r, "like") } func (c *Service) mediaSave(w http.ResponseWriter, r *http.Request) { c.mediaStatMutation(w, r, "save") } func (c *Service) 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 *Service) 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 { if err := decodeRequestJSON(r, &input); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } } key := strings.TrimSpace(firstNonEmpty(input.MediaKey, r.URL.Query().Get("mediaKey"))) if key == "" { writeError(w, http.StatusBadRequest, "missing mediaKey") 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") 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 *Service) 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 } 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") 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)`, key, 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}}) } const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000 func (c *Service) mediaExists(ctx context.Context, identifier string) (bool, error) { 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 } func (c *Service) 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 *Service) mediaTags(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(chi.URLParam(r, "id")) rows, err := c.db.Query(r.Context(), ` SELECT mt.tag, COALESCE(SUM(mv.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 mt.tag ORDER BY score DESC, LOWER(mt.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 *Service) 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 *Service) 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 *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) } 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 *Service) 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 // 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) 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))}) } } 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}) } func (c *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 *Service) 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 } 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 } writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered")) } // 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 *Service) 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 id=$2))`, strings.TrimSpace(identifier), mediaIDArg(strings.TrimSpace(identifier))).Scan(&hidden) return err != nil || hidden } // 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. func (c *Service) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (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), 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 id=$2) AND (active OR $3) AND (NOT $4 OR content_scanner_processed) LIMIT 1`, identifier, mediaIDArg(identifier), options.IncludeHidden, options.RequireContentScannerProcessed) var title, description string var width, height int var duration, size int64 var funscriptActionCount pgtype.Int4 var funscriptAvgSpeed, funscriptMaxSpeed pgtype.Float4 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 { return MediaRecord{}, err } 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 } // 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) { return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden}) } // ToJSON is the shared wire shape for a media record, matching every // media 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), "funscriptActionCount": intValue(record.FunscriptActionCount), "funscriptAvgSpeed": floatValue(record.FunscriptAvgSpeed), "funscriptMaxSpeed": floatValue(record.FunscriptMaxSpeed), "modifiedAt": record.ModifiedAt, } } // --- 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" } } 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 } // upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false // when the stored path is not a safe relative path, or when it contains a query or fragment marker // that CarrierNode would read as the end of the path. func upstreamMediaPath(filePath string) (string, bool) { relative := urlPath(filePath) if !files.SafeRelative(relative) || strings.ContainsAny(relative, "?#") { return "", false } // Escape each segment so percent-escapes and other reserved characters in a stored name // reach CarrierNode as literal text, not as an escape or a traversal it decodes later. segments := strings.Split(relative, "/") for i, segment := range segments { segments[i] = url.PathEscape(segment) } return strings.Join(segments, "/"), true } // 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 } 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}) }