package server import ( "context" "encoding/json" "errors" "fmt" "io" "mime" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "time" "github.com/go-chi/chi/v5" "mediacollection/internal/auth" ) func (s *Server) mountSharedRoutes(r chi.Router) { r.With(s.auth.Require).Get("/security/totp/status", s.auth.TOTPStatus) r.With(s.auth.Require).Get("/security/totp/initiate", s.auth.TOTPInitiate) r.With(s.auth.Require).Post("/security/totp/verify", s.auth.TOTPVerify) r.With(s.auth.Require).Post("/security/totp/disable", s.auth.TOTPDisable) r.With(s.auth.Optional).Get("/sync", s.getSyncState) r.With(s.auth.Optional).Put("/sync", s.putSyncState) r.With(s.auth.Optional).Get("/media/state", s.mediaState) r.With(s.auth.Require).Post("/media/like", s.mediaLike) r.With(s.auth.Require).Post("/media/save", s.mediaSave) r.With(s.auth.Optional).Post("/media/view", s.mediaView) r.With(s.auth.Optional).Post("/media/view-session", s.mediaViewSession) r.With(s.auth.Require).Get("/media/liked", s.mediaLiked) r.Get("/media/stream", s.streamMediaByQuery) r.Head("/media/stream", s.streamMediaByQuery) r.Get("/media/thumb", s.thumbnailMediaByQuery) r.With(s.auth.Optional).Get("/media/{id}/tags", s.mediaTags) r.With(s.auth.Require).Post("/media/{id}/tags", s.addMediaTag) r.With(s.auth.Require).Post("/media/{id}/tags/{tag}/vote", s.voteMediaTag) r.Get("/tags/suggestions", s.tagSuggestions) r.Get("/tags/{tag}/media", s.tagMedia) r.With(s.auth.Require).Get("/playlists", s.playlists) r.With(s.auth.Optional).Get("/playlists/summary", s.playlistSummary) r.With(s.auth.Optional).Get("/playlists/{id}", s.playlist) r.With(s.auth.Require).Post("/playlists", s.createPlaylist) r.With(s.auth.Require).Delete("/playlists/{id}", s.deletePlaylist) r.With(s.auth.Optional).Get("/playlists/{id}/items", s.playlistItems) r.With(s.auth.Require).Post("/playlists/{id}/items", s.addPlaylistItem) r.With(s.auth.Require).Delete("/playlists/{id}/items", s.deletePlaylistItem) r.With(s.auth.Optional).Get("/playlists/{id}/random", s.randomPlaylistItem) r.With(s.auth.Require).Patch("/playlists/{id}/items/reorder", s.reorderPlaylist) r.With(s.auth.Optional).Get("/profile", s.profile) } func (s *Server) getSyncState(w http.ResponseWriter, r *http.Request) { sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default")) writeJSON(w, http.StatusOK, s.sync.httpState(sessionID)) } func (s *Server) 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 } sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default")) state := map[string]any{ "sessionId": sessionID, "mediaId": input["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 { state["playAt"] = value } s.sync.setHTTPState(sessionID, state) s.sync.broadcast(sessionID) writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state}) } func (s *Server) mountViewerRoutes(r chi.Router) { r.Get("/media", s.listMedia) r.Get("/media/random", s.randomMedia) r.Get("/media/random/{category}", s.randomMedia) r.Get("/media/{id}/stream", s.streamMedia) r.Head("/media/{id}/stream", s.streamMedia) r.Get("/media/{id}/thumb", s.thumbnailMedia) r.Get("/media/{id}/funscript", s.funscriptMedia) r.Get("/media/{id}/fileinfo", s.mediaFileInfo) r.Get("/media/{id}/probe", s.probeMedia) r.Get("/library/unified", s.unifiedLibrary) r.Get("/routes", s.mediaRoutes) r.Get("/categories", s.mediaCategories) } func (s *Server) listMedia(w http.ResponseWriter, r *http.Request) { pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000) pageSize := optionalInt(firstNonEmpty(r.URL.Query().Get("pageSize"), r.URL.Query().Get("limit")), 24, 1, 100) search := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("q"), r.URL.Query().Get("search"))) conditions := []string{"active = TRUE"} args := make([]any, 0, 10) add := func(value any) string { args = append(args, value) return "$" + strconv.Itoa(len(args)) } if search != "" { placeholder := add("%" + search + "%") conditions = append(conditions, "(media_key ILIKE "+placeholder+" OR COALESCE(title, '') ILIKE "+placeholder+" OR COALESCE(original_filename, '') ILIKE "+placeholder+" OR COALESCE(file_path, '') ILIKE "+placeholder+")") } if value := r.URL.Query().Get("minHeight"); value != "" { if height, err := strconv.Atoi(value); err == nil && height > 0 { conditions = append(conditions, "COALESCE(height, 0) >= "+add(height)) } } for key, expression := range map[string]string{"isVr": "is_vr", "hasFunscript": "has_funscript"} { if value := boolQuery(r.URL.Query().Get(key)); value != nil { conditions = append(conditions, expression+" = "+add(*value)) } } if value := r.URL.Query().Get("minDurationSec"); value != "" { if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 { conditions = append(conditions, "COALESCE(duration_ms, 0) >= "+add(seconds*1000)) } } if value := r.URL.Query().Get("maxDurationSec"); value != "" { if seconds, err := strconv.ParseInt(value, 10, 64); err == nil && seconds >= 0 { conditions = append(conditions, "COALESCE(duration_ms, 0) <= "+add(seconds*1000)) } } if value := r.URL.Query().Get("minSpeed"); value != "" { if speed, err := strconv.ParseFloat(value, 32); err == nil && speed >= 0 { conditions = append(conditions, "COALESCE(speed, 0) >= "+add(float32(speed))) } } if value := r.URL.Query().Get("maxSpeed"); value != "" { if speed, err := strconv.ParseFloat(value, 32); err == nil && speed >= 0 { conditions = append(conditions, "COALESCE(speed, 0) <= "+add(float32(speed))) } } where := strings.Join(conditions, " AND ") var total int64 if err := s.db.QueryRow(r.Context(), "SELECT COUNT(*) FROM media WHERE "+where, args...).Scan(&total); err != nil { writeError(w, http.StatusInternalServerError, "media count unavailable") return } sortColumn := "modified_at" switch r.URL.Query().Get("sortBy") { case "created": sortColumn = "created_at" case "title": sortColumn = "LOWER(COALESCE(title, original_filename, media_key))" } sortDirection := "DESC" if strings.EqualFold(r.URL.Query().Get("sortDir"), "asc") { sortDirection = "ASC" } limitPlaceholder := add(pageSize) offsetPlaceholder := add((pageNumber - 1) * pageSize) query := fmt.Sprintf(` 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), COALESCE(speed, 0), COALESCE(modified_at, created_at) FROM media WHERE %s ORDER BY %s %s, id DESC LIMIT %s OFFSET %s`, where, sortColumn, sortDirection, limitPlaceholder, offsetPlaceholder) rows, err := s.db.Query(r.Context(), query, args...) if err != nil { writeError(w, http.StatusInternalServerError, "media list unavailable") return } defer rows.Close() items := make([]map[string]any, 0, pageSize) for rows.Next() { record, err := scanMedia(rows) if err != nil { writeError(w, http.StatusInternalServerError, "media record unavailable") return } items = append(items, record.toJSON()) } writeJSON(w, http.StatusOK, map[string]any{"items": items, "total": total, "page": pageNumber, "pageSize": pageSize}) } func (s *Server) randomMedia(w http.ResponseWriter, r *http.Request) { exact := strings.TrimSpace(r.URL.Query().Get("exact")) query := ` 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), COALESCE(speed, 0), COALESCE(modified_at, created_at) FROM media WHERE active = TRUE` args := []any{} if exact != "" { query += ` AND (media_key = $1 OR CAST(id AS TEXT) = $1) LIMIT 1` args = append(args, exact) } else { query += ` ORDER BY RANDOM() LIMIT 1` } rows, err := s.db.Query(r.Context(), query, args...) if err != nil { writeError(w, http.StatusInternalServerError, "random media unavailable") return } defer rows.Close() if !rows.Next() { writeJSON(w, http.StatusNotFound, map[string]any{"data": nil, "error": "no media found"}) return } record, err := scanMedia(rows) if err != nil { writeError(w, http.StatusInternalServerError, "random media unavailable") return } item := record.toJSON() writeJSON(w, http.StatusOK, map[string]any{"data": item, "item": item}) } func (s *Server) streamMedia(w http.ResponseWriter, r *http.Request) { s.streamMediaIdentifier(w, r, chi.URLParam(r, "id")) } func (s *Server) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { s.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } func (s *Server) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { record, err := s.findMedia(r.Context(), identifier) if err != nil { writeError(w, http.StatusNotFound, "media not found") return } s.proxyServant(w, r, "/media/"+urlPath(record.FilePath)) } func (s *Server) thumbnailMedia(w http.ResponseWriter, r *http.Request) { s.thumbnailMediaIdentifier(w, r, chi.URLParam(r, "id")) } func (s *Server) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { s.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { id := identifier if !safeRelative(id) { writeError(w, http.StatusBadRequest, "invalid media id") return } if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") { thumbnailPath := "/thumbnails/" + id + ".jpg" if exists, _, _, err := s.probeServant(r.Context(), thumbnailPath); err == nil && exists { s.proxyServant(w, r, thumbnailPath) return } } record, err := s.findMedia(r.Context(), id) if err != nil || !isImagePath(record.FilePath) { writeError(w, http.StatusNotFound, "thumbnail not found") return } s.proxyServant(w, r, "/media/"+urlPath(record.FilePath)) } func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) { record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) if err != nil { writeError(w, http.StatusNotFound, "media not found") return } base := strings.TrimSuffix(record.FilePath, filepath.Ext(record.FilePath)) for _, candidate := range []string{base + ".funscript", base + ".json"} { candidatePath := "/media/" + urlPath(candidate) if exists, _, _, err := s.probeServant(r.Context(), candidatePath); err == nil && exists { s.proxyServant(w, r, candidatePath) return } } writeError(w, http.StatusNotFound, "funscript not found") } func (s *Server) mediaFileInfo(w http.ResponseWriter, r *http.Request) { record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) if err != nil { writeError(w, http.StatusNotFound, "media not found") return } response := record.toJSON() if exists, size, modTime, err := s.probeServant(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists { response["absolutePath"] = "" response["sizeBytes"] = size response["modifiedAt"] = modTime } writeJSON(w, http.StatusOK, response) } func (s *Server) probeMedia(w http.ResponseWriter, r *http.Request) { record, err := s.findMedia(r.Context(), chi.URLParam(r, "id")) if err != nil { writeError(w, http.StatusNotFound, "media not found") return } writeJSON(w, http.StatusOK, map[string]any{"ok": true, "media": record.toJSON()}) } func (s *Server) unifiedLibrary(w http.ResponseWriter, r *http.Request) { s.listMedia(w, r) } func (s *Server) mediaRoutes(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"routes": []string{"/", "/feed", "/tags", "/playlists"}}) } func (s *Server) mediaCategories(w http.ResponseWriter, r *http.Request) { rows, err := s.db.Query(r.Context(), `SELECT DISTINCT COALESCE(category, '') FROM media WHERE active = TRUE AND COALESCE(category, '') <> '' ORDER BY 1`) if err != nil { writeError(w, http.StatusInternalServerError, "categories unavailable") return } defer rows.Close() categories := make([]string, 0) for rows.Next() { var category string if rows.Scan(&category) == nil { categories = append(categories, category) } } writeJSON(w, http.StatusOK, map[string]any{"categories": categories}) } func (s *Server) 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 := auth.UserFromContext(r.Context()) var likes, saves, views int64 if err := s.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 } _ = s.db.QueryRow(r.Context(), `SELECT COUNT(*) FROM media_stats WHERE media_key = $1 AND stat_type = 'save'`, key).Scan(&saves) _ = s.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 { _ = s.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) _ = s.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 (s *Server) mediaLike(w http.ResponseWriter, r *http.Request) { s.mediaStatMutation(w, r, "like") } func (s *Server) mediaSave(w http.ResponseWriter, r *http.Request) { s.mediaStatMutation(w, r, "save") } func (s *Server) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { user := auth.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 := s.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, s.cfg.ServiceName) if err != nil { writeError(w, http.StatusInternalServerError, "media state update failed") return } } else { _, _ = s.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 (s *Server) mediaView(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.db.Exec(r.Context(), `INSERT INTO media_stats (media_key, user_id, stat_type, app) VALUES ($1, $2, 'view', $3)`, key, userID, s.cfg.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 (s *Server) mediaViewSession(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) mediaLiked(w http.ResponseWriter, r *http.Request) { user := auth.UserFromContext(r.Context()) rows, err := s.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 (s *Server) mediaTags(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(chi.URLParam(r, "id")) rows, err := s.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 (s *Server) addMediaTag(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) voteMediaTag(w http.ResponseWriter, r *http.Request) { user := auth.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 { _, _ = s.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 := s.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 (s *Server) tagSuggestions(w http.ResponseWriter, r *http.Request) { limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 1000) rows, err := s.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 (s *Server) 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 := s.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 (s *Server) playlists(w http.ResponseWriter, r *http.Request) { user := auth.UserFromContext(r.Context()) rows, err := s.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 (s *Server) playlistSummary(w http.ResponseWriter, r *http.Request) { user := auth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists")) return } rows, err := s.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 (s *Server) playlist(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) createPlaylist(w http.ResponseWriter, r *http.Request) { user := auth.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 } _, _ = s.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 := s.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 (s *Server) deletePlaylist(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) playlistItems(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 := s.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 (s *Server) addPlaylistItem(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 = s.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 (s *Server) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { user := auth.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 := s.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 (s *Server) reorderPlaylist(w http.ResponseWriter, r *http.Request) { user := auth.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 { _, _ = s.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 (s *Server) profile(w http.ResponseWriter, r *http.Request) { user := auth.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}) } func (s *Server) findMedia(ctx context.Context, identifier string) (MediaRecord, error) { identifier = strings.TrimSpace(identifier) var record MediaRecord row := s.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), COALESCE(speed, 0), COALESCE(modified_at, created_at) FROM media WHERE media_key=$1 OR CAST(id AS TEXT)=$1 LIMIT 1`, identifier) var title, description string var width, height int var duration, size int64 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, &speed, &record.ModifiedAt); err != nil { return MediaRecord{}, err } 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 } type rowScanner interface{ Scan(dest ...any) error } func scanMedia(row rowScanner) (MediaRecord, error) { var record MediaRecord var title, description string var width, height int var duration, size int64 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, &speed, &record.ModifiedAt); err != nil { return record, err } 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 } 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), "modifiedAt": record.ModifiedAt, } } func (s *Server) resolveMediaPath(ctx context.Context, relative string) (string, error) { return s.resolveUnderRoots(relative, s.effectiveMediaRoots(ctx)) } // resolveAnyMediaPath additionally checks DownloadsRoot and OutputRoot - the mirror image of // mediaKeyForPath, which computes a key relative to whichever of those roots a file lives under. func (s *Server) resolveAnyMediaPath(ctx context.Context, relative string) (string, error) { roots := append(s.effectiveMediaRoots(ctx), s.cfg.DownloadsRoot, s.cfg.OutputRoot) return s.resolveUnderRoots(relative, roots) } func (s *Server) resolveThumbnailPath(relative string) (string, error) { return s.resolveUnderRoots(relative, []string{s.cfg.ThumbnailRoot}) } func (s *Server) 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 } func (s *Server) 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) } 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 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, `..\`) } 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) } 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) } 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 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 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 "" }