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 server/main
__debug_bin* __debug_bin*
gpt*.txt gpt*.txt
screenlog.*

View File

@ -1,9 +1,27 @@
module server module server
go 1.16 go 1.23
toolchain go1.24.3
require ( require (
github.com/gin-gonic/gin v1.6.3 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
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect )
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-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 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= 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 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= 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= 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 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 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/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 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 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= 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/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/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.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/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 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 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= 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.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/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= 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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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.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.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 ( import (
"log" "log"
"net/http" "net/http"
"sort"
"strconv" "strconv"
"strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// 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.",
"data": data, "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 != "" { if categoryName != "" && categoryName != "最新添加" {
cateidx, err := strconv.Atoi(category) // 普通类别:直接过滤
if err != nil { for _, m := range movies {
log.Println(err) if m.TimeCategory == categoryName {
return 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") 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 {
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)
return return
} }
page = p - 1 page = p - 1
} }
var limit int = 12 limit := 12
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 {
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)
return return
} }
limit = l limit = l
} }
start := page * limit 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 response["code"] = http.StatusOK
response["message"] = "Success"
data["items"] = movies[start:end] response["data"] = responseData
data["total"] = len(movies) c.JSON(http.StatusOK, response)
} }

View File

@ -5,150 +5,286 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
"log" "log"
"os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
) )
// Category 电影分类结构 // Movie 电影信息结构
type Category struct {
Name string `json:"name"`
Movies []Movie `json:"movies"`
}
// Movie 电影结构
type Movie struct { type Movie struct {
Name string `json:"filename"` FileName string `json:"filename"` // 原始文件名(如 "video1.mp4"
Image string `json:"image"` Image string `json:"image"` // 对应的缩略图文件名(如 "video1.png"
Duration int `json:"duration"` Duration int `json:"duration"` // 视频时长(分钟)
TimeCategory string `json:"time_category"` // 时长分类(如 "15min", "30min"
VideoPath string `json:"-"` // 视频文件完整路径用于ffmpeg
CreatedTime int64 `json:"created_time"` // 文件创建时间戳
} }
// var movies []Movie var movies []Movie // 存储所有电影信息的全局切片
var categories []Category 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() { // 解析ffmpeg输出的时长信息
// 需要改进 如果存在这个文件的略缩图, 就不存进movieDict里 output := stderr.String()
var movieDict map[string]*Movie = make(map[string]*Movie) 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 { if err != nil {
log.Println(err) return 0, err
} }
return fileInfo.ModTime().Unix(), nil
}
for _, filename := range matches { // scanMovieFiles 扫描movie目录并返回文件列表
base := filepath.Base(filename) 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) // createMovieDict 创建需要处理缩略图的视频字典
base = base[:strings.IndexByte(base, '.')] func createMovieDict(files []string) map[string]*Movie {
movieDict := make(map[string]*Movie)
if _, ok := movieDict[base]; ok { for _, fullPath := range files {
if !IsRemakePNG { filename := filepath.Base(fullPath)
delete(movieDict, base) ext := filepath.Ext(filename)
} baseName := strings.TrimSuffix(filename, ext)
} else {
movieDict[base] = &Movie{Name: filename} // 跳过目录和系统文件
if ext == ".db" {
continue
} }
} // 处理PNG文件
if ext == ".png" {
// 初始化分类 if _, exists := movieDict[baseName]; exists && !IsRemakePNG {
categories = []Category{ delete(movieDict, baseName)
{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
} }
continue
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)
}
} }
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 { if err != nil {
var movies = category.Movies log.Fatalf("遍历movie目录失败: %v", err)
sort.Slice(movies, func(i, j int) bool {
return movies[i].Duration < movies[j].Duration
})
} }
for key, movie := range movieDict { // 为最近添加的文件添加"最新添加"类别
// width := 160 markRecentMovies()
// height := 120
// if movie.Duration <= 40 {
// continue
// }
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" for _, movie := range movieDict {
} else if movie.Duration <= 5 { if movie.VideoPath == "" {
filter = "select='isnan(prev_selected_t)+gte(t-prev_selected_t\\,10)',scale=320:180,tile=3x3" continue
} 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"
} }
generateThumbnail(movie)
cmd := exec.Command("ffmpeg", }
"-i", movie.Name, }
"-vf", filter,
"-frames:v", "1", // markRecentMovies 标记最近添加的电影
"-y", func markRecentMovies() {
"movie/"+key+".png", // 首先按创建时间排序
) sort.Slice(movies, func(i, j int) bool {
return movies[i].CreatedTime > movies[j].CreatedTime
var buffer bytes.Buffer })
cmd.Stdout = &buffer
if cmd.Run() != nil { // 标记前20个最新文件为"最新添加"类别
log.Println(buffer.String()) for i := 0; i < len(movies) && i < 20; i++ {
panic(fmt.Errorf("could not generate frame %s %d", movie.Name, movie.Duration)) 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 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';
import Pagination from '@mui/material/Pagination'; import Pagination from '@mui/material/Pagination';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import CircularProgress from '@mui/material/CircularProgress'; 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 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' },
{ 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 Main = () => {
const config = useContext(ConfigContext); const config = useContext(ConfigContext);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const categories = [ const isFirstLoad = useRef(true);
{ label: '15min', idx: 0 }, const scrollListenerActive = useRef(false);
{ label: '30min', idx: 1 },
{ label: '60min', idx: 2 },
{ label: '大于60min', idx: 3 },
];
const limit = 20; // -
const [params, setParams] = usePersistedState('params', {
const getInitialParams = () => { lastCategory: DEFAULT_CATEGORY,
const storedParams = localStorage.getItem('params'); history: Object.fromEntries([
if (storedParams) { ...categories.map(cat => [
return JSON.parse(storedParams); cat.value,
} else { { lastPage: 1, scrollPos: 0 }
return { ]),
lastCategory: 0, //
history: { [SEARCH_CATEGORY, { lastPage: 1, scrollPos: 0 }]
0: { lastPage: 1, scrollPos: 0 }, ]),
1: { lastPage: 1, scrollPos: 0 }, //
2: { lastPage: 1, scrollPos: 0 }, searchQuery: ''
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 fetchMovies = useCallback(async (category, page) => { const [movies, setMovies] = useState([]);
setLoading(true); const [pagination, setPagination] = useState({ page: 1, total: 0, pages: 1 });
try { const currentCategory = params.lastCategory || DEFAULT_CATEGORY;
const response = await axios.get(
`${window.location.origin}/movie/?page=${page}&limit=${limit}&category=${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); const saveScrollPosition = useCallback((category = currentCategory) => {
} else { const currentScrollPos = window.scrollY;
setPagination({
movies: data.items, setParams(prev => {
page: page, const updatedHistory = {
total: data.total, ...prev.history,
length: Math.ceil(data.total / limit), [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) { } 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]);
//
const restoreScrollPosition = useCallback((category) => {
const scrollPos = params.history?.[category]?.scrollPos || 0;
requestAnimationFrame(() => {
setTimeout(() => window.scrollTo(0, scrollPos), 100);
});
}, [params.history]);
//
useEffect(() => { useEffect(() => {
const currentCategory = params.lastCategory; if (!isFirstLoad.current) return;
const currentPage = params.history[currentCategory].lastPage;
fetchMovies(currentCategory, currentPage); const category = currentCategory;
}, [fetchMovies, params]); 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; 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 handleSearchKeyDown = useCallback((e) => {
const currentCategory = params.lastCategory; if (e.key === 'Enter') {
updateParams({ handleSearchSubmit();
history: { }
...params.history, }, [handleSearchSubmit]);
[currentCategory]: { ...params.history[currentCategory], lastPage: page },
}, //
}); useEffect(() => removeScrollListener, [removeScrollListener]);
fetchMovies(currentCategory, page);
}, //
[fetchMovies, params, updateParams] 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 ( return (
<Container style={{ marginTop: 20 }}> <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 <CategoryNav
categories={categories} categories={categories}
currentCategory={params.lastCategory} currentCategory={currentCategory === SEARCH_CATEGORY ? '' : currentCategory}
onCategoryChange={handleCategoryChange} onCategoryChange={handleCategoryChange}
/> />
<PaginationWrapper page={pagination.page} length={pagination.length} onPageChange={handlePageChange} /> {/* 显示当前搜索状态 */}
{currentCategory === SEARCH_CATEGORY && (
{loading ? ( <div style={{ textAlign: 'center', margin: '10px 0' }}>
<Loading /> 搜索: "{params.searchQuery}" ({pagination.total} 个结果)
) : ( </div>
<MoviesGrid
movies={pagination.movies}
config={config}
onRenderComplete={handleRenderComplete}
onMovieCardClick={handleMovieCardClick}
/>
)} )}
<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> </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;

View File

@ -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>
); );