diff --git a/.gitignore b/.gitignore index b791477..a6853c5 100644 --- a/.gitignore +++ b/.gitignore @@ -52,3 +52,4 @@ server/server server/main __debug_bin* gpt*.txt +screenlog.* diff --git a/server/handler.go b/server/handler.go index b2a8bd9..7719143 100644 --- a/server/handler.go +++ b/server/handler.go @@ -10,61 +10,88 @@ import ( // MovieList 电影列表 func MovieList(c *gin.Context) { - - data := gin.H{} response := gin.H{ "code": http.StatusInternalServerError, - "message": "", - "data": data, + "message": "An unexpected error occurred.", // Default error message + "data": gin.H{"items": []Movie{}, "total": 0}, } - defer c.JSON(0, response) - category := c.Query("category") + categoryName := c.Query("category") // Expects category name like "15min", "30min", etc. - var movies []Movie - if category != "" { - cateidx, err := strconv.Atoi(category) - if err != nil { - log.Println(err) - return + var moviesToPaginate []Movie + + // Filter movies by category if a categoryName is provided + if categoryName != "" { + for _, m := range movies { // 'movies' is the global slice from initMovie() + if m.TimeCategory == categoryName { + moviesToPaginate = append(moviesToPaginate, m) + } } - movies = categories[cateidx].Movies + } else { + // If no category is specified, use all movies + // The global 'movies' slice is already sorted by category, then duration. + // So, if no category is given, pagination will occur over this pre-sorted list. + moviesToPaginate = movies } - var page int = 0 + // Pagination logic + page := 0 // Default to page 1 (0-indexed internally) spage := c.Query("page") if spage != "" { p, err := strconv.Atoi(spage) - if err != nil { - log.Println(err) + if err != nil || p < 1 { // Page numbers should be 1 or greater + log.Println("Invalid page number:", spage, err) + response["code"] = http.StatusBadRequest + response["message"] = "Invalid page number. Must be a positive integer." + c.JSON(http.StatusBadRequest, response) // Send response immediately for bad input return } - page = p - 1 + page = p - 1 // Convert to 0-indexed } - var limit int = 12 + limit := 12 // Default limit slimit := c.Query("limit") if slimit != "" { l, err := strconv.Atoi(slimit) - if err != nil { - log.Println(err) + if err != nil || l < 1 { // Limit should be positive + log.Println("Invalid limit number:", slimit, err) + response["code"] = http.StatusBadRequest + response["message"] = "Invalid limit number. Must be a positive integer." + c.JSON(http.StatusBadRequest, response) // Send response immediately return } limit = l } + // Calculate start and end for slicing start := page * limit - var end int = start + limit + end := start + limit - if start > len(movies) { - start = len(movies) + // Handle cases where the requested page is out of bounds + if start >= len(moviesToPaginate) { + // Requested page is beyond the available data, return empty list for items + response["data"] = gin.H{ + "items": []Movie{}, + "total": len(moviesToPaginate), + } + response["code"] = http.StatusOK + response["message"] = "Success" + c.JSON(http.StatusOK, response) + return } - if end > len(movies) { - end = len(movies) + + if end > len(moviesToPaginate) { + end = len(moviesToPaginate) + } + + // Prepare successful response data + responseData := gin.H{ + "items": moviesToPaginate[start:end], + "total": len(moviesToPaginate), } response["code"] = http.StatusOK - - data["items"] = movies[start:end] - data["total"] = len(movies) + response["message"] = "Success" + response["data"] = responseData + c.JSON(http.StatusOK, response) } diff --git a/server/movie.go b/server/movie.go index b24808f..267ad85 100644 --- a/server/movie.go +++ b/server/movie.go @@ -7,148 +7,234 @@ import ( "log" "os/exec" "path/filepath" + "regexp" "sort" "strconv" "strings" ) -// Category 电影分类结构 -type Category struct { - Name string `json:"name"` - Movies []Movie `json:"movies"` -} - // Movie 电影结构 type Movie struct { - Name string `json:"filename"` - Image string `json:"image"` - Duration int `json:"duration"` + Name string `json:"filename"` // Original filename of the movie, e.g., "video1.mp4" + Image string `json:"image"` // Corresponding image filename, e.g., "video1.png" + Duration int `json:"duration"` // Duration in minutes + TimeCategory string `json:"time_category"` // 分类名称, e.g., "15min", "30min" + VideoPath string `json:"-"` // Full path to the video file, used for ffmpeg } -// var movies []Movie -var categories []Category +var movies []Movie // This will store all movies -var IsRemakePNG = false +var IsRemakePNG = false // Set to true to regenerate all PNGs + +func getVideoDuration(videoPath string) (float64, error) { + // 使用ffmpeg获取视频信息 + cmd := exec.Command("ffmpeg", "-i", videoPath) + var stderr bytes.Buffer + cmd.Stderr = &stderr + _ = cmd.Run() // 忽略错误,因为ffmpeg在没有输出文件时会返回错误 + + // 解析ffmpeg输出的时长信息 + output := stderr.String() + re := regexp.MustCompile(`Duration: (\d{2}):(\d{2}):(\d{2}\.\d{2})`) + matches := re.FindStringSubmatch(output) + if len(matches) < 4 { + // Try to find duration even if format is slightly different (e.g. no milliseconds) + reAlt := regexp.MustCompile(`Duration: (\d{2}):(\d{2}):(\d{2})`) + matches = reAlt.FindStringSubmatch(output) + if len(matches) < 4 { + return 0, fmt.Errorf("duration not found in ffmpeg output for %s. Output: %s", filepath.Base(videoPath), output) + } + // Add .00 for consistency if seconds has no decimal part + matches[3] += ".00" + } + + // 将时间转换为秒 + hours, errH := strconv.ParseFloat(matches[1], 64) + minutes, errM := strconv.ParseFloat(matches[2], 64) + seconds, errS := strconv.ParseFloat(matches[3], 64) + + if errH != nil || errM != nil || errS != nil { + return 0, fmt.Errorf("error parsing time components from ffmpeg output: %v, %v, %v", errH, errM, errS) + } + + duration := hours*3600 + minutes*60 + seconds + return duration, nil +} func initMovie() { - // 需要改进 如果存在这个文件的略缩图, 就不存进movieDict里 + // movieDict stores movies for which thumbnails might need to be generated. + // Key: base filename without extension (e.g., "video1") + // Value: *Movie object (initially with Name as full path to video, Duration updated later) var movieDict map[string]*Movie = make(map[string]*Movie) - matches, err := filepath.Glob("movie/*") + // Glob for all files in "movie/" directory to check for existing PNGs + allFiles, err := filepath.Glob("movie/*") if err != nil { - log.Println(err) + log.Printf("Error globbing movie directory: %v", err) + // Decide if you want to return or continue with an empty list } - for _, filename := range matches { - base := filepath.Base(filename) + // This loop is to determine which videos need thumbnails. + // If a video `video.mp4` exists but `video.png` also exists, + // `video.mp4` is removed from `movieDict` unless `IsRemakePNG` is true. + for _, fullPath := range allFiles { + baseWithExt := filepath.Base(fullPath) + ext := filepath.Ext(baseWithExt) + baseName := strings.TrimSuffix(baseWithExt, ext) // Filename without extension - // ext := filepath.Ext(base) - base = base[:strings.IndexByte(base, '.')] - - if _, ok := movieDict[base]; ok { - if !IsRemakePNG { - delete(movieDict, base) + if ext == ".png" { + // If it's a PNG, check if its corresponding video is in the dict + if movieEntry, ok := movieDict[baseName]; ok { + if !IsRemakePNG { + // PNG exists and we are not remaking, so remove video from thumbnail generation list + log.Printf("Thumbnail %s already exists. Skipping generation for %s.", baseWithExt, movieEntry.VideoPath) + delete(movieDict, baseName) + } } - } else { - movieDict[base] = &Movie{Name: filename} + } else if ext != "" && ext != ".db" { // Assume other non-empty extensions are videos + // If it's a video file (or any non-PNG, non-empty extension file) + if _, ok := movieDict[baseName]; !ok { + // If not already processed (e.g. by a .png file check) and not forced remake + movieDict[baseName] = &Movie{VideoPath: fullPath} // Store full path for ffmpeg + } else if IsRemakePNG { + // If it was already there (e.g. from a PNG that we decided to remake), ensure VideoPath is set + movieDict[baseName].VideoPath = fullPath + } + } + } + + // Reset the global movies slice + movies = []Movie{} + + // Walk through the movie directory to process video files + err = filepath.WalkDir("./movie", func(path string, d fs.DirEntry, err error) error { + if err != nil { + log.Printf("Error accessing path %q: %v\n", path, err) + return err + } + if d.IsDir() || filepath.Ext(d.Name()) == ".png" || filepath.Ext(d.Name()) == ".db" { // Skip directories, PNGs, and DB files + return nil } - } + videoFileName := d.Name() // e.g., "video1.mp4" + baseNameWithoutExt := strings.TrimSuffix(videoFileName, filepath.Ext(videoFileName)) - // 初始化分类 - categories = []Category{ - {Name: "15min", Movies: []Movie{}}, - {Name: "30min", Movies: []Movie{}}, - {Name: "60min", Movies: []Movie{}}, - {Name: "大于60min", Movies: []Movie{}}, - } + durationSec, err := getVideoDuration(path) + if err != nil { + // log.Printf("Error getting duration for %s: %v. Skipping this file.", videoFileName, err) + // Remove from movieDict if it was there, as we can't process it + delete(movieDict, baseNameWithoutExt) + return nil // Continue with next file + } - filepath.Walk("./movie", func(path string, info fs.FileInfo, err error) error { - if !info.IsDir() && filepath.Ext(info.Name()) != ".png" { - base := info.Name() - cmd := exec.Command("ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=duration", "-of", "default=nw=1:nk=1", "./movie/"+info.Name()) - durationOutput, err := cmd.Output() - if err != nil { - log.Printf("Error getting duration for %s: %v", info.Name(), err) - return err - } + durationMin := int(durationSec / 60.0) - duration, err := strconv.ParseFloat(strings.Trim(string(durationOutput), "\n "), 64) - if err != nil { - log.Printf("Error parsing duration for %s: %v", info.Name(), err) - return err - } - // log.Println(path, info.Name()) + var timeCat string + if durationMin <= 15 { + timeCat = "15min" + } else if durationMin <= 30 { + timeCat = "30min" + } else if durationMin <= 60 { + timeCat = "60min" + } else { + timeCat = "大于60min" + } - movie := Movie{ - Name: info.Name(), - Image: base[:strings.IndexByte(base, '.')] + ".png", - Duration: int(duration / 60.0), - } - - if m, ok := movieDict[base[:strings.IndexByte(base, '.')]]; ok { - m.Duration = movie.Duration - } - - if movie.Duration <= 15 { - categories[0].Movies = append(categories[0].Movies, movie) - } else if movie.Duration <= 30 { - categories[1].Movies = append(categories[1].Movies, movie) - } else if movie.Duration <= 60 { - categories[2].Movies = append(categories[2].Movies, movie) - } else { - categories[3].Movies = append(categories[3].Movies, movie) - } + movie := Movie{ + Name: videoFileName, + Image: baseNameWithoutExt + ".png", + Duration: durationMin, + TimeCategory: timeCat, + VideoPath: path, // Store full path + } + movies = append(movies, movie) + // If this movie base name is in movieDict (meaning it needs/might need a thumbnail), + // update its duration. + if mEntry, ok := movieDict[baseNameWithoutExt]; ok { + mEntry.Duration = movie.Duration // Update duration for thumbnail filter logic + // Ensure VideoPath in movieDict is the one we just processed (it should be) + mEntry.VideoPath = path + mEntry.Name = movie.Name // Also update Name for logging in thumbnail part } return nil }) - for _, category := range categories { - var movies = category.Movies - sort.Slice(movies, func(i, j int) bool { - return movies[i].Duration < movies[j].Duration - }) + if err != nil { + log.Printf("Error walking the path ./movie: %v\n", err) } - for key, movie := range movieDict { - // width := 160 - // height := 120 - // if movie.Duration <= 40 { - // continue - // } + // Sort the global movies list. + // First by custom time category order, then by duration within that category. + categoryOrderMap := map[string]int{ + "15min": 0, + "30min": 1, + "60min": 2, + "大于60min": 3, + } + + sort.Slice(movies, func(i, j int) bool { + catOrderI := categoryOrderMap[movies[i].TimeCategory] + catOrderJ := categoryOrderMap[movies[j].TimeCategory] + + if catOrderI != catOrderJ { + return catOrderI < catOrderJ + } + return movies[i].Duration < movies[j].Duration + }) + + // Generate thumbnails for movies in movieDict + // These are the movies for which PNGs didn't exist or IsRemakePNG is true + for key, movieToProcess := range movieDict { + if movieToProcess.VideoPath == "" { + // log.Printf("Skipping thumbnail for %s, VideoPath is empty (likely only PNG found and no corresponding video processed).", key) + continue + } + // movieToProcess.Duration should have been updated by the WalkDir logic. + // If a video was in movieDict but not found/processed by WalkDir, its Duration might be 0. + if movieToProcess.Duration == 0 && movieToProcess.Name != "" { // Name check to avoid new entries + // Try to get duration again if it's missing, might happen if it was added to dict but WalkDir failed for it + // Or if the logic for updating movieDict was missed for some edge case. + // For simplicity, we assume duration is now correctly populated from WalkDir pass. + log.Printf("Warning: Duration for %s (path: %s) is 0, thumbnail filter might be suboptimal.", movieToProcess.Name, movieToProcess.VideoPath) + } + + log.Printf("Generating thumbnail for: %s (Duration: %d min, Path: %s)", movieToProcess.Name, movieToProcess.Duration, movieToProcess.VideoPath) - log.Println(movie.Name, "时长:", movie.Duration) var filter string - - if movie.Duration <= 2 { + // Use movieToProcess.Duration for filter logic + if movieToProcess.Duration <= 2 { filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,5)',scale=320:180,tile=3x3" - } else if movie.Duration <= 5 { + } else if movieToProcess.Duration <= 5 { filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,10)',scale=320:180,tile=3x3" - } else if movie.Duration <= 30 { + } else if movieToProcess.Duration <= 30 { filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,20)',scale=320:180,tile=3x3" - } else if movie.Duration <= 60 { + } else if movieToProcess.Duration <= 60 { filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,35)',scale=320:180,tile=3x3" - } else { + } else { // duration > 60 filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,60)',scale=320:180,tile=3x3" } + outputImagePath := filepath.Join("movie", key+".png") + cmd := exec.Command("ffmpeg", - "-i", movie.Name, + "-i", movieToProcess.VideoPath, // Use full path to video "-vf", filter, "-frames:v", "1", - "-y", - "movie/"+key+".png", + "-q:v", "3", // Quality for JPEG/PNG, usually 2-5 is good for -qscale:v + "-y", // Overwrite output files without asking + outputImagePath, ) - var buffer bytes.Buffer - cmd.Stdout = &buffer - if cmd.Run() != nil { - log.Println(buffer.String()) - panic(fmt.Errorf("could not generate frame %s %d", movie.Name, movie.Duration)) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + log.Printf("Error generating thumbnail for %s (Duration: %d min): %v\nStderr: %s", + movieToProcess.VideoPath, movieToProcess.Duration, err, stderr.String()) + // Consider whether to panic or just log + // panic(fmt.Errorf("could not generate frame %s %d. Error: %v. Stderr: %s", movieToProcess.VideoPath, movieToProcess.Duration, err, stderr.String())) + } else { + log.Printf("Successfully generated thumbnail: %s", outputImagePath) } - } - - // log.Printf("%##v", categories) } diff --git a/src/Main.jsx b/src/Main.jsx index 59280df..c007ad0 100644 --- a/src/Main.jsx +++ b/src/Main.jsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useContext, useCallback } from 'react'; +import React, { useState, useEffect, useContext, useCallback, useRef } from 'react'; import axios from 'axios'; import Container from '@mui/material/Container'; import Grid from '@mui/material/Grid'; @@ -10,195 +10,201 @@ import ConfigContext from './Config'; import MovieCard from './components/MovieCard'; import CategoryNav from './components/CategoryNav'; +const categories = [ + { label: '15min', value: '15min' }, + { label: '30min', value: '30min' }, + { label: '60min', value: '60min' }, + { label: '大于60min', value: '大于60min' }, +]; + +const LIMIT = 20; + +const usePersistedState = (key, defaultValue) => { + const [state, setState] = useState(() => { + const stored = localStorage.getItem(key); + return stored ? JSON.parse(stored) : defaultValue; + }); + + useEffect(() => { + localStorage.setItem(key, JSON.stringify(state)); + }, [key, state]); + + return [state, setState]; +}; + const Main = () => { const config = useContext(ConfigContext); const [loading, setLoading] = useState(false); - const categories = [ - { label: '15min', idx: 0 }, - { label: '30min', idx: 1 }, - { label: '60min', idx: 2 }, - { label: '大于60min', idx: 3 }, - ]; + const scrollRef = useRef(0); - const limit = 20; - - const getInitialParams = () => { - const storedParams = localStorage.getItem('params'); - if (storedParams) { - return JSON.parse(storedParams); - } else { - return { - lastCategory: 0, - history: { - 0: { lastPage: 1, scrollPos: 0 }, - 1: { lastPage: 1, scrollPos: 0 }, - 2: { lastPage: 1, scrollPos: 0 }, - 3: { lastPage: 1, scrollPos: 0 }, - }, - }; - } - }; - - const [params, setParams] = useState(getInitialParams()); - - const [pagination, setPagination] = useState({ - movies: [], - page: params.history[params.lastCategory].lastPage, - total: 1, - length: 1, + // 初始化状态,直接使用 categories 中的 value 值 + const [params, setParams] = usePersistedState('params', { + lastCategory: categories[0].value, // 直接使用 '15min' 这样的值 + history: categories.reduce((acc, category) => ({ + ...acc, + [category.value]: { lastPage: 1, scrollPos: 0 } // 使用 category.value 作为键 + }), {}) }); + const [movies, setMovies] = useState([]); + const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 }); + const fetchMovies = useCallback(async (category, page) => { setLoading(true); try { + // 直接使用 category 值,不需要转换 const response = await axios.get( - `${window.location.origin}/movie/?page=${page}&limit=${limit}&category=${category}` + `/movie/?page=${page}&limit=${LIMIT}&category=${encodeURIComponent(category)}` ); if (response.status === 200) { - const data = response.data.data; + const { items, total } = response.data.data; - if (data.items.length === 0 && page > 1) { - fetchMovies(category, page - 1); - } else { - setPagination({ - movies: data.items, - page: page, - total: data.total, - length: Math.ceil(data.total / limit), - }); + if (items.length === 0 && page > 1) { + setParams(prev => ({ + ...prev, + history: { + ...prev.history, + [category]: { + ...(prev.history[category] || { lastPage: 1, scrollPos: 0 }), + lastPage: page - 1 + } + } + })); + return; } + + setMovies(items); + setPagination({ + page, + total, + pages: Math.ceil(total / LIMIT) + }); + + requestAnimationFrame(() => { + window.scrollTo(0, scrollRef.current); + }); } } catch (error) { console.error('Error fetching movies:', error); } finally { setLoading(false); } - }, [window.location.origin, limit]); + }, [setParams]); - useEffect(() => { - const currentCategory = params.lastCategory; - const currentPage = params.history[currentCategory].lastPage; - fetchMovies(currentCategory, currentPage); - }, [fetchMovies, params]); - - const updateParams = useCallback((newParams) => { - setParams((prevParams) => { - const updatedParams = { ...prevParams, ...newParams }; - localStorage.setItem('params', JSON.stringify(updatedParams)); - return updatedParams; - }); - }, []); - - const handlePageChange = useCallback( - (event, page) => { - const currentCategory = params.lastCategory; - updateParams({ - history: { - ...params.history, - [currentCategory]: { ...params.history[currentCategory], lastPage: page }, - }, - }); - fetchMovies(currentCategory, page); - }, - [fetchMovies, params, updateParams] - ); - - // 导致递归刷新 - const handleCategoryChange = useCallback( - (category) => { - const currentPage = params.history[category].lastPage; - fetchMovies(category, currentPage); - - const currentCategory = params.lastCategory; - updateParams({ - lastCategory: category, - history: { - ...params.history, - [currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY }, - }, - }); - }, - [fetchMovies, params, updateParams] - ); - - const handleRenderComplete = useCallback(() => { - const { scrollPos } = params.history[params.lastCategory]; - window.scrollTo(0, scrollPos); + const getCurrentCategoryAndPage = useCallback(() => { + // 直接从 params 中获取 lastCategory,确保它是 categories 中的 value 值 + const lastCategory = params.lastCategory || categories[0].value; + const categoryHistory = params.history[lastCategory] || { lastPage: 1, scrollPos: 0 }; + return { + category: lastCategory, + page: categoryHistory.lastPage + }; }, [params]); - const handleMovieCardClick = () => { - const currentCategory = params.lastCategory; - updateParams({ - history: { - ...params.history, - [currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY }, - }, + useEffect(() => { + const { category, page } = getCurrentCategoryAndPage(); + scrollRef.current = params.history[category]?.scrollPos || 0; + fetchMovies(category, page); + }, [getCurrentCategoryAndPage, fetchMovies, params.history]); + + const handleCategoryChange = useCallback((category) => { + scrollRef.current = window.scrollY; + const currentCategory = params.lastCategory || categories[0].value; + + setParams(prev => { + const newHistory = { + ...prev.history, + [currentCategory]: { + ...(prev.history[currentCategory] || { lastPage: 1, scrollPos: 0 }), + scrollPos: scrollRef.current + }, + [category]: { + ...(prev.history[category] || { lastPage: 1, scrollPos: 0 }) + } + }; + + return { + ...prev, + lastCategory: category, // 直接存储传入的 category 值 + history: newHistory + }; }); - }; + }, [params.lastCategory, setParams]); + + const handlePageChange = useCallback((_, page) => { + scrollRef.current = window.scrollY; + const lastCategory = params.lastCategory || categories[0].value; + + setParams(prev => ({ + ...prev, + history: { + ...prev.history, + [lastCategory]: { + ...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }), + lastPage: page + } + } + })); + }, [params.lastCategory, setParams]); + + const handleMovieCardClick = useCallback(() => { + scrollRef.current = window.scrollY; + const lastCategory = params.lastCategory || categories[0].value; + + setParams(prev => ({ + ...prev, + history: { + ...prev.history, + [lastCategory]: { + ...(prev.history[lastCategory] || { lastPage: 1, scrollPos: 0 }), + scrollPos: scrollRef.current + } + } + })); + }, [params.lastCategory, setParams]); return ( - + {loading ? ( - + ) : ( - + + {movies.map((item) => ( + + + + + + ))} + )} - + ); }; -const PaginationWrapper = ({ page, length, onPageChange }) => ( - - - -); - - -const MoviesGrid = ({ movies, config, onRenderComplete, onMovieCardClick }) => { - useEffect(() => { - onRenderComplete(); - }, [movies, onRenderComplete]); - - return ( - - {movies.map((item) => ( - - - - - - ))} - - ); -}; - -const Loading = () => ( - - - -); - export default Main; \ No newline at end of file diff --git a/src/components/CategoryNav.jsx b/src/components/CategoryNav.jsx index 34cea69..2db9c39 100644 --- a/src/components/CategoryNav.jsx +++ b/src/components/CategoryNav.jsx @@ -9,7 +9,7 @@ const CategoryNav = ({ categories, currentCategory, onCategoryChange }) => { }; return ( - + { centered > {categories.map((category, idx) => ( - + ))} );