Skip to content

Commit

Permalink
refactor(api): stream handler
Browse files Browse the repository at this point in the history
use file extention to detect which mime type to use
  • Loading branch information
sundowndev committed Jan 17, 2021
1 parent f28865c commit 5c87403
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
4 changes: 3 additions & 1 deletion api/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import (
"github.com/dreamvo/gilfoyle/ent/media"
"github.com/dreamvo/gilfoyle/ent/schema"
"github.com/gin-gonic/gin"
"mime"
"net/http"
"path"
"path/filepath"
"strings"
)

Expand Down Expand Up @@ -62,7 +64,7 @@ func (s *Server) getMediaPlaylistFile(ctx *gin.Context) {
filenameParts := strings.Split(filename, "/")
file := filenameParts[len(filenameParts)-1]

ctx.DataFromReader(http.StatusOK, stat.Size, "application/octet-stream", f, map[string]string{
ctx.DataFromReader(http.StatusOK, stat.Size, mime.TypeByExtension(filepath.Ext(file)), f, map[string]string{
"Content-Disposition": fmt.Sprintf(`attachment; filename="%s"`, file),
})
}
24 changes: 22 additions & 2 deletions api/stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestStream(t *testing.T) {
})

t.Run("GET /medias/{media_id}/stream/*filename", func(t *testing.T) {
t.Run("should return requested file", func(t *testing.T) {
t.Run("should return the requested file", func(t *testing.T) {
m, err := dbClient.Media.
Create().
SetTitle("test").
Expand All @@ -59,10 +59,30 @@ func TestStream(t *testing.T) {

assert.Equal(t, http.StatusOK, res.Result().StatusCode)
assert.Equal(t, "test", res.Body.String())
assert.Equal(t, "application/octet-stream", res.Header().Get("Content-Type"))
assert.Equal(t, "application/x-mpegURL", res.Header().Get("Content-Type"))
assert.Equal(t, "attachment; filename=\"index.m3u8\"", res.Header().Get("Content-Disposition"))
})

t.Run("should return the requested file (2)", func(t *testing.T) {
m, err := dbClient.Media.
Create().
SetTitle("test").
SetStatus(schema.MediaStatusReady).
Save(context.Background())
assert.NoError(t, err)

err = s.storage.Save(context.Background(), strings.NewReader("test"), path.Join(m.ID.String(), "low", "000.ts"))
assert.NoError(t, err)

res, err := testutils.Send(s.router, http.MethodGet, fmt.Sprintf("/medias/%s/stream/low/000.ts", m.ID.String()), nil)
assert.NoError(t, err)

assert.Equal(t, http.StatusOK, res.Result().StatusCode)
assert.Equal(t, "test", res.Body.String())
assert.Equal(t, "video/MP2T", res.Header().Get("Content-Type"))
assert.Equal(t, "attachment; filename=\"000.ts\"", res.Header().Get("Content-Disposition"))
})

t.Run("should return error because of non-Ready status", func(t *testing.T) {
m, err := dbClient.Media.
Create().
Expand Down

0 comments on commit 5c87403

Please sign in to comment.