navidrome/api/stream.go

70 lines
1.7 KiB
Go
Raw Normal View History

2016-03-03 20:46:19 +01:00
package api
import (
"github.com/astaxie/beego"
"github.com/deluan/gosonic/api/responses"
"github.com/deluan/gosonic/domain"
"github.com/deluan/gosonic/stream"
2016-03-03 20:46:19 +01:00
"github.com/deluan/gosonic/utils"
"github.com/karlkfi/inject"
"strconv"
2016-03-03 20:46:19 +01:00
)
type StreamController struct {
BaseAPIController
repo domain.MediaFileRepository
id string
mf *domain.MediaFile
}
2016-03-03 20:46:19 +01:00
func (c *StreamController) Prepare() {
inject.ExtractAssignable(utils.Graph, &c.repo)
c.id = c.GetParameter("id", "id parameter required")
2016-03-03 20:46:19 +01:00
mf, err := c.repo.Get(c.id)
2016-03-03 20:46:19 +01:00
if err != nil {
beego.Error("Error reading mediafile", c.id, "from the database", ":", err)
2016-03-03 20:46:19 +01:00
c.SendError(responses.ERROR_GENERIC, "Internal error")
}
if mf == nil {
beego.Error("MediaFile", c.id, "not found!")
c.SendError(responses.ERROR_DATA_NOT_FOUND)
}
c.mf = mf
}
func (c *StreamController) Stream() {
var maxBitRate int
c.Ctx.Input.Bind(&maxBitRate, "maxBitRate")
maxBitRate = utils.MinInt(c.mf.BitRate, maxBitRate)
beego.Debug("Streaming file", ":", c.mf.Path)
beego.Debug("Bitrate", c.mf.BitRate, "MaxBitRate", maxBitRate)
if maxBitRate > 0 {
c.Ctx.Output.Header("Content-Length", strconv.Itoa(c.mf.Duration*maxBitRate*1000/8))
}
c.Ctx.Output.Header("Content-Type", "audio/mpeg")
c.Ctx.Output.Header("Expires", "0")
c.Ctx.Output.Header("Cache-Control", "must-revalidate")
c.Ctx.Output.Header("Pragma", "public")
err := stream.Stream(c.mf.Path, c.mf.BitRate, maxBitRate, c.Ctx.ResponseWriter)
2016-03-03 20:46:19 +01:00
if err != nil {
beego.Error("Error streaming file id", c.id, ":", err)
2016-03-03 20:46:19 +01:00
}
beego.Debug("Finished streaming of", c.mf.Path)
}
func (c *StreamController) Download() {
beego.Debug("Sending file", c.mf.Path)
stream.Stream(c.mf.Path, 0, 0, c.Ctx.ResponseWriter)
2016-03-03 20:46:19 +01:00
beego.Debug("Finished sending", c.mf.Path)
2016-03-03 20:46:19 +01:00
}