mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
添加对外挂字幕的支持
添加对字幕的支持
This commit is contained in:
@@ -31,6 +31,38 @@ func embyPlaybackInfoHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// embySubtitleStreamHandler serves an external subtitle track advertised in a
|
||||
// MediaSource's MediaStreams via its Emby index
|
||||
// (/Videos/:id/Subtitles/:index/Stream). The index maps to a discovered
|
||||
// sideloaded subtitle file next to the video (SRT/ASS/SSA/VTT, local or
|
||||
// cloud://), following the same layout appended by mediaStreams.
|
||||
func embySubtitleStreamHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
uid := c.Param("userId")
|
||||
if uid == "" {
|
||||
uid = embyUserID(c)
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
// The official-format route carries a :format suffix (Stream.ass /
|
||||
// Stream.vtt); prefer it for the Content-Type when present, otherwise
|
||||
// fall back to the discovered source codec. :mediaSourceId is ignored —
|
||||
// the item is located by :id and subtitles by :index (1:1 in this shim).
|
||||
format := strings.TrimSpace(c.Param("format"))
|
||||
codec := svc.Emby.SubtitleStreamCodec(ctx, c.Param("id"), c.Param("index"), uid)
|
||||
if codec != "" {
|
||||
if format != "" {
|
||||
codec = service.SubtitleCodecFromFormat(format)
|
||||
}
|
||||
c.Header("Content-Type", service.SubtitleContentType(codec))
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
if err := svc.Emby.ServeSubtitleStream(ctx, c.Writer, c.Param("id"), c.Param("index"), uid); err != nil {
|
||||
embyError(c, http.StatusNotFound, "subtitle not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func embyAttachRequestTokenToMediaSources(c *gin.Context, out any) {
|
||||
token := embyRequestToken(c)
|
||||
if token == "" || out == nil {
|
||||
@@ -83,6 +115,20 @@ func embyAttachTokenToMediaSources(sources []map[string]any, token string) {
|
||||
}
|
||||
source[key] = embyAppendAPIKey(raw, token)
|
||||
}
|
||||
// Subtitle streams advertise a DeliveryUrl; the official Emby client
|
||||
// fetches it directly, so it must carry the auth token too.
|
||||
if streams, ok := source["MediaStreams"].([]map[string]any); ok {
|
||||
for _, stream := range streams {
|
||||
if stream["Type"] != "Subtitle" {
|
||||
continue
|
||||
}
|
||||
raw, ok := stream["DeliveryUrl"].(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
stream["DeliveryUrl"] = embyAppendAPIKey(raw, token)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -192,6 +192,21 @@ func registerEmbyAuthenticatedPlaybackRoutes(auth *gin.RouterGroup, prefix strin
|
||||
auth.POST("/Users/:userId/Items/:id/PlaybackInfo", embyPlaybackInfoHandler(svc))
|
||||
|
||||
registerEmbyVideoStreamRoutes(auth, svc, "/Videos")
|
||||
auth.GET("/Videos/:id/Subtitles/:index/Stream", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/Videos/:id/Subtitles/:index/Stream", embySubtitleStreamHandler(svc))
|
||||
auth.GET("/Users/:userId/Videos/:id/Subtitles/:index/Stream", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/Users/:userId/Videos/:id/Subtitles/:index/Stream", embySubtitleStreamHandler(svc))
|
||||
// Official Emby/Swagger shape:
|
||||
// /Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}
|
||||
// The mediaSourceId segment is a bare path param. We name it :seg (matching
|
||||
// the HLS /Videos/:id/:seg catch-all) so gin allows the two routes to
|
||||
// coexist — gin permits the same :param name to be both terminal and parent
|
||||
// of children, but rejects two different param names at the same position.
|
||||
// The subtitle handler ignores this segment (lookup is by :id + :index).
|
||||
auth.GET("/Videos/:id/:seg/Subtitles/:index/Stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/Videos/:id/:seg/Subtitles/:index/Stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.GET("/Users/:userId/Videos/:id/:seg/Subtitles/:index/Stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/Users/:userId/Videos/:id/:seg/Subtitles/:index/Stream.:format", embySubtitleStreamHandler(svc))
|
||||
if prefix == "/emby" {
|
||||
auth.GET("/api/stream/:id", embyVideoStreamHandler(svc, service.CloudPlaybackModeSTRM))
|
||||
auth.HEAD("/api/stream/:id", embyVideoStreamHandler(svc, service.CloudPlaybackModeSTRM))
|
||||
|
||||
@@ -62,6 +62,18 @@ func registerLowercaseEmbyPlaybackRoutes(auth *gin.RouterGroup, svc *service.Con
|
||||
auth.POST("/users/:userId/items/:id/playbackinfo", embyPlaybackInfoHandler(svc))
|
||||
|
||||
registerEmbyVideoStreamRoutes(auth, svc, "/videos")
|
||||
auth.GET("/videos/:id/subtitles/:index/stream", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/videos/:id/subtitles/:index/stream", embySubtitleStreamHandler(svc))
|
||||
auth.GET("/users/:userId/videos/:id/subtitles/:index/stream", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/users/:userId/videos/:id/subtitles/:index/stream", embySubtitleStreamHandler(svc))
|
||||
// Official Emby/Swagger shape:
|
||||
// /videos/{Id}/{MediaSourceId}/subtitles/{Index}/stream.{Format}
|
||||
// The mediaSourceId segment is a bare path param named :seg (shared with the
|
||||
// HLS /videos/:id/:seg catch-all) so gin allows both routes to coexist.
|
||||
auth.GET("/videos/:id/:seg/subtitles/:index/stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/videos/:id/:seg/subtitles/:index/stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.GET("/users/:userId/videos/:id/:seg/subtitles/:index/stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.HEAD("/users/:userId/videos/:id/:seg/subtitles/:index/stream.:format", embySubtitleStreamHandler(svc))
|
||||
auth.GET("/videos/:id/master.m3u8", embyVideoHLSPlaylistHandler(svc))
|
||||
auth.HEAD("/videos/:id/master.m3u8", embyVideoHLSPlaylistHandler(svc))
|
||||
auth.GET("/videos/:id/main.m3u8", embyVideoHLSPlaylistHandler(svc))
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/glebarez/sqlite"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/config"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/model"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/service"
|
||||
)
|
||||
|
||||
// TestEmbySubtitleOfficialRouteServesRawASS verifies that the official Emby
|
||||
// subtitle route shape
|
||||
// (/Videos/{itemId}/{mediaSourceId}/Subtitles/{index}/Stream.{format}) is
|
||||
// registered, resolves the media, and streams the RAW ASS bytes — matching the
|
||||
// advertised Codec — so a real Emby client can load the subtitle.
|
||||
func TestEmbySubtitleOfficialRouteServesRawASS(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.AllModels()...); err != nil {
|
||||
t.Fatalf("migrate: %v", 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.Fatalf("create user: %v", err)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
videoPath := filepath.Join(dir, "Movie.mkv")
|
||||
subPath := filepath.Join(dir, "Movie.ass")
|
||||
rawASS := "Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,test line\n"
|
||||
if err := os.WriteFile(videoPath, []byte("video"), 0o644); err != nil {
|
||||
t.Fatalf("write video: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(subPath, []byte(rawASS), 0o644); err != nil {
|
||||
t.Fatalf("write subtitle: %v", err)
|
||||
}
|
||||
|
||||
mediaID := "media-1"
|
||||
if err := db.Create(&model.Media{
|
||||
Base: model.Base{ID: mediaID},
|
||||
LibraryID: "lib-1",
|
||||
Title: "Movie",
|
||||
Path: videoPath,
|
||||
Container: "mkv",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create media: %v", err)
|
||||
}
|
||||
|
||||
const secret = "test-secret"
|
||||
router := gin.New()
|
||||
registerEmbyRoutes(router, secret, &service.Container{
|
||||
Repo: repos,
|
||||
Emby: service.NewEmbyService(&config.Config{}, zap.NewNop(), repos).SetSubtitleService(
|
||||
service.NewSubtitleService(zap.NewNop(), repos),
|
||||
),
|
||||
})
|
||||
|
||||
// Official-format route:
|
||||
// /Videos/{Id}/{MediaSourceId}/Subtitles/{Index}/Stream.{Format}
|
||||
// Index 2 = first subtitle when audio present (Video 0, Audio 1, Sub 2).
|
||||
req := httptest.NewRequest(http.MethodGet, "/emby/Videos/"+mediaID+"/"+mediaID+"/Subtitles/2/Stream.ass", nil)
|
||||
req.Header.Set("X-Emby-Token", signedTestToken(t, secret))
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("unexpected status %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); ct != "text/plain; charset=utf-8" {
|
||||
t.Fatalf("Content-Type = %q, want text/plain", ct)
|
||||
}
|
||||
if got := w.Body.String(); got != rawASS {
|
||||
t.Fatalf("served body = %q, want raw ASS %q", got, rawASS)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEmbySubtitleDeliveryUrlGetsToken ensures the subtitle DeliveryUrl carries
|
||||
// the auth token in PlaybackInfo (delivered via embyAttachTokenToMediaSources).
|
||||
func TestEmbySubtitleDeliveryUrlGetsToken(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.AllModels()...); err != nil {
|
||||
t.Fatalf("migrate: %v", 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.Fatalf("create user: %v", err)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
videoPath := filepath.Join(dir, "Movie.mkv")
|
||||
subPath := filepath.Join(dir, "Movie.ass")
|
||||
if err := os.WriteFile(videoPath, []byte("video"), 0o644); err != nil {
|
||||
t.Fatalf("write video: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(subPath, []byte("Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,x\n"), 0o644); err != nil {
|
||||
t.Fatalf("write subtitle: %v", err)
|
||||
}
|
||||
|
||||
mediaID := "media-1"
|
||||
if err := db.Create(&model.Media{
|
||||
Base: model.Base{ID: mediaID},
|
||||
LibraryID: "lib-1",
|
||||
Title: "Movie",
|
||||
Path: videoPath,
|
||||
Container: "mkv",
|
||||
VideoCodec: "h264",
|
||||
AudioCodec: "aac",
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create media: %v", err)
|
||||
}
|
||||
|
||||
const secret = "test-secret"
|
||||
token := signedTestToken(t, secret)
|
||||
router := gin.New()
|
||||
registerEmbyRoutes(router, secret, &service.Container{
|
||||
Repo: repos,
|
||||
Emby: service.NewEmbyService(&config.Config{}, zap.NewNop(), repos).SetSubtitleService(
|
||||
service.NewSubtitleService(zap.NewNop(), repos),
|
||||
),
|
||||
})
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/emby/Items/"+mediaID+"/PlaybackInfo", nil)
|
||||
req.Header.Set("X-Emby-Token", token)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("unexpected status %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
source := body["MediaSources"].([]any)[0].(map[string]any)
|
||||
streams := source["MediaStreams"].([]any)
|
||||
var deliveryURL string
|
||||
for _, s := range streams {
|
||||
stream := s.(map[string]any)
|
||||
if stream["Type"] == "Subtitle" {
|
||||
deliveryURL, _ = stream["DeliveryUrl"].(string)
|
||||
break
|
||||
}
|
||||
}
|
||||
if deliveryURL == "" {
|
||||
t.Fatalf("no subtitle DeliveryUrl found: %#v", source)
|
||||
}
|
||||
// Official shape with bare MediaSourceId + format suffix and the token appended.
|
||||
wantPrefix := "/Videos/" + mediaID + "/" + mediaID + "/Subtitles/2/Stream.ass"
|
||||
if deliveryURL[:len(wantPrefix)] != wantPrefix {
|
||||
t.Fatalf("DeliveryUrl %q does not start with %q", deliveryURL, wantPrefix)
|
||||
}
|
||||
if !strings.Contains(deliveryURL, "api_key="+token) {
|
||||
t.Fatalf("DeliveryUrl %q missing auth token", deliveryURL)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user