添加跳过片头片尾功能

This commit is contained in:
truewhile
2026-09-23 10:22:13 +08:00
parent 016c6687e9
commit 94ef0116b1
26 changed files with 2115 additions and 4 deletions
+151
View File
@@ -0,0 +1,151 @@
// Package handler — Emby / Jellyfin 媒体分段(片头、片尾)兼容接口。
//
// GET /MediaSegments/{itemId}
// GET /Items/{itemId}/MediaSegments
// GET /Users/{userId}/Items/{itemId}/MediaSegments
//
// 契约对齐 Jellyfin 10.10 引入的 Media Segments API(Emby 采用同一形状),
// 也是 TheIntroDB 官方 Jellyfin 插件走的同一条路:
//
// QueryResult<MediaSegmentDto> = {"Items": [...], "TotalRecordCount": N}
// MediaSegmentDto = {"Id", "ItemId", "Type", "StartTicks", "EndTicks"}
//
// 时间是 .NET ticks(1 tick = 100ns,即每秒 10,000,000、每毫秒 10,000);
// Type 是枚举名字符串 Intro / Outro / Recap / Preview / Commercial。
package handler
import (
"context"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/service"
)
// 第三方客户端会在起播前后同步请求分段,不能被一次外网抓取无限拖住。超时后
// 退回已有缓存(可能为空),请求本身永远不失败。
const embyMediaSegmentsFetchBudget = 5 * time.Second
// 1 秒 = 10,000,000 ticks => 1 毫秒 = 10,000 ticks。
const embyTicksPerMillisecond int64 = 10_000
func embyMediaSegmentsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
// 未知条目、虚拟剧集/季、远程 Emby 挂载、以及当前不可见的内容一律返回
// 空结果而不是 404:客户端会把 404 判成「条目损坏」(同 emby_routes.go
// 里 AdditionalParts 的说明),而「没有可跳过的片段」本来就是个合法状态。
empty := gin.H{"Items": []any{}, "TotalRecordCount": 0}
if svc == nil || svc.Repo == nil || svc.Segments == nil {
c.JSON(http.StatusOK, empty)
return
}
id := c.Param("id")
// 远程 Emby 挂载的条目是上游库的投影,本地没有可查询的外部 ID 关联。
if service.IsEmbyRemoteID(id) {
c.JSON(http.StatusOK, empty)
return
}
m, err := svc.Repo.Media.FindByID(c.Request.Context(), id)
if err != nil || m == nil || !mediaVisibleForRequest(c, svc, m) {
c.JSON(http.StatusOK, empty)
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), embyMediaSegmentsFetchBudget)
defer cancel()
rows, listErr := svc.Segments.ListForPlayback(ctx, m)
if listErr != nil && svc.Log != nil {
svc.Log.Debug("emby media segments lookup failed",
zap.String("media_id", m.ID), zap.Error(listErr))
}
items := embySegmentItems(m, rows, embyRequestedSegmentTypes(c))
c.JSON(http.StatusOK, gin.H{"Items": items, "TotalRecordCount": len(items)})
}
}
// embySegmentItems 把库内片段转换成 MediaSegmentDto 列表。
func embySegmentItems(m *model.Media, rows []model.MediaSegment, want map[string]bool) []gin.H {
// 末段在库内用 end_ms = 0 表示「一直到片尾」(TheIntroDB 对片尾返回 end_ms: null),
// 这里必须换算成真实结束时间;拿不到时长就丢弃该分段,否则会给出一个零长度区间,
// 客户端要么忽略要么画出一个错误的跳转点。
durationMs := int64(m.DurationSec) * 1000
items := make([]gin.H, 0, len(rows))
for _, row := range rows {
typeName := embySegmentTypeName(row.Kind)
if typeName == "" {
continue
}
if len(want) > 0 && !want[typeName] {
continue
}
endMs := row.EndMs
if endMs <= 0 {
if durationMs <= 0 {
continue
}
endMs = durationMs
}
if endMs <= row.StartMs {
continue
}
items = append(items, gin.H{
"Id": row.ID,
"ItemId": m.ID,
"Type": typeName,
"StartTicks": row.StartMs * embyTicksPerMillisecond,
"EndTicks": endMs * embyTicksPerMillisecond,
})
}
return items
}
// embySegmentTypeName 把库内 kind 映射成 Emby/Jellyfin 的 MediaSegmentType 名字。
// 库内的 credits 取自 TheIntroDB 的字段名,在 Emby 一侧对应 Outro。
func embySegmentTypeName(kind string) string {
switch kind {
case model.SegmentKindIntro:
return "Intro"
case model.SegmentKindRecap:
return "Recap"
case model.SegmentKindCredits:
return "Outro"
case model.SegmentKindPreview:
return "Preview"
default:
return ""
}
}
// embyRequestedSegmentTypes 解析 includeSegmentTypes(Jellyfin 的过滤参数)。
// 支持重复参数与逗号分隔两种写法;返回空集合表示不过滤。
//
// 只认枚举名字符串。数字枚举虽然 ASP.NET 模型绑定也接受,但各家定义的顺序并
// 不一致,猜错会把过滤结果算错;认不出来时按「不过滤」处理,返回的是超集,
// 客户端自己仍会再过滤一次。
func embyRequestedSegmentTypes(c *gin.Context) map[string]bool {
raw := make([]string, 0, 4)
for _, key := range []string{"includeSegmentTypes", "IncludeSegmentTypes", "includesegmenttypes"} {
raw = append(raw, c.QueryArray(key)...)
}
want := make(map[string]bool, len(raw))
for _, value := range raw {
for _, part := range strings.Split(value, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
for _, name := range []string{"Intro", "Outro", "Recap", "Preview", "Commercial"} {
if strings.EqualFold(part, name) {
want[name] = true
}
}
}
}
return want
}
@@ -0,0 +1,217 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"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"
)
type embySegmentsPayload struct {
Items []struct {
ID string `json:"Id"`
ItemID string `json:"ItemId"`
Type string `json:"Type"`
StartTicks int64 `json:"StartTicks"`
EndTicks int64 `json:"EndTicks"`
} `json:"Items"`
TotalRecordCount int `json:"TotalRecordCount"`
}
// 电影:intro 有明确结束点;credits 的 end_ms 为 null(库内落成 0),
// 必须用媒体时长补齐 —— 这是最容易写错的一处。
const embySegmentsProviderBody = `{"tmdb_id":27205,"type":"movie","intro":[{"start_ms":null,"end_ms":38000}],"credits":[{"start_ms":6480000,"end_ms":null}]}`
const (
embySegmentsMovieDurationSec = 8880
embySegmentsTicksPerSecond = 10_000_000
)
func newEmbySegmentsTestRouter(t *testing.T, durationSec int) (*gin.Engine, string, *int32) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(model.AllModels()...); err != nil {
t.Fatal(err)
}
repos := repository.New(db)
if err := repos.User.Create(t.Context(), &model.User{
Base: model.Base{ID: "user-1"},
Username: "tester",
PasswordHash: "x",
Role: "admin",
Tier: "plus",
IsActive: true,
}); err != nil {
t.Fatal(err)
}
lib := model.Library{Base: model.Base{ID: "lib-movies"}, Name: "电影", Path: "D:\\media\\movies", Type: "movie", Enabled: true}
if err := repos.Library.Create(t.Context(), &lib); err != nil {
t.Fatal(err)
}
if err := db.Create(&model.Media{
Base: model.Base{ID: "movie-1"},
LibraryID: lib.ID,
Title: "Inception",
Path: "D:\\media\\movies\\Inception.mkv",
DurationSec: durationSec,
TMDbID: 27205,
}).Error; err != nil {
t.Fatal(err)
}
var calls int32
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&calls, 1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(embySegmentsProviderBody))
}))
t.Cleanup(provider.Close)
segments := service.NewMediaSegmentService(zap.NewNop(), repos).
SetIntroDB(service.NewIntroDBService(zap.NewNop()).SetBaseURL(provider.URL))
const secret = "test-secret"
router := gin.New()
registerEmbyRoutes(router, secret, &service.Container{
Repo: repos,
Emby: service.NewEmbyService(&config.Config{}, zap.NewNop(), repos),
Segments: segments,
Log: zap.NewNop(),
})
return router, secret, &calls
}
func embySegmentsRequest(t *testing.T, router *gin.Engine, secret, path string) embySegmentsPayload {
t.Helper()
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("X-Emby-Token", signedTestToken(t, secret))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("%s status = %d body=%s", path, w.Code, w.Body.String())
}
var payload embySegmentsPayload
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("%s decode: %v", path, err)
}
return payload
}
func TestEmbyMediaSegmentsReturnsTicksAndMapsCreditsToOutro(t *testing.T) {
router, secret, _ := newEmbySegmentsTestRouter(t, embySegmentsMovieDurationSec)
payload := embySegmentsRequest(t, router, secret, "/MediaSegments/movie-1")
if payload.TotalRecordCount != 2 || len(payload.Items) != 2 {
t.Fatalf("segments = %#v (total %d), want 2", payload.Items, payload.TotalRecordCount)
}
intro := payload.Items[0]
if intro.Type != "Intro" || intro.ItemID != "movie-1" || intro.ID == "" {
t.Fatalf("intro segment = %#v", intro)
}
// start_ms null 表示从片头开始。
if intro.StartTicks != 0 || intro.EndTicks != 38*embySegmentsTicksPerSecond {
t.Fatalf("intro ticks = %d..%d, want 0..%d",
intro.StartTicks, intro.EndTicks, 38*embySegmentsTicksPerSecond)
}
// 库内 credits 在 Emby 一侧是 Outro;end_ms = 0 必须按媒体时长补齐,
// 否则客户端会拿到一个零长度区间。
outro := payload.Items[1]
if outro.Type != "Outro" {
t.Fatalf("credits should map to Outro, got %q", outro.Type)
}
if outro.StartTicks != 6480*embySegmentsTicksPerSecond {
t.Fatalf("outro StartTicks = %d, want %d", outro.StartTicks, 6480*embySegmentsTicksPerSecond)
}
if outro.EndTicks != embySegmentsMovieDurationSec*embySegmentsTicksPerSecond {
t.Fatalf("outro EndTicks = %d, want the media duration %d",
outro.EndTicks, embySegmentsMovieDurationSec*embySegmentsTicksPerSecond)
}
}
func TestEmbyMediaSegmentsIsServedFromTheSameCacheAsTheWebPlayer(t *testing.T) {
router, secret, calls := newEmbySegmentsTestRouter(t, embySegmentsMovieDurationSec)
// 多条路径 + 大小写变体都应命中同一份缓存,而不是各自再打一次外网。
for _, path := range []string{
"/MediaSegments/movie-1",
"/mediasegments/movie-1",
"/Items/movie-1/MediaSegments",
"/items/movie-1/mediasegments",
"/Users/user-1/Items/movie-1/MediaSegments",
} {
payload := embySegmentsRequest(t, router, secret, path)
if len(payload.Items) != 2 {
t.Fatalf("%s returned %#v, want 2 segments", path, payload.Items)
}
}
if got := atomic.LoadInt32(calls); got != 1 {
t.Fatalf("provider calls = %d, want 1 (all routes share the cached rows)", got)
}
}
func TestEmbyMediaSegmentsHonoursIncludeSegmentTypes(t *testing.T) {
router, secret, _ := newEmbySegmentsTestRouter(t, embySegmentsMovieDurationSec)
payload := embySegmentsRequest(t, router, secret, "/MediaSegments/movie-1?includeSegmentTypes=Intro")
if payload.TotalRecordCount != 1 || len(payload.Items) != 1 {
t.Fatalf("filtered segments = %#v (total %d), want only Intro", payload.Items, payload.TotalRecordCount)
}
if payload.Items[0].Type != "Intro" {
t.Fatalf("filtered type = %q, want Intro", payload.Items[0].Type)
}
// 认不出的枚举名按「不过滤」处理:返回超集比返回空集安全。
payload = embySegmentsRequest(t, router, secret, "/MediaSegments/movie-1?includeSegmentTypes=NotAType")
if payload.TotalRecordCount != 2 {
t.Fatalf("unknown filter returned %d segments, want the unfiltered set", payload.TotalRecordCount)
}
}
func TestEmbyMediaSegmentsDropsOpenEndedRangeWhenDurationUnknown(t *testing.T) {
// 时长未知(STRM/云盘媒体探测前)时,credits 无法换算成真实结束点,
// 只能丢弃;有明确结束点的 intro 必须保留。
router, secret, _ := newEmbySegmentsTestRouter(t, 0)
payload := embySegmentsRequest(t, router, secret, "/MediaSegments/movie-1")
if payload.TotalRecordCount != 1 || len(payload.Items) != 1 {
t.Fatalf("segments = %#v (total %d), want only the intro", payload.Items, payload.TotalRecordCount)
}
if payload.Items[0].Type != "Intro" {
t.Fatalf("kept segment = %#v, want Intro", payload.Items[0])
}
}
func TestEmbyMediaSegmentsReturnsEmptyInsteadOfNotFound(t *testing.T) {
router, secret, calls := newEmbySegmentsTestRouter(t, embySegmentsMovieDurationSec)
// 未知条目必须 200 + 空数组:客户端会把 404 判成「条目损坏」。
payload := embySegmentsRequest(t, router, secret, "/MediaSegments/does-not-exist")
if payload.Items == nil || len(payload.Items) != 0 || payload.TotalRecordCount != 0 {
t.Fatalf("unknown item payload = %#v", payload)
}
// 远程 Emby 条目同理(本地没有可查询的外部 ID 关联)。
payload = embySegmentsRequest(t, router, secret, "/MediaSegments/embyremote~acct1~item1")
if len(payload.Items) != 0 {
t.Fatalf("remote emby item payload = %#v, want empty", payload.Items)
}
if got := atomic.LoadInt32(calls); got != 0 {
t.Fatalf("provider calls = %d, want 0 for unresolvable items", got)
}
}
+3 -1
View File
@@ -198,7 +198,9 @@ func registerEmbyAuthenticatedItemRoutes(auth *gin.RouterGroup, svc *service.Con
auth.GET("/Users/:userId/Shows/:id/Episodes", embyShowEpisodesHandler(svc))
auth.GET("/Shows/NextUp", embyNextUpHandler(svc))
auth.GET("/Users/:userId/Shows/NextUp", embyNextUpHandler(svc))
auth.GET("/MediaSegments/:id", embyEmptyItemsHandler(svc))
auth.GET("/MediaSegments/:id", embyMediaSegmentsHandler(svc))
auth.GET("/Items/:id/MediaSegments", embyMediaSegmentsHandler(svc))
auth.GET("/Users/:userId/Items/:id/MediaSegments", embyMediaSegmentsHandler(svc))
auth.GET("/Artists", embyEmptyItemsHandler(svc))
auth.GET("/Persons", embyEmptyItemsHandler(svc))
auth.GET("/Genres", embyGenresHandler(svc))
+3 -1
View File
@@ -42,7 +42,9 @@ func registerLowercaseEmbyItemRoutes(auth *gin.RouterGroup, svc *service.Contain
auth.GET("/users/:userId/shows/:id/episodes", embyShowEpisodesHandler(svc))
auth.GET("/shows/nextup", embyNextUpHandler(svc))
auth.GET("/users/:userId/shows/nextup", embyNextUpHandler(svc))
auth.GET("/mediasegments/:id", embyEmptyItemsHandler(svc))
auth.GET("/mediasegments/:id", embyMediaSegmentsHandler(svc))
auth.GET("/items/:id/mediasegments", embyMediaSegmentsHandler(svc))
auth.GET("/users/:userId/items/:id/mediasegments", embyMediaSegmentsHandler(svc))
auth.GET("/artists", embyEmptyItemsHandler(svc))
auth.GET("/persons", embyEmptyItemsHandler(svc))
auth.GET("/genres", embyGenresHandler(svc))
+4
View File
@@ -346,6 +346,9 @@ func newPlaybackScopeTestRouter(t *testing.T) (*gin.Engine, *service.Container,
&model.Library{},
&model.Media{},
&model.PlayProfile{},
&model.Series{},
&model.MediaSegment{},
&model.MediaSegmentFetch{},
); err != nil {
t.Fatal(err)
}
@@ -408,6 +411,7 @@ func newPlaybackScopeTestRouter(t *testing.T) (*gin.Engine, *service.Container,
api := router.Group("/api")
api.Use(middleware.AuthRequired(cfg.Secrets.JWTSecret))
api.GET("/playback/:id/info", playbackInfoHandler(svc))
api.GET("/playback/:id/segments", playbackSegmentsHandler(svc))
api.GET("/playback/:id/external-url", externalURLHandler(svc))
api.GET("/playback/:id/external-players", externalPlayersHandler(svc))
api.GET("/stream/:id", streamHandler(svc))
+55
View File
@@ -0,0 +1,55 @@
// Package handler — 片头/片尾片段接口。
//
// GET /playback/:id/segments
//
// 单独开一个接口而不是塞进 /media/:id/playback,有两个原因:一是抓取外部数据
// 可能要几秒,不能拖慢决定能否起播的那个请求;二是片段与播放来源(本地 / 云盘 /
// 远程 Emby)无关,独立出来对所有媒体一致。
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/truewhile/MeBox/internal/service"
)
// playbackSegmentsHandler returns the skippable ranges for one media item.
// The client calls it after playback has already started, so the provider
// lookup never delays a play.
func playbackSegmentsHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
autoSkip := resolveAutoSkipFlag(c, svc)
segments := []service.SegmentView{}
m, err := findMediaForPlaybackEndpoint(c, svc, c.Param("id"))
if err != nil || m == nil || !mediaVisibleForRequest(c, svc, m) {
c.JSON(http.StatusNotFound, gin.H{"error": "media not found"})
return
}
// 远程 Emby 挂载的条目是上游库的投影,本地没有可查询的外部 ID 关联。
if svc.Segments != nil && !service.IsEmbyRemoteID(m.ID) {
rows, listErr := svc.Segments.ListForPlayback(c.Request.Context(), m)
if listErr != nil && svc.Log != nil {
svc.Log.Debug("list media segments failed",
zap.String("media_id", m.ID), zap.Error(listErr))
}
segments = service.ToSegmentViews(rows)
}
c.JSON(http.StatusOK, gin.H{"segments": segments, "auto_skip": autoSkip})
}
}
// resolveAutoSkipFlag reads the「自动跳过片头」switch off whichever profile is
// currently in effect. It reuses selectedPlayProfile so the server agrees with
// the UI about which profile is active (explicit header first, then the user's
// default profile), and a PIN-locked profile never silently skips for the user.
func resolveAutoSkipFlag(c *gin.Context, svc *service.Container) bool {
profile, locked := selectedPlayProfile(c, svc)
if locked || profile == nil {
return false
}
return profile.SkipIntro
}
+134
View File
@@ -0,0 +1,134 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"go.uber.org/zap"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/service"
)
type segmentPayload struct {
Segments []struct {
Kind string `json:"kind"`
StartMs int64 `json:"start_ms"`
EndMs int64 `json:"end_ms"`
} `json:"segments"`
AutoSkip bool `json:"auto_skip"`
}
const segmentsProviderBody = `{"tmdb_id":27205,"type":"movie","intro":[{"start_ms":null,"end_ms":38000}],"credits":[{"start_ms":6480000,"end_ms":null}]}`
func TestPlaybackSegmentsReturnsProviderDataAndAutoSkip(t *testing.T) {
router, svc, secret := newPlaybackScopeTestRouter(t)
// 片段数据与播放来源无关,云盘媒体同样适用,只要它能解析出外部 ID。
// 注意列名是 tm_db_id(GORM 对 TMDbID 的默认命名)。
if err := svc.Repo.DB.Model(&model.Media{}).
Where("id = ?", "media-1").Update("tm_db_id", 27205).Error; err != nil {
t.Fatal(err)
}
var calls int32
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
atomic.AddInt32(&calls, 1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(segmentsProviderBody))
}))
defer provider.Close()
svc.Segments = service.NewMediaSegmentService(zap.NewNop(), svc.Repo).
SetIntroDB(service.NewIntroDBService(zap.NewNop()).SetBaseURL(provider.URL))
// 默认档案打开「自动跳过片头」,接口应把开关原样带出来。
if err := svc.Repo.DB.Create(&model.PlayProfile{
Base: model.Base{ID: "profile-1"},
UserID: "user-1",
Name: "主档案",
IsDefault: true,
SkipIntro: true,
}).Error; err != nil {
t.Fatal(err)
}
loginToken := signedTestToken(t, secret)
fetch := func() segmentPayload {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "http://nas.local/api/playback/media-1/segments", nil)
req.Header.Set("Authorization", "Bearer "+loginToken)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
}
var payload segmentPayload
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode: %v", err)
}
return payload
}
first := fetch()
if !first.AutoSkip {
t.Fatal("auto_skip should reflect the active profile's skip_intro switch")
}
if len(first.Segments) != 2 {
t.Fatalf("segments = %#v, want 2", first.Segments)
}
// start_ms: null -> 0;end_ms: null -> 0(延续到片尾,由客户端按时长补齐)。
if first.Segments[0].Kind != "intro" || first.Segments[0].StartMs != 0 || first.Segments[0].EndMs != 38_000 {
t.Fatalf("intro segment = %#v", first.Segments[0])
}
if first.Segments[1].Kind != "credits" || first.Segments[1].StartMs != 6_480_000 || first.Segments[1].EndMs != 0 {
t.Fatalf("credits segment = %#v", first.Segments[1])
}
// 第二次播放必须走本地缓存,不再打外网。
if second := fetch(); len(second.Segments) != 2 {
t.Fatalf("second fetch segments = %#v", second.Segments)
}
if got := atomic.LoadInt32(&calls); got != 1 {
t.Fatalf("provider calls = %d, want 1", got)
}
}
func TestPlaybackSegmentsAutoSkipIsFalseWithoutProfile(t *testing.T) {
router, svc, secret := newPlaybackScopeTestRouter(t)
svc.Segments = service.NewMediaSegmentService(zap.NewNop(), svc.Repo)
req := httptest.NewRequest(http.MethodGet, "http://nas.local/api/playback/media-1/segments", nil)
req.Header.Set("Authorization", "Bearer "+signedTestToken(t, secret))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
}
var payload segmentPayload
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode: %v", err)
}
if payload.AutoSkip {
t.Fatal("auto_skip must default to false")
}
// 即使一条片段都没有,也必须返回空数组而不是 null,前端才能无条件遍历。
if payload.Segments == nil {
t.Fatal("segments must serialise as an empty array, not null")
}
}
func TestPlaybackSegmentsForUnknownMediaReturnsNotFound(t *testing.T) {
router, svc, secret := newPlaybackScopeTestRouter(t)
svc.Segments = service.NewMediaSegmentService(zap.NewNop(), svc.Repo)
req := httptest.NewRequest(http.MethodGet, "http://nas.local/api/playback/does-not-exist/segments", nil)
req.Header.Set("Authorization", "Bearer "+signedTestToken(t, secret))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d body=%s, want 404", w.Code, w.Body.String())
}
}
@@ -73,6 +73,7 @@ func registerAuthedFavoriteAndMediaActionRoutes(authed *gin.RouterGroup, svc *se
func registerAuthedPlaybackExtraRoutes(authed *gin.RouterGroup, svc *service.Container) {
authed.GET("/playback/:id/info", playbackInfoHandler(svc))
authed.GET("/playback/:id/resume", playbackResumeHandler(svc))
authed.GET("/playback/:id/segments", playbackSegmentsHandler(svc))
authed.POST("/playback/:id/progress", playbackProgressHandler(svc))
authed.GET("/playback/:id/external-players", externalPlayersHandler(svc))
authed.GET("/playback/:id/external-url", externalURLHandler(svc))
@@ -36,6 +36,7 @@ func TestAuthenticatedRouteSurfacesAreRegistered(t *testing.T) {
"GET /api/storage",
"GET /api/watch-history",
"GET /api/playback/:id/info",
"GET /api/playback/:id/segments",
} {
if !routes[want] {
t.Fatalf("%s route is not registered", want)