Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion internal/jellycompat/audio_selection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type testCompatSessionManager struct {
sessions map[string]*playback.Session
audioTrackCalls []compatAudioTrackCall
progressCalls int
stopCalls []string
}

type compatAudioTrackCall struct {
Expand Down Expand Up @@ -67,7 +68,10 @@ func (m *testCompatSessionManager) UpdateAudioTrack(sessionID string, audioTrack
return nil
}

func (m *testCompatSessionManager) StopSession(string) error { return nil }
func (m *testCompatSessionManager) StopSession(sessionID string) error {
m.stopCalls = append(m.stopCalls, sessionID)
return nil
}

func (m *testCompatSessionManager) GetSession(sessionID string) (*playback.Session, error) {
if session, ok := m.sessions[sessionID]; ok {
Expand Down
1 change: 1 addition & 0 deletions internal/jellycompat/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ func NewRouter(deps Dependencies) chi.Router {
r.Post("/Sessions/Playing", playbackHandler.HandleSessionPlaying)
r.Post("/Sessions/Playing/Progress", playbackHandler.HandleSessionPlayingProgress)
r.Post("/Sessions/Playing/Stopped", playbackHandler.HandleSessionPlayingStopped)
r.Delete("/Videos/ActiveEncodings", playbackHandler.HandleDeleteActiveEncodings)
r.Post("/Sessions/Logout", authHandler.HandleLogout)
r.Get("/socket", HandleSocket)
})
Expand Down
72 changes: 61 additions & 11 deletions internal/jellycompat/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,66 @@ func (h *PlaybackHandler) HandleSessionPlayingStopped(w http.ResponseWriter, r *
h.handlePlaybackReport(w, r, true)
}

// HandleDeleteActiveEncodings handles DELETE /Videos/ActiveEncodings.
//
// Jellyfin clients (e.g. JellyCon) call this endpoint when playback stops to
// signal the server to tear down any running HLS transcode for the session.
// Without it, the transcode process keeps running until the playback session
// TTL expires (default 6 h). We honour the request by stopping the transcode
// identified by the playSessionId query parameter.
func (h *PlaybackHandler) HandleDeleteActiveEncodings(w http.ResponseWriter, r *http.Request) {
session := SessionFromContext(r.Context())
if session == nil {
w.WriteHeader(http.StatusNoContent)
return
}
q := newCaseInsensitiveQuery(r.URL.Query())
// DeviceId is intentionally ignored: Silo's playback store is keyed by
// PlaySessionId, clients always send it, and Jellyfin's own teardown matches
// by playSessionId (ignoring deviceId) whenever playSessionId is non-empty.
playSessionID := q.Get("PlaySessionId")
if playSessionID == "" {
w.WriteHeader(http.StatusNoContent)
return
}

// Ownership guard (mirrors the Stopped report path): only the session's own
// caller may tear it down, and a session with no upstream transcode yet has
// nothing to tear down. The PlaybackSession is created by PlaybackInfo with
// an empty UpstreamSessionID; it is only populated once the first manifest
// request reaches ensureUpstreamPlayback. Deleting it before then would drop
// a live session and 404 the pending manifest, so an unknown, not-owned, or
// not-yet-started PlaySessionId is a uniform idempotent 204 no-op (no
// cross-session teardown, no ownership oracle, no premature deletion).
playSession, ok := h.playbackStore.Get(playSessionID)
if !ok || playSession.CompatToken != session.Token || playSession.UpstreamSessionID == "" {
w.WriteHeader(http.StatusNoContent)
return
}

h.teardownPlaySession(playSession)

w.WriteHeader(http.StatusNoContent)
}

// teardownPlaySession stops the upstream playback session and removes the compat
// play session from the store. Every step is idempotent, so it is safe to call
// from both the explicit ActiveEncodings teardown and a Stopped playback report
// (which may race). It is a no-op-safe teardown for an already-gone session.
func (h *PlaybackHandler) teardownPlaySession(playSession *PlaybackSession) {
transcodeNodeURL := ""
if h.sessionMgr != nil {
if upstreamSession, err := h.sessionMgr.GetSession(playSession.UpstreamSessionID); err == nil {
transcodeNodeURL = upstreamSession.TranscodeNodeURL
}
}
h.closeTranscodeSession(playSession.UpstreamSessionID, transcodeNodeURL)
if h.sessionMgr != nil {
_ = h.sessionMgr.StopSession(playSession.UpstreamSessionID)
}
h.playbackStore.Delete(playSession.ID)
}

func (h *PlaybackHandler) handlePlaybackReport(w http.ResponseWriter, r *http.Request, stop bool) {
session := SessionFromContext(r.Context())
if session == nil {
Expand Down Expand Up @@ -755,17 +815,7 @@ func (h *PlaybackHandler) handlePlaybackReport(w http.ResponseWriter, r *http.Re
}
}
if stop {
transcodeNodeURL := ""
if h.sessionMgr != nil {
if upstreamSession, err := h.sessionMgr.GetSession(playSession.UpstreamSessionID); err == nil {
transcodeNodeURL = upstreamSession.TranscodeNodeURL
}
}
h.closeTranscodeSession(playSession.UpstreamSessionID, transcodeNodeURL)
if h.sessionMgr != nil {
_ = h.sessionMgr.StopSession(playSession.UpstreamSessionID)
}
h.playbackStore.Delete(playSession.ID)
h.teardownPlaySession(playSession)
}

w.WriteHeader(http.StatusNoContent)
Expand Down
182 changes: 182 additions & 0 deletions internal/jellycompat/streams_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
package jellycompat

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/Silo-Server/silo-server/internal/playback"
)

// withCompatSession attaches a compat session carrying tok to req, so the
// ActiveEncodings ownership guard (CompatToken == session.Token) is satisfied.
func withCompatSession(req *http.Request, tok string) *http.Request {
return req.WithContext(context.WithValue(req.Context(), compatSessionKey, &Session{Token: tok}))
}

func TestAudioSelectionChanged(t *testing.T) {
selected := 2
session := &PlaybackSession{
Expand Down Expand Up @@ -90,3 +102,173 @@ func TestRewriteManifest_PreservesPlaybackAndMediaSourceIDs(t *testing.T) {
t.Fatalf("expected nested manifest to include media and playback session ids, got:\n%s", got)
}
}

// newActiveEncodingsHandler builds a PlaybackHandler literal directly (not
// NewPlaybackHandler, which touches the filesystem) with the transcodes map
// initialized — closeTranscodeSession writes/deletes it and would nil-map-panic
// otherwise.
func newActiveEncodingsHandler(mgr *testCompatSessionManager) (*PlaybackHandler, *PlaybackSessionStore) {
store := NewPlaybackSessionStore(time.Hour, nil)
h := &PlaybackHandler{
playbackStore: store,
sessionMgr: mgr,
transcodes: make(map[string]*playback.TranscodeSession),
}
return h, store
}

// TestHandleDeleteActiveEncodings_StopsTranscodeAndDeletesSession verifies the
// happy path: the upstream session is stopped and the compat play session is
// removed from the store, returning 204.
func TestHandleDeleteActiveEncodings_StopsTranscodeAndDeletesSession(t *testing.T) {
mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); ok {
t.Fatal("play session should be deleted")
}
if len(mgr.stopCalls) != 1 || mgr.stopCalls[0] != "upstream-1" {
t.Fatalf("expected StopSession(upstream-1); got %v", mgr.stopCalls)
}
}

// TestHandleDeleteActiveEncodings_MissingPlaySessionIdReturns204 verifies a
// request with no PlaySessionId is a 204 no-op (no teardown).
func TestHandleDeleteActiveEncodings_MissingPlaySessionIdReturns204(t *testing.T) {
mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); !ok {
t.Fatal("unrelated play session must not be torn down")
}
if len(mgr.stopCalls) != 0 {
t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls)
}
}

// TestHandleDeleteActiveEncodings_UnknownPlaySessionReturns204 verifies an
// unknown PlaySessionId is a 204 no-op (idempotent "already gone" semantics).
func TestHandleDeleteActiveEncodings_UnknownPlaySessionReturns204(t *testing.T) {
mgr := &testCompatSessionManager{}
h, _ := newActiveEncodingsHandler(mgr)

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=does-not-exist", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if len(mgr.stopCalls) != 0 {
t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls)
}
}

// TestHandleDeleteActiveEncodings_CaseInsensitivePlaySessionId verifies a
// lowercase playSessionId key (as Wholphin sends) still resolves and tears down
// the session — the reason newCaseInsensitiveQuery is used.
func TestHandleDeleteActiveEncodings_CaseInsensitivePlaySessionId(t *testing.T) {
mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?playSessionId=ps-1", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); ok {
t.Fatal("lowercase playSessionId should still resolve and delete the session")
}
}

// TestHandleDeleteActiveEncodings_ForeignPlaySessionNotTornDown proves the
// ownership guard: a caller whose token differs from the play session's
// CompatToken gets a uniform 204 no-op and does NOT tear down the foreign
// session (no cross-session IDOR teardown).
func TestHandleDeleteActiveEncodings_ForeignPlaySessionNotTornDown(t *testing.T) {
mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "owner"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "attacker")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); !ok {
t.Fatal("foreign play session must not be torn down")
}
if len(mgr.stopCalls) != 0 {
t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls)
}
}

// TestHandleDeleteActiveEncodings_RealClientShape exercises the dominant real
// JellyCon call shape (DeviceId present alongside PlaySessionId): with a
// matching-token session the session is still torn down (DeviceId ignored).
func TestHandleDeleteActiveEncodings_RealClientShape(t *testing.T) {
mgr := &testCompatSessionManager{sessions: map[string]*playback.Session{"upstream-1": {ID: "upstream-1"}}}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", UpstreamSessionID: "upstream-1", CompatToken: "tok"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?DeviceId=dev1&PlaySessionId=ps-1", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); ok {
t.Fatal("play session should be torn down when DeviceId accompanies a matching PlaySessionId")
}
if len(mgr.stopCalls) != 1 || mgr.stopCalls[0] != "upstream-1" {
t.Fatalf("expected StopSession(upstream-1); got %v", mgr.stopCalls)
}
}

// TestHandleDeleteActiveEncodings_NotYetStartedNotTornDown guards the early
// window between PlaybackInfo and the first manifest request, when the play
// session exists but UpstreamSessionID is still empty. A DELETE that lands then
// must be a 204 no-op that leaves the session in the store, so the pending
// manifest request still resolves (mirrors the Stopped report path). Removing
// the UpstreamSessionID == "" guard makes this test fail.
func TestHandleDeleteActiveEncodings_NotYetStartedNotTornDown(t *testing.T) {
mgr := &testCompatSessionManager{}
h, store := newActiveEncodingsHandler(mgr)
store.Put(PlaybackSession{ID: "ps-1", CompatToken: "tok"})

req := withCompatSession(httptest.NewRequest("DELETE", "/Videos/ActiveEncodings?PlaySessionId=ps-1", nil), "tok")
rec := httptest.NewRecorder()
h.HandleDeleteActiveEncodings(rec, req)

if rec.Code != 204 {
t.Fatalf("status = %d, body = %s; want 204", rec.Code, rec.Body.String())
}
if _, ok := store.Get("ps-1"); !ok {
t.Fatal("not-yet-started play session must survive teardown so the pending manifest still resolves")
}
if len(mgr.stopCalls) != 0 {
t.Fatalf("expected no StopSession calls; got %v", mgr.stopCalls)
}
}