Compare commits

...

2 Commits

Author SHA1 Message Date
a92d9837aa 添加搜索功能 2025-06-02 06:20:16 +08:00
0c4e8b089a 做一次大更新. 2025-06-02 03:19:36 +08:00
7 changed files with 723 additions and 311 deletions

1
.gitignore vendored
View File

@ -52,3 +52,4 @@ server/server
server/main
__debug_bin*
gpt*.txt
screenlog.*

View File

@ -1,9 +1,27 @@
module server
go 1.16
go 1.23
toolchain go1.24.3
require (
github.com/gin-gonic/gin v1.6.3
github.com/giorgisio/goav v0.1.0 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible
)
require (
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.13.0 // indirect
github.com/go-playground/universal-translator v0.17.0 // indirect
github.com/go-playground/validator/v10 v10.2.0 // indirect
github.com/golang/protobuf v1.3.3 // indirect
github.com/json-iterator/go v1.1.9 // indirect
github.com/leodido/go-urn v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 // indirect
github.com/stretchr/testify v1.10.0 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
golang.org/x/sys v0.29.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

View File

@ -5,8 +5,6 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/giorgisio/goav v0.1.0 h1:ZyfG3NfX7PMSimv4ulhmnQJf/XeHpMdGCn+afRmY5Oc=
github.com/giorgisio/goav v0.1.0/go.mod h1:RtH8HyxLRLU1iY0pjfhWBKRhnbsnmfoI+FxMwb5bfEo=
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
@ -20,8 +18,6 @@ github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzq
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gosuri/uilive v0.0.0-20170323041506-ac356e6e42cd/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8=
github.com/gosuri/uiprogress v0.0.0-20170224063937-d0567a9d84a1/go.mod h1:C1RTYn4Sc7iEyf6j8ft5dyoZ4212h8G1ol9QQluh5+0=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
@ -36,18 +32,22 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -3,68 +3,135 @@ package main
import (
"log"
"net/http"
"sort"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// MovieList 电影列表
func MovieList(c *gin.Context) {
data := gin.H{}
response := gin.H{
"code": http.StatusInternalServerError,
"message": "",
"data": data,
"message": "An unexpected error occurred.",
"data": gin.H{"items": []Movie{}, "total": 0},
}
defer c.JSON(0, response)
category := c.Query("category")
var moviesToPaginate []Movie
categoryName := c.Query("category")
searchQuery := c.Query("search") // 获取搜索参数
var movies []Movie
if category != "" {
cateidx, err := strconv.Atoi(category)
if err != nil {
log.Println(err)
return
// === 第一步:基础过滤(类别)===
if categoryName != "" && categoryName != "最新添加" {
// 普通类别:直接过滤
for _, m := range movies {
if m.TimeCategory == categoryName {
moviesToPaginate = append(moviesToPaginate, m)
}
}
movies = categories[cateidx].Movies
} else {
// 最新添加/所有电影使用全局movies
moviesToPaginate = make([]Movie, len(movies))
copy(moviesToPaginate, movies)
}
var page int = 0
// === 第二步:搜索过滤 ===
if searchQuery != "" {
var searchResults []Movie
lowerSearch := strings.ToLower(searchQuery)
for _, m := range moviesToPaginate {
// 检查文件名是否包含搜索词(不区分大小写)
if strings.Contains(strings.ToLower(m.FileName), lowerSearch) {
searchResults = append(searchResults, m)
}
}
moviesToPaginate = searchResults
}
// === 第三步:排序处理 ===
sortBy := c.Query("sort")
order := c.Query("order")
if sortBy == "" {
sortBy = "created_time" // 默认按创建时间排序
}
// 应用排序
sort.Slice(moviesToPaginate, func(i, j int) bool {
switch sortBy {
case "created_time":
if order == "desc" {
return moviesToPaginate[i].CreatedTime > moviesToPaginate[j].CreatedTime
}
return moviesToPaginate[i].CreatedTime < moviesToPaginate[j].CreatedTime
case "duration":
if order == "desc" {
return moviesToPaginate[i].Duration > moviesToPaginate[j].Duration
}
return moviesToPaginate[i].Duration < moviesToPaginate[j].Duration
default:
// 默认按创建时间降序
return moviesToPaginate[i].CreatedTime > moviesToPaginate[j].CreatedTime
}
})
// === 第四步:分页处理 ===
page := 0
spage := c.Query("page")
if spage != "" {
p, err := strconv.Atoi(spage)
if err != nil {
log.Println(err)
if err != nil || p < 1 {
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)
return
}
page = p - 1
}
var limit int = 12
limit := 12
slimit := c.Query("limit")
if slimit != "" {
l, err := strconv.Atoi(slimit)
if err != nil {
log.Println(err)
if err != nil || l < 1 {
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)
return
}
limit = l
}
start := page * limit
var end int = start + limit
end := start + limit
total := len(moviesToPaginate)
if start > len(movies) {
start = len(movies)
// 处理超出范围的情况
if start >= total {
response["data"] = gin.H{
"items": []Movie{},
"total": total,
}
response["code"] = http.StatusOK
response["message"] = "Success"
c.JSON(http.StatusOK, response)
return
}
if end > len(movies) {
end = len(movies)
if end > total {
end = total
}
responseData := gin.H{
"items": moviesToPaginate[start:end],
"total": total,
}
response["code"] = http.StatusOK
data["items"] = movies[start:end]
data["total"] = len(movies)
response["message"] = "Success"
response["data"] = responseData
c.JSON(http.StatusOK, response)
}

View File

@ -5,150 +5,286 @@ import (
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)
// Category 电影分类结构
type Category struct {
Name string `json:"name"`
Movies []Movie `json:"movies"`
}
// Movie 电影结构
// Movie 电影信息结构
type Movie struct {
Name string `json:"filename"`
Image string `json:"image"`
Duration int `json:"duration"`
FileName string `json:"filename"` // 原始文件名(如 "video1.mp4"
Image string `json:"image"` // 对应的缩略图文件名(如 "video1.png"
Duration int `json:"duration"` // 视频时长(分钟)
TimeCategory string `json:"time_category"` // 时长分类(如 "15min", "30min"
VideoPath string `json:"-"` // 视频文件完整路径用于ffmpeg
CreatedTime int64 `json:"created_time"` // 文件创建时间戳
}
// var movies []Movie
var categories []Category
var movies []Movie // 存储所有电影信息的全局切片
var IsRemakePNG = false // 是否重新生成所有PNG缩略图
var IsRemakePNG = false
// getVideoDuration 获取视频时长(秒)
func getVideoDuration(videoPath string) (float64, error) {
cmd := exec.Command("ffmpeg", "-i", videoPath)
var stderr bytes.Buffer
cmd.Stderr = &stderr
_ = cmd.Run() // 忽略错误ffmpeg在没有输出文件时会返回错误
func initMovie() {
// 需要改进 如果存在这个文件的略缩图, 就不存进movieDict里
var movieDict map[string]*Movie = make(map[string]*Movie)
// 解析ffmpeg输出的时长信息
output := stderr.String()
re := regexp.MustCompile(`Duration: (\d{2}):(\d{2}):(\d{2}\.\d{2})`)
matches := re.FindStringSubmatch(output)
matches, err := filepath.Glob("movie/*")
// 尝试匹配不含毫秒的格式
if len(matches) < 4 {
reAlt := regexp.MustCompile(`Duration: (\d{2}):(\d{2}):(\d{2})`)
matches = reAlt.FindStringSubmatch(output)
if len(matches) < 4 {
return 0, fmt.Errorf("无法在ffmpeg输出中找到时长: %s. 输出: %s", filepath.Base(videoPath), output)
}
matches[3] += ".00" // 添加毫秒部分保持格式一致
}
// 转换为秒数
hours, _ := strconv.ParseFloat(matches[1], 64)
minutes, _ := strconv.ParseFloat(matches[2], 64)
seconds, _ := strconv.ParseFloat(matches[3], 64)
return hours*3600 + minutes*60 + seconds, nil
}
// getFileCreationTime 获取文件创建时间戳
func getFileCreationTime(path string) (int64, error) {
fileInfo, err := os.Stat(path)
if err != nil {
log.Println(err)
return 0, err
}
return fileInfo.ModTime().Unix(), nil
}
for _, filename := range matches {
base := filepath.Base(filename)
// scanMovieFiles 扫描movie目录并返回文件列表
func scanMovieFiles() ([]string, error) {
files, err := filepath.Glob("movie/*")
if err != nil {
return nil, fmt.Errorf("扫描movie目录失败: %w", err)
}
return files, nil
}
// ext := filepath.Ext(base)
base = base[:strings.IndexByte(base, '.')]
// createMovieDict 创建需要处理缩略图的视频字典
func createMovieDict(files []string) map[string]*Movie {
movieDict := make(map[string]*Movie)
if _, ok := movieDict[base]; ok {
if !IsRemakePNG {
delete(movieDict, base)
}
} else {
movieDict[base] = &Movie{Name: filename}
for _, fullPath := range files {
filename := filepath.Base(fullPath)
ext := filepath.Ext(filename)
baseName := strings.TrimSuffix(filename, ext)
// 跳过目录和系统文件
if ext == ".db" {
continue
}
}
// 初始化分类
categories = []Category{
{Name: "15min", Movies: []Movie{}},
{Name: "30min", Movies: []Movie{}},
{Name: "60min", Movies: []Movie{}},
{Name: "大于60min", Movies: []Movie{}},
}
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
// 处理PNG文件
if ext == ".png" {
if _, exists := movieDict[baseName]; exists && !IsRemakePNG {
delete(movieDict, baseName)
}
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())
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)
}
continue
}
return nil
// 处理视频文件
if ext != "" {
if _, exists := movieDict[baseName]; !exists || IsRemakePNG {
movieDict[baseName] = &Movie{VideoPath: fullPath}
}
}
}
return movieDict
}
// processVideoFile 处理单个视频文件
func processVideoFile(path string, movieDict map[string]*Movie) error {
filename := filepath.Base(path)
baseName := strings.TrimSuffix(filename, filepath.Ext(filename))
// 获取视频时长
durationSec, err := getVideoDuration(path)
if err != nil {
delete(movieDict, baseName)
return fmt.Errorf("获取时长失败: %s: %w", filename, err)
}
// 获取文件创建时间
createdTime, err := getFileCreationTime(path)
if err != nil {
return fmt.Errorf("获取创建时间失败: %s: %w", filename, err)
}
// 转换为分钟并分类
durationMin := int(durationSec / 60)
timeCat := getTimeCategory(durationMin)
// 创建电影记录
movie := Movie{
FileName: filename,
Image: baseName + ".png",
Duration: durationMin,
TimeCategory: timeCat,
VideoPath: path,
CreatedTime: createdTime,
}
movies = append(movies, movie)
// 更新缩略图字典
if entry, exists := movieDict[baseName]; exists {
entry.FileName = movie.FileName
entry.Duration = movie.Duration
entry.VideoPath = movie.VideoPath
entry.CreatedTime = movie.CreatedTime
}
return nil
}
// getTimeCategory 根据时长获取分类
func getTimeCategory(durationMin int) string {
switch {
case durationMin <= 15:
return "15min"
case durationMin <= 30:
return "30min"
case durationMin <= 60:
return "60min"
default:
return "大于60min"
}
}
// sortMovies 对电影列表排序
func sortMovies() {
categoryOrder := map[string]int{
"15min": 0,
"30min": 1,
"60min": 2,
"大于60min": 3,
"最新添加": 4, // 新增的"最新添加"类别
}
sort.Slice(movies, func(i, j int) bool {
catI := categoryOrder[movies[i].TimeCategory]
catJ := categoryOrder[movies[j].TimeCategory]
if catI != catJ {
return catI < catJ
}
// 如果是recent类别按创建时间倒序排序
if movies[i].TimeCategory == "最新添加" {
return movies[i].CreatedTime > movies[j].CreatedTime
}
// 其他类别按时长排序
return movies[i].Duration < movies[j].Duration
})
}
// generateThumbnail 生成单个视频缩略图
func generateThumbnail(movie *Movie) {
baseName := strings.TrimSuffix(movie.FileName, filepath.Ext(movie.FileName))
outputPath := filepath.Join("movie", baseName+".png")
// 根据时长选择不同的采样策略
var filter string
switch {
case movie.Duration <= 2:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,5)',scale=320:180,tile=3x3"
case movie.Duration <= 5:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,10)',scale=320:180,tile=3x3"
case movie.Duration <= 30:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,20)',scale=320:180,tile=3x3"
case movie.Duration <= 60:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,35)',scale=320:180,tile=3x3"
default:
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,60)',scale=320:180,tile=3x3"
}
// 执行ffmpeg命令生成缩略图
cmd := exec.Command("ffmpeg",
"-i", movie.VideoPath,
"-vf", filter,
"-frames:v", "1",
"-q:v", "3",
"-y", // 覆盖已存在文件
outputPath,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
log.Printf("生成缩略图失败: %s (%d min): %v\n错误输出: %s",
movie.VideoPath, movie.Duration, err, stderr.String())
} else {
log.Printf("成功生成缩略图: %s", outputPath)
}
}
// initMovie 初始化电影数据主函数
func initMovie() {
// 扫描目录获取文件列表
files, err := scanMovieFiles()
if err != nil {
log.Fatal(err)
}
// 创建需要处理缩略图的视频字典
movieDict := createMovieDict(files)
movies = make([]Movie, 0) // 重置全局电影列表
// 遍历处理每个视频文件
err = filepath.WalkDir("./movie", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() ||
filepath.Ext(d.Name()) == ".png" ||
filepath.Ext(d.Name()) == ".db" {
return err
}
return processVideoFile(path, movieDict)
})
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.Fatalf("遍历movie目录失败: %v", err)
}
for key, movie := range movieDict {
// width := 160
// height := 120
// if movie.Duration <= 40 {
// continue
// }
// 为最近添加的文件添加"最新添加"类别
markRecentMovies()
log.Println(movie.Name, "时长:", movie.Duration)
var filter string
// 排序电影列表
// sortMovies()
if movie.Duration <= 2 {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,5)',scale=320:180,tile=3x3"
} else if movie.Duration <= 5 {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,10)',scale=320:180,tile=3x3"
} else if movie.Duration <= 30 {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,20)',scale=320:180,tile=3x3"
} else if movie.Duration <= 60 {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,35)',scale=320:180,tile=3x3"
} else {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,60)',scale=320:180,tile=3x3"
// 生成缩略图
for _, movie := range movieDict {
if movie.VideoPath == "" {
continue
}
cmd := exec.Command("ffmpeg",
"-i", movie.Name,
"-vf", filter,
"-frames:v", "1",
"-y",
"movie/"+key+".png",
)
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))
}
generateThumbnail(movie)
}
}
// markRecentMovies 标记最近添加的电影
func markRecentMovies() {
// 首先按创建时间排序
sort.Slice(movies, func(i, j int) bool {
return movies[i].CreatedTime > movies[j].CreatedTime
})
// 标记前20个最新文件为"最新添加"类别
for i := 0; i < len(movies) && i < 20; i++ {
movies[i].TimeCategory = "最新添加"
}
// log.Printf("%##v", categories)
}

View File

@ -1,204 +1,394 @@
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';
import Pagination from '@mui/material/Pagination';
import { Link } from 'react-router-dom';
import CircularProgress from '@mui/material/CircularProgress';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import ClearIcon from '@mui/icons-material/Clear';
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' },
{ label: '最新添加', value: '最新添加' },
];
//
const SEARCH_CATEGORY = 'search';
const LIMIT = 20;
const DEFAULT_CATEGORY = categories[0].value;
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 isFirstLoad = useRef(true);
const scrollListenerActive = useRef(false);
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,
// -
const [params, setParams] = usePersistedState('params', {
lastCategory: DEFAULT_CATEGORY,
history: Object.fromEntries([
...categories.map(cat => [
cat.value,
{ lastPage: 1, scrollPos: 0 }
]),
//
[SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0 }]
]),
//
searchQuery: ''
});
const fetchMovies = useCallback(async (category, page) => {
setLoading(true);
try {
const response = await axios.get(
`${window.location.origin}/movie/?page=${page}&limit=${limit}&category=${category}`
);
const [movies, setMovies] = useState([]);
const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
if (response.status === 200) {
const data = response.data.data;
//
const [searchInput, setSearchInput] = useState(params.searchQuery || '');
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),
});
//
const saveScrollPosition = useCallback((category = currentCategory) => {
const currentScrollPos = window.scrollY;
setParams(prev => {
const updatedHistory = {
...prev.history,
[category]: {
...(prev.history[category] || { lastPage: 1, scrollPos: 0 }),
scrollPos: currentScrollPos
}
};
return { ...prev, history: updatedHistory };
});
}, [setParams, currentCategory]);
const setupScrollListener = useCallback(() => {
if (scrollListenerActive.current) return;
const handleScroll = () => {
clearTimeout(window.scrollTimer);
window.scrollTimer = setTimeout(() => saveScrollPosition(), 100);
};
window.addEventListener('scroll', handleScroll);
scrollListenerActive.current = true;
return () => {
window.removeEventListener('scroll', handleScroll);
clearTimeout(window.scrollTimer);
scrollListenerActive.current = false;
};
}, [saveScrollPosition]);
const removeScrollListener = useCallback(() => {
if (scrollListenerActive.current) {
window.removeEventListener('scroll', window.scrollHandler);
scrollListenerActive.current = false;
}
}, []);
// fetchMovies
const fetchMovies = useCallback(async (category, page, search = '') => {
setLoading(true);
try {
const isSearch = category === SEARCH_CATEGORY;
const isLatest = category === '最新添加';
let apiUrl = `/movie?page=${page}&limit=${LIMIT}`;
if (isSearch) {
//
apiUrl += `&search=${encodeURIComponent(search)}`;
} else if (isLatest) {
//
apiUrl += `&sort=created_time&order=desc`;
} else {
//
apiUrl += `&category=${encodeURIComponent(category)}`;
}
const response = await axios.get(apiUrl);
if (response.status !== 200) return;
const { items, total } = response.data.data;
const totalPages = Math.ceil(total / LIMIT);
if (items.length === 0 && page > 1) {
setParams(prev => ({
...prev,
history: {
...prev.history,
[category]: { ...prev.history[category], lastPage: page - 1 }
}
}));
return;
}
setMovies(items);
setPagination({ page, total, pages: totalPages });
} catch (error) {
console.error('Error fetching movies:', error);
} finally {
setLoading(false);
}
}, [window.location.origin, limit]);
}, [setParams]);
//
const restoreScrollPosition = useCallback((category) => {
const scrollPos = params.history?.[category]?.scrollPos || 0;
requestAnimationFrame(() => {
setTimeout(() => window.scrollTo(0, scrollPos), 100);
});
}, [params.history]);
//
useEffect(() => {
const currentCategory = params.lastCategory;
const currentPage = params.history[currentCategory].lastPage;
fetchMovies(currentCategory, currentPage);
}, [fetchMovies, params]);
if (!isFirstLoad.current) return;
const category = currentCategory;
const categoryHistory = params.history[category] || { lastPage: 1 };
//
if (category === SEARCH_CATEGORY) {
fetchMovies(category, categoryHistory.lastPage, params.searchQuery);
} else {
fetchMovies(category, categoryHistory.lastPage);
}
isFirstLoad.current = false;
}, [fetchMovies, currentCategory, params.history, params.searchQuery]);
//
useEffect(() => {
if (loading || isFirstLoad.current) return;
restoreScrollPosition(currentCategory);
setupScrollListener();
}, [loading, restoreScrollPosition, currentCategory, setupScrollListener]);
// -
const handleCategoryChange = useCallback((newCategory) => {
removeScrollListener();
saveScrollPosition();
setParams(prev => {
const categoryHistory = prev.history[newCategory] || { lastPage: 1 };
// 使
if (newCategory === SEARCH_CATEGORY) {
fetchMovies(newCategory, categoryHistory.lastPage, prev.searchQuery);
} else {
fetchMovies(newCategory, categoryHistory.lastPage);
}
return {
...prev,
lastCategory: newCategory
};
});
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies]);
// -
const handlePageChange = useCallback((_, page) => {
removeScrollListener();
saveScrollPosition();
setParams(prev => ({
...prev,
history: {
...prev.history,
[currentCategory]: {
...prev.history[currentCategory],
lastPage: page,
scrollPos: 0
}
}
}));
//
if (currentCategory === SEARCH_CATEGORY) {
fetchMovies(currentCategory, page, params.searchQuery);
} else {
fetchMovies(currentCategory, page);
}
window.scrollTo(0, 0);
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, currentCategory, params.searchQuery]);
//
const handleMovieCardClick = useCallback(() => {
removeScrollListener();
saveScrollPosition();
}, [removeScrollListener, saveScrollPosition]);
//
const handleSearchSubmit = useCallback(() => {
if (!searchInput.trim()) return;
removeScrollListener();
saveScrollPosition();
setParams(prev => {
//
const updatedParams = {
...prev,
lastCategory: SEARCH_CATEGORY,
searchQuery: searchInput.trim(),
history: {
...prev.history,
[SEARCH_CATEGORY]: {
...prev.history[SEARCH_CATEGORY],
lastPage: 1 //
}
}
};
//
fetchMovies(SEARCH_CATEGORY, 1, searchInput.trim());
const updateParams = useCallback((newParams) => {
setParams((prevParams) => {
const updatedParams = { ...prevParams, ...newParams };
localStorage.setItem('params', JSON.stringify(updatedParams));
return updatedParams;
});
}, [removeScrollListener, saveScrollPosition, setParams, fetchMovies, searchInput]);
//
const handleClearSearch = useCallback(() => {
if (!searchInput) return;
setSearchInput('');
//
if (currentCategory === SEARCH_CATEGORY) {
setParams(prev => ({
...prev,
lastCategory: DEFAULT_CATEGORY,
searchQuery: ''
}));
//
const categoryHistory = params.history[DEFAULT_CATEGORY] || { lastPage: 1 };
fetchMovies(DEFAULT_CATEGORY, categoryHistory.lastPage);
} else {
//
setParams(prev => ({
...prev,
searchQuery: ''
}));
}
}, [currentCategory, fetchMovies, params.history, searchInput, setParams]);
//
const handleSearchChange = useCallback((e) => {
setSearchInput(e.target.value);
}, []);
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 handleSearchKeyDown = useCallback((e) => {
if (e.key === 'Enter') {
handleSearchSubmit();
}
}, [handleSearchSubmit]);
//
useEffect(() => removeScrollListener, [removeScrollListener]);
//
const paginationComponent = (
<Pagination
count={pagination.pages}
page={pagination.page}
onChange={handlePageChange}
sx={{ my: 2, display: 'flex', justifyContent: 'center' }}
/>
);
//
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]);
const handleMovieCardClick = () => {
const currentCategory = params.lastCategory;
updateParams({
history: {
...params.history,
[currentCategory]: { ...params.history[currentCategory], scrollPos: window.scrollY },
},
});
};
return (
<Container style={{ marginTop: 20 }}>
{/* 添加搜索框 */}
<TextField
fullWidth
variant="outlined"
placeholder="搜索文件名..."
value={searchInput}
onChange={handleSearchChange}
onKeyDown={handleSearchKeyDown}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
),
endAdornment: searchInput && (
<InputAdornment position="end">
<IconButton onClick={handleClearSearch}>
<ClearIcon />
</IconButton>
</InputAdornment>
)
}}
sx={{ mb: 2 }}
/>
<CategoryNav
categories={categories}
currentCategory={params.lastCategory}
currentCategory={currentCategory === SEARCH_CATEGORY ? '' : currentCategory}
onCategoryChange={handleCategoryChange}
/>
<PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />
{loading ? (
<Loading />
) : (
<MoviesGrid
movies={pagination.movies}
config={config}
onRenderComplete={handleRenderComplete}
onMovieCardClick={handleMovieCardClick}
/>
{/* 显示当前搜索状态 */}
{currentCategory === SEARCH_CATEGORY && (
<div style={{ textAlign: 'center', margin: '10px 0' }}>
搜索: "{params.searchQuery}" ({pagination.total} 个结果)
</div>
)}
<PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} />
{paginationComponent}
{loading ? (
<CircularProgress sx={{ display: 'block', margin: '20px auto' }} />
) : (
<Grid container spacing={2} sx={{ mt: 0.5 }}>
{movies.map(item => (
<Grid item xs={6} sm={4} md={3} lg={2} key={item.filename}>
<Link
to={`/res/${item.filename}`}
style={{ textDecoration: 'none', paddingBottom: 10 }}
onClick={handleMovieCardClick}
>
<MovieCard movie={item} config={config} />
</Link>
</Grid>
))}
</Grid>
)}
{paginationComponent}
</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;

View File

@ -9,7 +9,7 @@ const CategoryNav = ({ categories, currentCategory, onCategoryChange }) => {
};
return (
<Tabs
value={currentCategory}
onChange={handleChange}
@ -21,7 +21,7 @@ const CategoryNav = ({ categories, currentCategory, onCategoryChange }) => {
centered
>
{categories.map((category, idx) => (
<Tab key={category.label} label={category.label} value={idx} />
<Tab key={category.label} label={category.label} value={category.label} />
))}
</Tabs>
);