做一次大更新.
This commit is contained in:
parent
7d814d7737
commit
0c4e8b089a
1
.gitignore
vendored
1
.gitignore
vendored
@ -52,3 +52,4 @@ server/server
|
|||||||
server/main
|
server/main
|
||||||
__debug_bin*
|
__debug_bin*
|
||||||
gpt*.txt
|
gpt*.txt
|
||||||
|
screenlog.*
|
||||||
|
@ -10,61 +10,88 @@ import (
|
|||||||
|
|
||||||
// MovieList 电影列表
|
// MovieList 电影列表
|
||||||
func MovieList(c *gin.Context) {
|
func MovieList(c *gin.Context) {
|
||||||
|
|
||||||
data := gin.H{}
|
|
||||||
response := gin.H{
|
response := gin.H{
|
||||||
"code": http.StatusInternalServerError,
|
"code": http.StatusInternalServerError,
|
||||||
"message": "",
|
"message": "An unexpected error occurred.", // Default error message
|
||||||
"data": data,
|
"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
|
var moviesToPaginate []Movie
|
||||||
if category != "" {
|
|
||||||
cateidx, err := strconv.Atoi(category)
|
// Filter movies by category if a categoryName is provided
|
||||||
if err != nil {
|
if categoryName != "" {
|
||||||
log.Println(err)
|
for _, m := range movies { // 'movies' is the global slice from initMovie()
|
||||||
return
|
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")
|
spage := c.Query("page")
|
||||||
if spage != "" {
|
if spage != "" {
|
||||||
p, err := strconv.Atoi(spage)
|
p, err := strconv.Atoi(spage)
|
||||||
if err != nil {
|
if err != nil || p < 1 { // Page numbers should be 1 or greater
|
||||||
log.Println(err)
|
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
|
return
|
||||||
}
|
}
|
||||||
page = p - 1
|
page = p - 1 // Convert to 0-indexed
|
||||||
}
|
}
|
||||||
|
|
||||||
var limit int = 12
|
limit := 12 // Default limit
|
||||||
slimit := c.Query("limit")
|
slimit := c.Query("limit")
|
||||||
if slimit != "" {
|
if slimit != "" {
|
||||||
l, err := strconv.Atoi(slimit)
|
l, err := strconv.Atoi(slimit)
|
||||||
if err != nil {
|
if err != nil || l < 1 { // Limit should be positive
|
||||||
log.Println(err)
|
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
|
return
|
||||||
}
|
}
|
||||||
limit = l
|
limit = l
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calculate start and end for slicing
|
||||||
start := page * limit
|
start := page * limit
|
||||||
var end int = start + limit
|
end := start + limit
|
||||||
|
|
||||||
if start > len(movies) {
|
// Handle cases where the requested page is out of bounds
|
||||||
start = len(movies)
|
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
|
response["code"] = http.StatusOK
|
||||||
|
response["message"] = "Success"
|
||||||
data["items"] = movies[start:end]
|
response["data"] = responseData
|
||||||
data["total"] = len(movies)
|
c.JSON(http.StatusOK, response)
|
||||||
}
|
}
|
||||||
|
278
server/movie.go
278
server/movie.go
@ -7,148 +7,234 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Category 电影分类结构
|
|
||||||
type Category struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Movies []Movie `json:"movies"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Movie 电影结构
|
// Movie 电影结构
|
||||||
type Movie struct {
|
type Movie struct {
|
||||||
Name string `json:"filename"`
|
Name string `json:"filename"` // Original filename of the movie, e.g., "video1.mp4"
|
||||||
Image string `json:"image"`
|
Image string `json:"image"` // Corresponding image filename, e.g., "video1.png"
|
||||||
Duration int `json:"duration"`
|
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 movies []Movie // This will store all movies
|
||||||
var categories []Category
|
|
||||||
|
|
||||||
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() {
|
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)
|
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 {
|
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 {
|
// This loop is to determine which videos need thumbnails.
|
||||||
base := filepath.Base(filename)
|
// 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)
|
if ext == ".png" {
|
||||||
base = base[:strings.IndexByte(base, '.')]
|
// If it's a PNG, check if its corresponding video is in the dict
|
||||||
|
if movieEntry, ok := movieDict[baseName]; ok {
|
||||||
if _, ok := movieDict[base]; ok {
|
if !IsRemakePNG {
|
||||||
if !IsRemakePNG {
|
// PNG exists and we are not remaking, so remove video from thumbnail generation list
|
||||||
delete(movieDict, base)
|
log.Printf("Thumbnail %s already exists. Skipping generation for %s.", baseWithExt, movieEntry.VideoPath)
|
||||||
|
delete(movieDict, baseName)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if ext != "" && ext != ".db" { // Assume other non-empty extensions are videos
|
||||||
movieDict[base] = &Movie{Name: filename}
|
// 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))
|
||||||
|
|
||||||
// 初始化分类
|
durationSec, err := getVideoDuration(path)
|
||||||
categories = []Category{
|
if err != nil {
|
||||||
{Name: "15min", Movies: []Movie{}},
|
// log.Printf("Error getting duration for %s: %v. Skipping this file.", videoFileName, err)
|
||||||
{Name: "30min", Movies: []Movie{}},
|
// Remove from movieDict if it was there, as we can't process it
|
||||||
{Name: "60min", Movies: []Movie{}},
|
delete(movieDict, baseNameWithoutExt)
|
||||||
{Name: "大于60min", Movies: []Movie{}},
|
return nil // Continue with next file
|
||||||
}
|
}
|
||||||
|
|
||||||
filepath.Walk("./movie", func(path string, info fs.FileInfo, err error) error {
|
durationMin := int(durationSec / 60.0)
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
duration, err := strconv.ParseFloat(strings.Trim(string(durationOutput), "\n "), 64)
|
var timeCat string
|
||||||
if err != nil {
|
if durationMin <= 15 {
|
||||||
log.Printf("Error parsing duration for %s: %v", info.Name(), err)
|
timeCat = "15min"
|
||||||
return err
|
} else if durationMin <= 30 {
|
||||||
}
|
timeCat = "30min"
|
||||||
// log.Println(path, info.Name())
|
} else if durationMin <= 60 {
|
||||||
|
timeCat = "60min"
|
||||||
|
} else {
|
||||||
|
timeCat = "大于60min"
|
||||||
|
}
|
||||||
|
|
||||||
movie := Movie{
|
movie := Movie{
|
||||||
Name: info.Name(),
|
Name: videoFileName,
|
||||||
Image: base[:strings.IndexByte(base, '.')] + ".png",
|
Image: baseNameWithoutExt + ".png",
|
||||||
Duration: int(duration / 60.0),
|
Duration: durationMin,
|
||||||
}
|
TimeCategory: timeCat,
|
||||||
|
VideoPath: path, // Store full path
|
||||||
if m, ok := movieDict[base[:strings.IndexByte(base, '.')]]; ok {
|
}
|
||||||
m.Duration = movie.Duration
|
movies = append(movies, movie)
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 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
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
for _, category := range categories {
|
if err != nil {
|
||||||
var movies = category.Movies
|
log.Printf("Error walking the path ./movie: %v\n", err)
|
||||||
sort.Slice(movies, func(i, j int) bool {
|
|
||||||
return movies[i].Duration < movies[j].Duration
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for key, movie := range movieDict {
|
// Sort the global movies list.
|
||||||
// width := 160
|
// First by custom time category order, then by duration within that category.
|
||||||
// height := 120
|
categoryOrderMap := map[string]int{
|
||||||
// if movie.Duration <= 40 {
|
"15min": 0,
|
||||||
// continue
|
"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
|
var filter string
|
||||||
|
// Use movieToProcess.Duration for filter logic
|
||||||
if movie.Duration <= 2 {
|
if movieToProcess.Duration <= 2 {
|
||||||
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,5)',scale=320:180,tile=3x3"
|
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"
|
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"
|
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"
|
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"
|
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",
|
cmd := exec.Command("ffmpeg",
|
||||||
"-i", movie.Name,
|
"-i", movieToProcess.VideoPath, // Use full path to video
|
||||||
"-vf", filter,
|
"-vf", filter,
|
||||||
"-frames:v", "1",
|
"-frames:v", "1",
|
||||||
"-y",
|
"-q:v", "3", // Quality for JPEG/PNG, usually 2-5 is good for -qscale:v
|
||||||
"movie/"+key+".png",
|
"-y", // Overwrite output files without asking
|
||||||
|
outputImagePath,
|
||||||
)
|
)
|
||||||
|
|
||||||
var buffer bytes.Buffer
|
var stderr bytes.Buffer
|
||||||
cmd.Stdout = &buffer
|
cmd.Stderr = &stderr
|
||||||
if cmd.Run() != nil {
|
if err := cmd.Run(); err != nil {
|
||||||
log.Println(buffer.String())
|
log.Printf("Error generating thumbnail for %s (Duration: %d min): %v\nStderr: %s",
|
||||||
panic(fmt.Errorf("could not generate frame %s %d", movie.Name, movie.Duration))
|
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)
|
|
||||||
}
|
}
|
||||||
|
306
src/Main.jsx
306
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 axios from 'axios';
|
||||||
import Container from '@mui/material/Container';
|
import Container from '@mui/material/Container';
|
||||||
import Grid from '@mui/material/Grid';
|
import Grid from '@mui/material/Grid';
|
||||||
@ -10,195 +10,201 @@ import ConfigContext from './Config';
|
|||||||
import MovieCard from './components/MovieCard';
|
import MovieCard from './components/MovieCard';
|
||||||
import CategoryNav from './components/CategoryNav';
|
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 Main = () => {
|
||||||
const config = useContext(ConfigContext);
|
const config = useContext(ConfigContext);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const categories = [
|
const scrollRef = useRef(0);
|
||||||
{ label: '15min', idx: 0 },
|
|
||||||
{ label: '30min', idx: 1 },
|
|
||||||
{ label: '60min', idx: 2 },
|
|
||||||
{ label: '大于60min', idx: 3 },
|
|
||||||
];
|
|
||||||
|
|
||||||
const limit = 20;
|
// 初始化状态,直接使用 categories 中的 value 值
|
||||||
|
const [params, setParams] = usePersistedState('params', {
|
||||||
const getInitialParams = () => {
|
lastCategory: categories[0].value, // 直接使用 '15min' 这样的值
|
||||||
const storedParams = localStorage.getItem('params');
|
history: categories.reduce((acc, category) => ({
|
||||||
if (storedParams) {
|
...acc,
|
||||||
return JSON.parse(storedParams);
|
[category.value]: { lastPage: 1, scrollPos: 0 } // 使用 category.value 作为键
|
||||||
} 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,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const [movies, setMovies] = useState([]);
|
||||||
|
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
|
||||||
|
|
||||||
const fetchMovies = useCallback(async (category, page) => {
|
const fetchMovies = useCallback(async (category, page) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
|
// 直接使用 category 值,不需要转换
|
||||||
const response = await axios.get(
|
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) {
|
if (response.status === 200) {
|
||||||
const data = response.data.data;
|
const { items, total } = response.data.data;
|
||||||
|
|
||||||
if (data.items.length === 0 && page > 1) {
|
if (items.length === 0 && page > 1) {
|
||||||
fetchMovies(category, page - 1);
|
setParams(prev => ({
|
||||||
} else {
|
...prev,
|
||||||
setPagination({
|
history: {
|
||||||
movies: data.items,
|
...prev.history,
|
||||||
page: page,
|
[category]: {
|
||||||
total: data.total,
|
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }),
|
||||||
length: Math.ceil(data.total / limit),
|
lastPage: page - 1
|
||||||
});
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setMovies(items);
|
||||||
|
setPagination({
|
||||||
|
page,
|
||||||
|
total,
|
||||||
|
pages: Math.ceil(total / LIMIT)
|
||||||
|
});
|
||||||
|
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
window.scrollTo(0, scrollRef.current);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching movies:', error);
|
console.error('Error fetching movies:', error);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [window.location.origin, limit]);
|
}, [setParams]);
|
||||||
|
|
||||||
useEffect(() => {
|
const getCurrentCategoryAndPage = useCallback(() => {
|
||||||
const currentCategory = params.lastCategory;
|
// 直接从 params 中获取 lastCategory,确保它是 categories 中的 value 值
|
||||||
const currentPage = params.history[currentCategory].lastPage;
|
const lastCategory = params.lastCategory || categories[0].value;
|
||||||
fetchMovies(currentCategory, currentPage);
|
const categoryHistory = params.history[lastCategory] || { lastPage: 1, scrollPos: 0 };
|
||||||
}, [fetchMovies, params]);
|
return {
|
||||||
|
category: lastCategory,
|
||||||
const updateParams = useCallback((newParams) => {
|
page: categoryHistory.lastPage
|
||||||
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);
|
|
||||||
}, [params]);
|
}, [params]);
|
||||||
|
|
||||||
const handleMovieCardClick = () => {
|
useEffect(() => {
|
||||||
const currentCategory = params.lastCategory;
|
const { category, page } = getCurrentCategoryAndPage();
|
||||||
updateParams({
|
scrollRef.current = params.history[category]?.scrollPos || 0;
|
||||||
history: {
|
fetchMovies(category, page);
|
||||||
...params.history,
|
}, [getCurrentCategoryAndPage, fetchMovies, params.history]);
|
||||||
[currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY },
|
|
||||||
},
|
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 (
|
return (
|
||||||
<Container style={{ marginTop: 20 }}>
|
<Container style={{ marginTop: 20 }}>
|
||||||
<CategoryNav
|
<CategoryNav
|
||||||
categories={categories}
|
categories={categories}
|
||||||
currentCategory={params.lastCategory}
|
currentCategory={params.lastCategory || categories[0].value}
|
||||||
onCategoryChange={handleCategoryChange}
|
onCategoryChange={handleCategoryChange}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />
|
<Pagination
|
||||||
|
count={pagination.pages}
|
||||||
|
page={pagination.page}
|
||||||
|
onChange={handlePageChange}
|
||||||
|
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
|
||||||
|
/>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<Loading />
|
<CircularProgress sx={{ display: 'block', margin: '20px auto' }} />
|
||||||
) : (
|
) : (
|
||||||
<MoviesGrid
|
<Grid container spacing={2} sx={{ mt: 0.5 }}>
|
||||||
movies={pagination.movies}
|
{movies.map((item) => (
|
||||||
config={config}
|
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
|
||||||
onRenderComplete={handleRenderComplete}
|
<Link
|
||||||
onMovieCardClick={handleMovieCardClick}
|
to={`/res/${item.filename}`}
|
||||||
/>
|
style={{ textDecoration: 'none', paddingBottom: 10 }}
|
||||||
|
onClick={handleMovieCardClick}
|
||||||
|
>
|
||||||
|
<MovieCard movie={item} config={config} />
|
||||||
|
</Link>
|
||||||
|
</Grid>
|
||||||
|
))}
|
||||||
|
</Grid>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />
|
<Pagination
|
||||||
|
count={pagination.pages}
|
||||||
|
page={pagination.page}
|
||||||
|
onChange={handlePageChange}
|
||||||
|
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
|
||||||
|
/>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const PaginationWrapper = ({ page, length, onPageChange }) => (
|
|
||||||
<Grid container justifyContent="center" style={{ marginTop: 20, marginBottom: 20 }}>
|
|
||||||
<Pagination count={length} page={page} onChange={onPageChange} />
|
|
||||||
</Grid>
|
|
||||||
);
|
|
||||||
|
|
||||||
|
|
||||||
const MoviesGrid = ({ movies, config, onRenderComplete, onMovieCardClick }) => {
|
|
||||||
useEffect(() => {
|
|
||||||
onRenderComplete();
|
|
||||||
}, [movies, onRenderComplete]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Grid container spacing={2} style={{ marginTop: 3 }}>
|
|
||||||
{movies.map((item) => (
|
|
||||||
<Grid item xs={6} sm={4} md={3} lg={2}
|
|
||||||
style={{ display: 'flex', justifyContent: 'space-between' }}
|
|
||||||
key={item.filename}
|
|
||||||
>
|
|
||||||
<Link
|
|
||||||
to={`/res/${item.filename}`}
|
|
||||||
style={{ textDecoration: 'none', paddingBottom: 10 }}
|
|
||||||
onClick={onMovieCardClick} // 修改这里
|
|
||||||
>
|
|
||||||
<MovieCard movie={item} config={config} />
|
|
||||||
</Link>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</Grid>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const Loading = () => (
|
|
||||||
<Grid container justifyContent="center" style={{ marginTop: 20 }}>
|
|
||||||
<CircularProgress />
|
|
||||||
</Grid>
|
|
||||||
);
|
|
||||||
|
|
||||||
export default Main;
|
export default Main;
|
@ -9,7 +9,7 @@ const CategoryNav = ({ categories, currentCategory, onCategoryChange }) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
||||||
<Tabs
|
<Tabs
|
||||||
value={currentCategory}
|
value={currentCategory}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
@ -21,7 +21,7 @@ const CategoryNav = ({ categories, currentCategory, onCategoryChange }) => {
|
|||||||
centered
|
centered
|
||||||
>
|
>
|
||||||
{categories.map((category, idx) => (
|
{categories.map((category, idx) => (
|
||||||
<Tab key={category.label} label={category.label} value={idx} />
|
<Tab key={category.label} label={category.label} value={category.label} />
|
||||||
))}
|
))}
|
||||||
</Tabs>
|
</Tabs>
|
||||||
);
|
);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user