mirror of
https://github.com/truewhile/MeBox.git
synced 2026-11-16 04:44:23 +08:00
优化
This commit is contained in:
@@ -87,7 +87,7 @@ func updateSettingHandler(svc *service.Container) gin.HandlerFunc {
|
||||
if req.Key == "transcode.hw_enabled" || req.Key == "transcode.hw_accel" || req.Key == "transcoder.hardware_accel" || req.Key == "transcoder.encoder" {
|
||||
svc.Transcoder.StopAll()
|
||||
}
|
||||
if req.Key == "cache.images_max_size_mb" || req.Key == "cache.images_originals_max_size_mb" || req.Key == "cache.images_originals_ttl_hours" {
|
||||
if req.Key == "cache.images_max_size_mb" || req.Key == "cache.images_originals_max_size_mb" {
|
||||
if svc.Scheduler != nil {
|
||||
_ = svc.Scheduler.RunNowAsync(c.Request.Context(), "image_cache_cleanup")
|
||||
}
|
||||
|
||||
@@ -50,6 +50,25 @@ func embyServeImage(c *gin.Context, svc *service.Container, id, imageType, tag s
|
||||
embyServePlaceholderImage(c)
|
||||
return
|
||||
}
|
||||
// 媒体库主图:按 Emby 的做法,用库内几张成员海报拼一张封面(folder
|
||||
// image)。没有自定义封面时才生成;自定义封面继续走下面的代理路径。
|
||||
if svc.ImageProxy != nil && strings.EqualFold(strings.TrimSpace(imageType), "Primary") {
|
||||
if sources, lib := service.LibraryCoverSourcesForLibrary(ctx, svc.Repo, id); lib != nil &&
|
||||
strings.TrimSpace(lib.CoverURL) == "" && len(sources) > 0 {
|
||||
width, height := libraryCoverRequestSize(c)
|
||||
if data, err := svc.ImageProxy.LibraryCoverImage(ctx, id, sources, width, height); err == nil && len(data) > 0 {
|
||||
c.Header("Cache-Control", "public, max-age=300, stale-while-revalidate=86400")
|
||||
c.Header("Content-Type", "image/jpeg")
|
||||
c.Header("Content-Length", strconv.Itoa(len(data)))
|
||||
if c.Request.Method == http.MethodHead {
|
||||
c.Status(http.StatusOK)
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "image/jpeg", data)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// PersonImageURL handles TMDb/remote people first and falls back to regular
|
||||
// media/library artwork, so the official /Items/{personId}/Images route
|
||||
// works for synthetic person IDs as well as normal item IDs.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
// libraryCoverHandler 输出媒体库封面图(Emby 风格的成员海报拼图)。
|
||||
//
|
||||
// 之前 Web 端是拿两张成员海报在前端用 CSS 拼格子,Emby 客户端则直接拿一张
|
||||
// 评分最高的海报,结果同一个库在不同客户端长得完全不一样。现在服务端生成
|
||||
// 一张 16:9 的拼图(Emby 的 folder image 做法),Emby 客户端、Web 和 App
|
||||
// 都指向这一份,外观统一。
|
||||
func libraryCoverHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := strings.TrimSpace(c.Param("id"))
|
||||
if id == "" || svc == nil || svc.ImageProxy == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "cover unavailable"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 25*time.Second)
|
||||
defer cancel()
|
||||
|
||||
sources, lib := service.LibraryCoverSourcesForLibrary(ctx, svc.Repo, id)
|
||||
if lib == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "library not found"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(lib.CoverURL) != "" {
|
||||
// 管理员自定义封面优先,保持既有行为(代理该地址)。
|
||||
if err := svc.ImageProxy.Serve(ctx, c.Writer, c.Request, lib.CoverURL); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "custom cover unavailable"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(sources) == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "no library items with artwork"})
|
||||
return
|
||||
}
|
||||
width, height := libraryCoverRequestSize(c)
|
||||
data, err := svc.ImageProxy.LibraryCoverImage(ctx, id, sources, width, height)
|
||||
if err != nil || len(data) == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "cover generation failed"})
|
||||
return
|
||||
}
|
||||
writeLibraryCoverImage(c, data, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
// libraryCoverRequestSize 解析请求的封面尺寸:Web 用 w/h,Emby 用
|
||||
// maxWidth/maxHeight,两种都兼容。服务端统一输出 16:9 画布(与该库在 Emby
|
||||
// 里上报的 PrimaryImageAspectRatio 一致),客户端传的尺寸只当作「不超过」的
|
||||
// 边界使用。
|
||||
func libraryCoverRequestSize(c *gin.Context) (int, int) {
|
||||
return firstPositiveQueryIntParam(c, "maxWidth", "maxwidth", "width", "w"),
|
||||
firstPositiveQueryIntParam(c, "maxHeight", "maxheight", "height", "h")
|
||||
}
|
||||
|
||||
func firstPositiveQueryIntParam(c *gin.Context, names ...string) int {
|
||||
for _, name := range names {
|
||||
raw := strings.TrimSpace(c.Query(name))
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
if f, err := strconv.ParseFloat(raw, 64); err == nil && f > 0 {
|
||||
return int(f)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func writeLibraryCoverImage(c *gin.Context, data []byte, status int) {
|
||||
sum := sha256.Sum256(data)
|
||||
etag := `"` + hex.EncodeToString(sum[:8]) + `"`
|
||||
c.Header("ETag", etag)
|
||||
c.Header("Cache-Control", "public, max-age=300, stale-while-revalidate=86400")
|
||||
if match := strings.TrimSpace(c.GetHeader("If-None-Match")); match != "" && match == etag {
|
||||
c.Status(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
c.Header("Content-Type", "image/jpeg")
|
||||
c.Header("Content-Length", strconv.Itoa(len(data)))
|
||||
if c.Request.Method == http.MethodHead {
|
||||
c.Status(status)
|
||||
return
|
||||
}
|
||||
c.Data(status, "image/jpeg", data)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/glebarez/sqlite"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/config"
|
||||
"github.com/truewhile/MeBox/internal/middleware"
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
"github.com/truewhile/MeBox/internal/repository"
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
func coverTestToken(t *testing.T, secret, userID string) string {
|
||||
t.Helper()
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, middleware.Claims{
|
||||
UserID: userID,
|
||||
Role: "admin",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
Subject: userID,
|
||||
},
|
||||
})
|
||||
signed, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatalf("sign token: %v", err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
|
||||
// TestLibraryCoverRouteServesImageThroughFullRouter 走完整的 handler.Register
|
||||
// 路由表请求封面:既验证路由挂载正确,也验证鉴权链(AuthRequired +
|
||||
// activeUserRequired)不会把它挡成 404。
|
||||
func TestLibraryCoverRouteServesImageThroughFullRouter(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
const secret = "test-secret"
|
||||
|
||||
poster := coverTestJPEG(t, color.RGBA{R: 200, G: 120, B: 60, A: 255})
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
_, _ = w.Write(poster)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
parsed, _ := url.Parse(upstream.URL)
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.Library{}, &model.Media{}, &model.User{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
repos := repository.New(db)
|
||||
user := model.User{Base: model.Base{ID: "user-1"}, Username: "viewer", IsActive: true}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
lib := model.Library{Name: "电影", Path: "/media/movies", Type: "movie", Enabled: true}
|
||||
if err := repos.Library.Create(t.Context(), &lib); err != nil {
|
||||
t.Fatalf("create library: %v", err)
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
row := model.Media{
|
||||
Base: model.Base{ID: "m" + string(rune('a'+i))},
|
||||
LibraryID: lib.ID,
|
||||
Title: "Movie " + string(rune('A'+i)),
|
||||
Path: "/media/movies/m" + string(rune('a'+i)) + ".mkv",
|
||||
PosterURL: upstream.URL + "/p" + string(rune('1'+i)) + ".jpg",
|
||||
}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatalf("create media: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cfg := &config.Config{
|
||||
Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")},
|
||||
Secrets: config.SecretsConfig{JWTSecret: secret},
|
||||
}
|
||||
proxy := service.NewImageProxy(cfg, zap.NewNop())
|
||||
proxy.SetAllowedRemoteHostsProvider(func() []string { return []string{parsed.Host} })
|
||||
svc := &service.Container{Repo: repos, ImageProxy: proxy}
|
||||
|
||||
engine := gin.New()
|
||||
Register(engine, cfg, zap.NewNop(), svc)
|
||||
|
||||
token := coverTestToken(t, secret, user.ID)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/libraries/"+lib.ID+"/cover?w=480&h=270&api_key="+token, nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "image/jpeg" {
|
||||
t.Fatalf("content type = %q, want image/jpeg", ct)
|
||||
}
|
||||
img, err := jpeg.Decode(bytes.NewReader(w.Body.Bytes()))
|
||||
if err != nil {
|
||||
t.Fatalf("decode cover: %v", err)
|
||||
}
|
||||
if img.Bounds().Dx() != 480 || img.Bounds().Dy() != 270 {
|
||||
t.Fatalf("cover size = %v, want 480x270", img.Bounds())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/glebarez/sqlite"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/truewhile/MeBox/internal/config"
|
||||
"github.com/truewhile/MeBox/internal/model"
|
||||
"github.com/truewhile/MeBox/internal/repository"
|
||||
"github.com/truewhile/MeBox/internal/service"
|
||||
)
|
||||
|
||||
func coverTestJPEG(t *testing.T, c color.RGBA) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 160, 240))
|
||||
for y := 0; y < 240; y++ {
|
||||
for x := 0; x < 160; x++ {
|
||||
img.Set(x, y, c)
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
|
||||
t.Fatalf("encode jpeg: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// newLibraryCoverTestRouter 构造一个带真实图片代理的路由:成员海报来自
|
||||
// 本地 httptest 服务,走的是与生产一致的 ImageProxy 抓取路径。
|
||||
func newLibraryCoverTestRouter(t *testing.T) (*gin.Engine, *repository.Container, *httptest.Server) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
poster := coverTestJPEG(t, color.RGBA{R: 200, G: 120, B: 60, A: 255})
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
_, _ = w.Write(poster)
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.Library{}, &model.Media{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
repos := repository.New(db)
|
||||
|
||||
parsed, err := url.Parse(upstream.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("parse upstream: %v", err)
|
||||
}
|
||||
cfg := &config.Config{Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")}}
|
||||
proxy := service.NewImageProxy(cfg, zap.NewNop())
|
||||
proxy.SetAllowedRemoteHostsProvider(func() []string { return []string{parsed.Host} })
|
||||
|
||||
svc := &service.Container{Repo: repos, ImageProxy: proxy}
|
||||
router := gin.New()
|
||||
router.GET("/libraries/:id/cover", libraryCoverHandler(svc))
|
||||
router.HEAD("/libraries/:id/cover", libraryCoverHandler(svc))
|
||||
return router, repos, upstream
|
||||
}
|
||||
|
||||
func seedCoverLibrary(t *testing.T, repos *repository.Container, posterBase string, coverURL string) model.Library {
|
||||
t.Helper()
|
||||
lib := model.Library{Name: "电影", Path: "/media/movies", Type: "movie", Enabled: true, CoverURL: coverURL}
|
||||
if err := repos.Library.Create(t.Context(), &lib); err != nil {
|
||||
t.Fatalf("create library: %v", err)
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
row := model.Media{
|
||||
Base: model.Base{ID: "m" + string(rune('a'+i))},
|
||||
LibraryID: lib.ID,
|
||||
Title: "Movie " + string(rune('A'+i)),
|
||||
Path: "/media/movies/m" + string(rune('a'+i)) + ".mkv",
|
||||
PosterURL: posterBase + "/p" + string(rune('1'+i)) + ".jpg",
|
||||
}
|
||||
if err := repos.DB.Create(&row).Error; err != nil {
|
||||
t.Fatalf("create media: %v", err)
|
||||
}
|
||||
}
|
||||
return lib
|
||||
}
|
||||
|
||||
// TestLibraryCoverHandlerServesGeneratedCollage 覆盖 Web/App 的封面接口:
|
||||
// 返回的是服务端拼好的 16:9 图片,而不是单张成员海报。
|
||||
func TestLibraryCoverHandlerServesGeneratedCollage(t *testing.T) {
|
||||
router, repos, upstream := newLibraryCoverTestRouter(t)
|
||||
lib := seedCoverLibrary(t, repos, upstream.URL, "")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/libraries/"+lib.ID+"/cover?w=480&h=270", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "image/jpeg" {
|
||||
t.Fatalf("content type = %q, want image/jpeg", ct)
|
||||
}
|
||||
img, err := jpeg.Decode(bytes.NewReader(w.Body.Bytes()))
|
||||
if err != nil {
|
||||
t.Fatalf("decode cover: %v", err)
|
||||
}
|
||||
if img.Bounds().Dx() != 480 || img.Bounds().Dy() != 270 {
|
||||
t.Fatalf("cover size = %v, want 480x270", img.Bounds())
|
||||
}
|
||||
if etag := w.Header().Get("ETag"); etag == "" {
|
||||
t.Fatal("expected an ETag so clients can revalidate")
|
||||
}
|
||||
|
||||
// 条件请求应拿到 304。
|
||||
req = httptest.NewRequest(http.MethodGet, "/libraries/"+lib.ID+"/cover?w=480&h=270", nil)
|
||||
req.Header.Set("If-None-Match", w.Header().Get("ETag"))
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotModified {
|
||||
t.Fatalf("conditional request status = %d, want 304", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryCoverHandlerUnknownLibraryReturns404(t *testing.T) {
|
||||
router, _, _ := newLibraryCoverTestRouter(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/libraries/missing/cover", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLibraryCoverHandlerServesCustomCover 管理员填了 cover_url 时必须继续
|
||||
// 用自定义封面,不能在不知不觉中换成拼图。
|
||||
func TestLibraryCoverHandlerServesCustomCover(t *testing.T) {
|
||||
router, repos, upstream := newLibraryCoverTestRouter(t)
|
||||
lib := seedCoverLibrary(t, repos, upstream.URL, upstream.URL+"/custom.jpg")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/libraries/"+lib.ID+"/cover", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if _, err := jpeg.Decode(bytes.NewReader(w.Body.Bytes())); err != nil {
|
||||
t.Fatalf("custom cover should be an image: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbyLibraryPrimaryUsesGeneratedCollage 保证 Emby 客户端请求库主图时
|
||||
// 拿到的也是拼图(与 Web/App 同一份生成逻辑)。
|
||||
func TestEmbyLibraryPrimaryUsesGeneratedCollage(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open db: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.Library{}, &model.Media{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
|
||||
poster := coverTestJPEG(t, color.RGBA{G: 180, R: 90, B: 60, A: 255})
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
_, _ = w.Write(poster)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
parsed, _ := url.Parse(upstream.URL)
|
||||
|
||||
repos := repository.New(db)
|
||||
lib := model.Library{Name: "剧集", Path: "/media/tv", Type: "tv", Enabled: true}
|
||||
if err := repos.Library.Create(t.Context(), &lib); err != nil {
|
||||
t.Fatalf("create library: %v", err)
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
row := model.Media{
|
||||
Base: model.Base{ID: "e" + string(rune('a'+i))},
|
||||
LibraryID: lib.ID,
|
||||
Title: "Show " + string(rune('A'+i)),
|
||||
Path: "/media/tv/show" + string(rune('a'+i)) + "/S01E01.mkv",
|
||||
SeasonNum: 1, EpisodeNum: 1,
|
||||
PosterURL: upstream.URL + "/p" + string(rune('1'+i)) + ".jpg",
|
||||
}
|
||||
if err := repos.DB.Create(&row).Error; err != nil {
|
||||
t.Fatalf("create media: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cfg := &config.Config{Cache: config.CacheConfig{CacheDir: filepath.Join(t.TempDir(), "cache")}}
|
||||
proxy := service.NewImageProxy(cfg, zap.NewNop())
|
||||
proxy.SetAllowedRemoteHostsProvider(func() []string { return []string{parsed.Host} })
|
||||
svc := &service.Container{
|
||||
Repo: repos,
|
||||
Emby: service.NewEmbyService(cfg, zap.NewNop(), repos),
|
||||
ImageProxy: proxy,
|
||||
}
|
||||
router := gin.New()
|
||||
registerEmbyRoutes(router, "test-secret", svc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/Items/"+lib.ID+"/Images/Primary?maxWidth=400&maxHeight=300", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
img, err := jpeg.Decode(bytes.NewReader(w.Body.Bytes()))
|
||||
if err != nil {
|
||||
t.Fatalf("decode emby library cover: %v", err)
|
||||
}
|
||||
// 请求的是 400×300 的盒子,拼图按 16:9 装进去 → 400×225。
|
||||
if img.Bounds().Dx() != 400 || img.Bounds().Dy() != 225 {
|
||||
t.Fatalf("cover size = %v, want 400x225 (16:9 inside the requested box)", img.Bounds())
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -40,6 +41,25 @@ type webLibraryPayload struct {
|
||||
RemoteSource string `json:"remote_source,omitempty"`
|
||||
Total int64 `json:"total,omitempty"`
|
||||
Cards []service.SeriesCardView `json:"cards,omitempty"`
|
||||
// CoverImageURL 是客户端可直接使用的「有效封面」:管理员自定义的
|
||||
// cover_url 优先,否则指向服务端生成的成员海报拼图接口。Web / App 都
|
||||
// 读这一个字段,避免各自用卡片在前端拼格子、长得还不一样。
|
||||
CoverImageURL string `json:"cover_image_url,omitempty"`
|
||||
}
|
||||
|
||||
// effectiveLibraryCoverURL 计算库封面的有效地址。远程挂载库的封面由上游
|
||||
// Emby 决定,这里返回空串,调用方继续用卡片拼图兜底。
|
||||
func effectiveLibraryCoverURL(lib model.Library, isRemote bool) string {
|
||||
if isRemote {
|
||||
return ""
|
||||
}
|
||||
if raw := strings.TrimSpace(lib.CoverURL); raw != "" {
|
||||
return raw
|
||||
}
|
||||
if strings.TrimSpace(lib.ID) == "" {
|
||||
return ""
|
||||
}
|
||||
return "/api/libraries/" + url.PathEscape(lib.ID) + "/cover"
|
||||
}
|
||||
|
||||
// remoteLibraryPreviewBudget 限制 /api/libraries?with_preview=1 里远程 Emby
|
||||
@@ -124,9 +144,10 @@ func listLibrariesHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
for _, p := range previews {
|
||||
out = append(out, webLibraryPayload{
|
||||
Library: p.Library,
|
||||
Total: p.Total,
|
||||
Cards: service.NewSeriesCardViews(p.Cards),
|
||||
Library: p.Library,
|
||||
Total: p.Total,
|
||||
Cards: service.NewSeriesCardViews(p.Cards),
|
||||
CoverImageURL: effectiveLibraryCoverURL(p.Library, false),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -145,7 +166,7 @@ func listLibrariesHandler(svc *service.Container) gin.HandlerFunc {
|
||||
if counts != nil {
|
||||
total = counts[l.ID]
|
||||
}
|
||||
out = append(out, webLibraryPayload{Library: l, Total: total})
|
||||
out = append(out, webLibraryPayload{Library: l, Total: total, CoverImageURL: effectiveLibraryCoverURL(l, false)})
|
||||
}
|
||||
}
|
||||
// 精确指定目标库时,如果目标全是本地库,就不必枚举远程挂载。
|
||||
@@ -272,9 +293,9 @@ func getLibraryHandler(svc *service.Container) gin.HandlerFunc {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, webLibraryPayload{Library: libs[0]})
|
||||
c.JSON(http.StatusOK, webLibraryPayload{Library: libs[0], CoverImageURL: effectiveLibraryCoverURL(libs[0], false)})
|
||||
} else {
|
||||
c.JSON(http.StatusOK, webLibraryPayload{Library: *lib})
|
||||
c.JSON(http.StatusOK, webLibraryPayload{Library: *lib, CoverImageURL: effectiveLibraryCoverURL(*lib, false)})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ func registerAuthedLibraryRoutes(authed *gin.RouterGroup, svc *service.Container
|
||||
authed.GET("/libraries", listLibrariesHandler(svc))
|
||||
authed.POST("/libraries", middleware.AdminRequired(), createLibraryHandler(svc))
|
||||
authed.GET("/libraries/:id", getLibraryHandler(svc))
|
||||
// 服务端生成的媒体库封面(成员海报拼图),Web / App / Emby 共用同一份。
|
||||
authed.GET("/libraries/:id/cover", libraryCoverHandler(svc))
|
||||
authed.HEAD("/libraries/:id/cover", libraryCoverHandler(svc))
|
||||
authed.PATCH("/libraries/:id", middleware.AdminRequired(), updateLibraryHandler(svc))
|
||||
authed.PUT("/libraries/reorder", middleware.AdminRequired(), reorderLibrariesHandler(svc))
|
||||
authed.DELETE("/libraries/:id", middleware.AdminRequired(), deleteLibraryHandler(svc))
|
||||
|
||||
Reference in New Issue
Block a user