diff --git a/Dockerfile b/Dockerfile
index de4aad1..a5f065c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -32,5 +32,6 @@ ENV TZ
ENV GONIC_DB_PATH /data/gonic.db
ENV GONIC_LISTEN_ADDR :80
ENV GONIC_MUSIC_PATH /music
+ENV GONIC_PODCAST_PATH /podcasts
ENV GONIC_CACHE_PATH /cache
CMD ["gonic"]
diff --git a/Dockerfile.dev b/Dockerfile.dev
index 8d71827..1e05f74 100644
--- a/Dockerfile.dev
+++ b/Dockerfile.dev
@@ -31,5 +31,6 @@ EXPOSE 80
ENV GONIC_DB_PATH /data/gonic.db
ENV GONIC_LISTEN_ADDR :80
ENV GONIC_MUSIC_PATH /music
+ENV GONIC_PODCAST_PATH /podcasts
ENV GONIC_CACHE_PATH /cache
CMD ["gonic"]
diff --git a/cmd/gonic/main.go b/cmd/gonic/main.go
index 2ec5ffd..6beab9b 100644
--- a/cmd/gonic/main.go
+++ b/cmd/gonic/main.go
@@ -22,7 +22,8 @@ import (
const (
cleanTimeDuration = 10 * time.Minute
- coverCachePrefix = "covers"
+ cachePrefixAudio = "audio"
+ cachePrefixCovers = "covers"
)
func main() {
@@ -30,7 +31,7 @@ func main() {
confListenAddr := set.String("listen-addr", "0.0.0.0:4747", "listen address (optional)")
confMusicPath := set.String("music-path", "", "path to music")
confPodcastPath := set.String("podcast-path", "", "path to podcasts")
- confCachePath := set.String("cache-path", "/tmp/gonic_cache", "path to cache")
+ confCachePath := set.String("cache-path", "", "path to cache")
confDBPath := set.String("db-path", "gonic.db", "path to database (optional)")
confScanInterval := set.Int("scan-interval", 0, "interval (in minutes) to automatically scan music (optional)")
confJukeboxEnabled := set.Bool("jukebox-enabled", false, "whether the subsonic jukebox api should be enabled (optional)")
@@ -61,18 +62,24 @@ func main() {
if _, err := os.Stat(*confMusicPath); os.IsNotExist(err) {
log.Fatal("please provide a valid music directory")
}
- if _, err := os.Stat(*confPodcastPath); *confPodcastPath != "" && os.IsNotExist(err) {
+ if _, err := os.Stat(*confPodcastPath); os.IsNotExist(err) {
log.Fatal("please provide a valid podcast directory")
}
if _, err := os.Stat(*confCachePath); os.IsNotExist(err) {
- if err := os.MkdirAll(*confCachePath, os.ModePerm); err != nil {
- log.Fatalf("couldn't create cache path: %v\n", err)
+ log.Fatal("please provide a valid cache directory")
+ }
+
+ cacheDirAudio := path.Join(*confCachePath, cachePrefixAudio)
+ cacheDirCovers := path.Join(*confCachePath, cachePrefixCovers)
+
+ if _, err := os.Stat(cacheDirAudio); os.IsNotExist(err) {
+ if err := os.MkdirAll(cacheDirAudio, os.ModePerm); err != nil {
+ log.Fatalf("couldn't create audio cache path: %v\n", err)
}
}
- coverCachePath := path.Join(*confCachePath, coverCachePrefix)
- if _, err := os.Stat(coverCachePath); os.IsNotExist(err) {
- if err := os.MkdirAll(coverCachePath, os.ModePerm); err != nil {
- log.Fatalf("couldn't create cover cache path: %v\n", err)
+ if _, err := os.Stat(cacheDirCovers); os.IsNotExist(err) {
+ if err := os.MkdirAll(cacheDirCovers, os.ModePerm); err != nil {
+ log.Fatalf("couldn't create covers cache path: %v\n", err)
}
}
@@ -87,8 +94,8 @@ func main() {
server := server.New(server.Options{
DB: db,
MusicPath: *confMusicPath,
- CachePath: *confCachePath,
- CoverCachePath: coverCachePath,
+ CachePath: cacheDirAudio,
+ CoverCachePath: cacheDirCovers,
ProxyPrefix: *confProxyPrefix,
GenreSplit: *confGenreSplit,
PodcastPath: *confPodcastPath,
@@ -97,6 +104,7 @@ func main() {
var g run.Group
g.Add(server.StartHTTP(*confListenAddr))
g.Add(server.StartSessionClean(cleanTimeDuration))
+ g.Add(server.StartPodcastRefresher(time.Hour))
if *confScanInterval > 0 {
tickerDur := time.Duration(*confScanInterval) * time.Minute
g.Add(server.StartScanTicker(tickerDur))
@@ -104,9 +112,6 @@ func main() {
if *confJukeboxEnabled {
g.Add(server.StartJukebox())
}
- if *confProxyPrefix != "" {
- g.Add(server.StartPodcastRefresher(time.Hour))
- }
if err := g.Run(); err != nil {
log.Printf("error in job: %v", err)
diff --git a/server/assets/pages/home.tmpl b/server/assets/pages/home.tmpl
index fa3d0c8..57ab2ab 100644
--- a/server/assets/pages/home.tmpl
+++ b/server/assets/pages/home.tmpl
@@ -168,6 +168,30 @@
+
playlists
diff --git a/server/ctrladmin/ctrl.go b/server/ctrladmin/ctrl.go
index bf888f2..eddc4e8 100644
--- a/server/ctrladmin/ctrl.go
+++ b/server/ctrladmin/ctrl.go
@@ -128,7 +128,6 @@ type templateData struct {
DefaultListenBrainzURL string
SelectedUser *db.User
//
- PodcastsEnabled bool
Podcasts []*db.Podcast
}
diff --git a/server/ctrladmin/handlers.go b/server/ctrladmin/handlers.go
index 0c4ba7e..c293a6d 100644
--- a/server/ctrladmin/handlers.go
+++ b/server/ctrladmin/handlers.go
@@ -46,10 +46,6 @@ func (c *Controller) ServeHome(r *http.Request) *Response {
c.DB.Table("artists").Count(&data.ArtistCount)
c.DB.Table("albums").Count(&data.AlbumCount)
c.DB.Table("tracks").Count(&data.TrackCount)
- data.PodcastsEnabled = c.Podcasts.PodcastBasePath != ""
- if data.PodcastsEnabled {
- c.DB.Find(&data.Podcasts)
- }
// ** begin lastfm box
scheme := firstExisting(
"http", // fallback
@@ -92,6 +88,8 @@ func (c *Controller) ServeHome(r *http.Request) *Response {
for profile := range encode.Profiles() {
data.TranscodeProfiles = append(data.TranscodeProfiles, profile)
}
+ // ** begin podcasts box
+ c.DB.Find(&data.Podcasts)
//
return &Response{
template: "home.tmpl",
diff --git a/server/ctrlsubsonic/ctrl.go b/server/ctrlsubsonic/ctrl.go
index a1a71e9..7e5784c 100644
--- a/server/ctrlsubsonic/ctrl.go
+++ b/server/ctrlsubsonic/ctrl.go
@@ -13,8 +13,8 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/jukebox"
- "go.senan.xyz/gonic/server/scrobble"
"go.senan.xyz/gonic/server/podcasts"
+ "go.senan.xyz/gonic/server/scrobble"
)
type CtxKey int
diff --git a/server/ctrlsubsonic/handlers_common.go b/server/ctrlsubsonic/handlers_common.go
index 547d697..3cdb922 100644
--- a/server/ctrlsubsonic/handlers_common.go
+++ b/server/ctrlsubsonic/handlers_common.go
@@ -38,11 +38,8 @@ func (c *Controller) ServePing(r *http.Request) *spec.Response {
func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
- if err != nil {
- return spec.NewError(10, "please provide an `id` parameter")
- }
- if id.Type == specid.Podcast || id.Type == specid.PodcastEpisode {
- return spec.NewError(10, "please provide a valid track id")
+ if err != nil || id.Type != specid.Track {
+ return spec.NewError(10, "please provide an valid `id` track parameter")
}
// fetch user to get lastfm session
user := r.Context().Value(CtxUser).(*db.User)
@@ -109,8 +106,8 @@ func (c *Controller) ServeGetUser(r *http.Request) *spec.Response {
Username: user.Name,
AdminRole: user.IsAdmin,
JukeboxRole: true,
+ PodcastRole: true,
ScrobblingEnabled: hasLastFM || hasListenBrainz,
- PodcastRole: c.Podcasts.PodcastBasePath != "",
Folder: []int{1},
}
return sub
diff --git a/server/ctrlsubsonic/handlers_podcast.go b/server/ctrlsubsonic/handlers_podcast.go
index a241f34..54c8b03 100644
--- a/server/ctrlsubsonic/handlers_podcast.go
+++ b/server/ctrlsubsonic/handlers_podcast.go
@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/mmcdole/gofeed"
+
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
@@ -12,21 +13,19 @@ import (
func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
- isIncludeEpisodes := true
- if ie, err := params.GetBool("includeEpisodes"); !ie && err == nil {
- isIncludeEpisodes = false
+ isIncludeEpisodes := params.GetOrBool("includeEpisodes", true)
+ user := r.Context().Value(CtxUser).(*db.User)
+ id, _ := params.GetID("id")
+ podcasts, err := c.Podcasts.GetPodcastOrAll(user.ID, id.Value, isIncludeEpisodes)
+ if err != nil {
+ return spec.NewError(10, "failed get podcast(s): %s", err)
}
sub := spec.NewResponse()
- user := r.Context().Value(CtxUser).(*db.User)
- id, err := params.GetID("id")
- if err != nil {
- sub.Podcasts, err = c.Podcasts.GetAllPodcasts(user.ID, isIncludeEpisodes)
- if err != nil {
- return spec.NewError(10, "Failed to retrieve podcasts: %s", err)
- }
- return sub
+ sub.Podcasts = &spec.Podcasts{}
+ for _, podcast := range podcasts {
+ channel := spec.NewPodcastChannel(podcast)
+ sub.Podcasts.List = append(sub.Podcasts.List, channel)
}
- sub.Podcasts, _ = c.Podcasts.GetPodcast(id.Value, user.ID, isIncludeEpisodes)
return sub
}
@@ -34,10 +33,10 @@ func (c *Controller) ServeDownloadPodcastEpisode(r *http.Request) *spec.Response
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil || id.Type != specid.PodcastEpisode {
- return spec.NewError(10, "Please provide a valid podcast episode id")
+ return spec.NewError(10, "please provide a valid podcast episode id")
}
if err := c.Podcasts.DownloadEpisode(id.Value); err != nil {
- return spec.NewError(10, "Failed to download episode: %s", err)
+ return spec.NewError(10, "failed to download episode: %s", err)
}
return spec.NewResponse()
}
@@ -49,20 +48,18 @@ func (c *Controller) ServeCreatePodcastChannel(r *http.Request) *spec.Response {
fp := gofeed.NewParser()
feed, err := fp.ParseURL(rssURL)
if err != nil {
- return spec.NewError(10, "Failed to parse feed: %s", err)
+ return spec.NewError(10, "failed to parse feed: %s", err)
}
- _, err = c.Podcasts.AddNewPodcast(feed, user.ID)
- if err != nil {
- return spec.NewError(10, "Failed to add feed: %s", err)
+ if _, err = c.Podcasts.AddNewPodcast(feed, user.ID); err != nil {
+ return spec.NewError(10, "failed to add feed: %s", err)
}
return spec.NewResponse()
}
func (c *Controller) ServeRefreshPodcasts(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
- err := c.Podcasts.RefreshPodcasts(user.ID, false)
- if err != nil {
- return spec.NewError(10, "Failed to refresh feeds: %s", err)
+ if err := c.Podcasts.RefreshPodcastsForUser(user.ID); err != nil {
+ return spec.NewError(10, "failed to refresh feeds: %s", err)
}
return spec.NewResponse()
}
@@ -72,11 +69,10 @@ func (c *Controller) ServeDeletePodcastChannel(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil || id.Type != specid.Podcast {
- return spec.NewError(10, "Please provide a valid podcast ID")
+ return spec.NewError(10, "please provide a valid podcast id")
}
- err = c.Podcasts.DeletePodcast(user.ID, id.Value)
- if err != nil {
- return spec.NewError(10, "Failed to delete podcast: %s", err)
+ if err := c.Podcasts.DeletePodcast(user.ID, id.Value); err != nil {
+ return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
}
@@ -85,11 +81,10 @@ func (c *Controller) ServeDeletePodcastEpisode(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil || id.Type != specid.PodcastEpisode {
- return spec.NewError(10, "Please provide a valid podcast episode ID")
+ return spec.NewError(10, "please provide a valid podcast episode id")
}
- err = c.Podcasts.DeletePodcastEpisode(id.Value)
- if err != nil {
- return spec.NewError(10, "Failed to delete podcast: %s", err)
+ if err := c.Podcasts.DeletePodcastEpisode(id.Value); err != nil {
+ return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
}
diff --git a/server/ctrlsubsonic/handlers_raw.go b/server/ctrlsubsonic/handlers_raw.go
index cc02a48..f3c0383 100644
--- a/server/ctrlsubsonic/handlers_raw.go
+++ b/server/ctrlsubsonic/handlers_raw.go
@@ -11,7 +11,6 @@ import (
"time"
"github.com/disintegration/imaging"
- "github.com/jinzhu/gorm"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
@@ -75,50 +74,71 @@ var (
)
func coverGetPath(dbc *db.DB, musicPath, podcastPath string, id specid.ID) (string, error) {
- var err error
- coverPath := ""
switch id.Type {
case specid.Album:
- folder := &db.Album{}
- err = dbc.DB.
- Select("id, left_path, right_path, cover").
- First(folder, id.Value).
- Error
- coverPath = path.Join(
- musicPath,
- folder.LeftPath,
- folder.RightPath,
- folder.Cover,
- )
- if folder.Cover == "" {
- return "", errCoverEmpty
- }
+ return coverGetPathAlbum(dbc, musicPath, id.Value)
case specid.Podcast:
- podcast := &db.Podcast{}
- err = dbc.First(podcast, id.Value).Error
-
- if podcast.ImagePath == "" {
- return "", errCoverEmpty
- }
- coverPath = path.Join(podcastPath, podcast.ImagePath)
+ return coverGetPathPodcast(dbc, podcastPath, id.Value)
case specid.PodcastEpisode:
- podcastEp := &db.PodcastEpisode{}
- err = dbc.First(podcastEp, id.Value).Error
- if gorm.IsRecordNotFoundError(err) {
- return "", errCoverNotFound
- }
- podcast := &db.Podcast{}
- err = dbc.First(podcast, podcastEp.PodcastID).Error
- if podcast.ImagePath == "" {
- return "", errCoverEmpty
- }
- coverPath = path.Join(podcastPath, podcast.ImagePath)
+ return coverGetPathPodcastEpisode(dbc, podcastPath, id.Value)
default:
- }
- if gorm.IsRecordNotFoundError(err) {
return "", errCoverNotFound
}
- return coverPath, nil
+}
+
+func coverGetPathAlbum(dbc *db.DB, musicPath string, id int) (string, error) {
+ folder := &db.Album{}
+ err := dbc.DB.
+ Select("id, left_path, right_path, cover").
+ First(folder, id).
+ Error
+ if err != nil {
+ return "", fmt.Errorf("select album: %w", err)
+ }
+ if folder.Cover == "" {
+ return "", errCoverEmpty
+ }
+ return path.Join(
+ musicPath,
+ folder.LeftPath,
+ folder.RightPath,
+ folder.Cover,
+ ), nil
+}
+
+func coverGetPathPodcast(dbc *db.DB, podcastPath string, id int) (string, error) {
+ podcast := &db.Podcast{}
+ err := dbc.
+ First(podcast, id).
+ Error
+ if err != nil {
+ return "", fmt.Errorf("select podcast: %w", err)
+ }
+ if podcast.ImagePath == "" {
+ return "", errCoverEmpty
+ }
+ return path.Join(podcastPath, podcast.ImagePath), nil
+}
+
+func coverGetPathPodcastEpisode(dbc *db.DB, podcastPath string, id int) (string, error) {
+ episode := &db.PodcastEpisode{}
+ err := dbc.
+ First(episode, id).
+ Error
+ if err != nil {
+ return "", fmt.Errorf("select episode: %w", err)
+ }
+ podcast := &db.Podcast{}
+ err = dbc.
+ First(podcast, episode.PodcastID).
+ Error
+ if err != nil {
+ return "", fmt.Errorf("select podcast: %w", err)
+ }
+ if podcast.ImagePath == "" {
+ return "", errCoverEmpty
+ }
+ return path.Join(podcastPath, podcast.ImagePath), nil
}
func coverScaleAndSave(absPath, cachePath string, size int) error {
@@ -176,19 +196,20 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
}
var audioFile db.AudioFile
var audioPath string
- if id.Type == specid.Track {
+ switch id.Type {
+ case specid.Track:
track, _ := streamGetTrack(c.DB, id.Value)
audioFile = track
audioPath = path.Join(c.MusicPath, track.RelPath())
if err != nil {
return spec.NewError(70, "track with id `%s` was not found", id)
}
- } else if id.Type == specid.PodcastEpisode {
+ case specid.PodcastEpisode:
podcast, err := streamGetPodcast(c.DB, id.Value)
audioFile = podcast
audioPath = path.Join(c.Podcasts.PodcastBasePath, podcast.Path)
if err != nil {
- return spec.NewError(70, "track with id `%s` was not found", id)
+ return spec.NewError(70, "podcast with id `%s` was not found", id)
}
}
@@ -196,8 +217,8 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
return spec.NewError(70, "media with id `%d` was not found", id.Value)
}
user := r.Context().Value(CtxUser).(*db.User)
- if id.Type == specid.Track {
- defer streamUpdateStats(c.DB, user.ID, audioFile.(*db.Track).Album.ID)
+ if track, ok := audioFile.(*db.Track); ok {
+ defer streamUpdateStats(c.DB, user.ID, track.Album.ID)
}
pref := streamGetTransPref(c.DB, user.ID, params.GetOr("c", ""))
//
@@ -242,14 +263,15 @@ func (c *Controller) ServeDownload(w http.ResponseWriter, r *http.Request) *spec
}
var filePath string
var audioFile db.AudioFile
- if id.Type == specid.Track {
+ switch id.Type {
+ case specid.Track:
track, _ := streamGetTrack(c.DB, id.Value)
audioFile = track
filePath = path.Join(c.MusicPath, track.RelPath())
if err != nil {
return spec.NewError(70, "track with id `%s` was not found", id)
}
- } else if id.Type == specid.PodcastEpisode {
+ case specid.PodcastEpisode:
podcast, err := streamGetPodcast(c.DB, id.Value)
audioFile = podcast
filePath = path.Join(c.Podcasts.PodcastBasePath, podcast.Path)
diff --git a/server/ctrlsubsonic/spec/construct_podcast.go b/server/ctrlsubsonic/spec/construct_podcast.go
new file mode 100644
index 0000000..bae2147
--- /dev/null
+++ b/server/ctrlsubsonic/spec/construct_podcast.go
@@ -0,0 +1,45 @@
+package spec
+
+import "go.senan.xyz/gonic/server/db"
+
+func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
+ ret := &PodcastChannel{
+ ID: p.SID(),
+ OriginalImageURL: p.ImageURL,
+ Title: p.Title,
+ Description: p.Description,
+ URL: p.URL,
+ CoverArt: p.SID(),
+ Status: "skipped",
+ }
+ for _, episode := range p.Episodes {
+ specEpisode := NewPodcastEpisode(p, episode)
+ ret.Episode = append(ret.Episode, specEpisode)
+ }
+ return ret
+}
+
+func NewPodcastEpisode(p *db.Podcast, e *db.PodcastEpisode) *PodcastEpisode {
+ if e == nil {
+ return nil
+ }
+ return &PodcastEpisode{
+ ID: e.SID(),
+ StreamID: e.SID(),
+ ContentType: e.MIME(),
+ ChannelID: p.SID(),
+ Title: e.Title,
+ Description: e.Description,
+ Status: e.Status,
+ CoverArt: p.SID(),
+ PublishDate: *e.PublishDate,
+ Genre: "Podcast",
+ Duration: e.Length,
+ Year: e.PublishDate.Year(),
+ Suffix: e.Ext(),
+ BitRate: e.Bitrate,
+ IsDir: false,
+ Path: e.Path,
+ Size: e.Size,
+ }
+}
diff --git a/server/ctrlsubsonic/spec/spec.go b/server/ctrlsubsonic/spec/spec.go
index fc2225c..9a5536e 100644
--- a/server/ctrlsubsonic/spec/spec.go
+++ b/server/ctrlsubsonic/spec/spec.go
@@ -288,24 +288,24 @@ type JukeboxPlaylist struct {
}
type Podcasts struct {
- List []PodcastChannel `xml:"channel" json:"channel"`
+ List []*PodcastChannel `xml:"channel" json:"channel"`
}
type PodcastChannel struct {
- ID specid.ID `xml:"id,attr" json:"id"`
+ ID *specid.ID `xml:"id,attr" json:"id"`
URL string `xml:"url,attr" json:"url"`
Title string `xml:"title,attr" json:"title"`
Description string `xml:"description,attr" json:"description"`
- CoverArt specid.ID `xml:"coverArt,attr" json:"coverArt,omitempty"`
+ CoverArt *specid.ID `xml:"coverArt,attr" json:"coverArt,omitempty"`
OriginalImageURL string `xml:"originalImageUrl,attr" json:"originalImageUrl,omitempty"`
Status string `xml:"status,attr" json:"status"`
- Episode []PodcastEpisode `xml:"episode" json:"episode,omitempty"`
+ Episode []*PodcastEpisode `xml:"episode" json:"episode,omitempty"`
}
type PodcastEpisode struct {
- ID specid.ID `xml:"id,attr" json:"id"`
- StreamID specid.ID `xml:"streamId,attr" json:"streamId"`
- ChannelID specid.ID `xml:"channelId,attr" json:"channelId"`
+ ID *specid.ID `xml:"id,attr" json:"id"`
+ StreamID *specid.ID `xml:"streamId,attr" json:"streamId"`
+ ChannelID *specid.ID `xml:"channelId,attr" json:"channelId"`
Title string `xml:"title,attr" json:"title"`
Description string `xml:"description,attr" json:"description"`
PublishDate time.Time `xml:"publishDate,attr" json:"publishDate"`
@@ -314,7 +314,7 @@ type PodcastEpisode struct {
IsDir bool `xml:"isDir,attr" json:"isDir"`
Year int `xml:"year,attr" json:"year"`
Genre string `xml:"genre,attr" json:"genre"`
- CoverArt specid.ID `xml:"coverArt,attr" json:"coverArt"`
+ CoverArt *specid.ID `xml:"coverArt,attr" json:"coverArt"`
Size int `xml:"size,attr" json:"size"`
ContentType string `xml:"contentType,attr" json:"contentType"`
Suffix string `xml:"suffix,attr" json:"suffix"`
diff --git a/server/db/model.go b/server/db/model.go
index ee603d8..cfeaf01 100644
--- a/server/db/model.go
+++ b/server/db/model.go
@@ -300,6 +300,7 @@ type Podcast struct {
ImageURL string
ImagePath string
Error string
+ Episodes []*PodcastEpisode
}
func (p *Podcast) Fullpath(podcastPath string) string {
diff --git a/server/podcasts/podcasts.go b/server/podcasts/podcasts.go
index 18d1ac8..8258fa5 100644
--- a/server/podcasts/podcasts.go
+++ b/server/podcasts/podcasts.go
@@ -17,8 +17,7 @@ import (
"github.com/jinzhu/gorm"
"github.com/mmcdole/gofeed"
- "go.senan.xyz/gonic/server/ctrlsubsonic/spec"
- "go.senan.xyz/gonic/server/ctrlsubsonic/specid"
+
"go.senan.xyz/gonic/server/db"
"go.senan.xyz/gonic/server/scanner/tags"
)
@@ -34,95 +33,38 @@ const (
episodeDeleted = "deleted"
)
-func (p *Podcasts) GetAllPodcasts(userID int, includeEpisodes bool) (*spec.Podcasts, error) {
+func (p *Podcasts) GetPodcastOrAll(userID int, id int, includeEpisodes bool) ([]*db.Podcast, error) {
podcasts := []*db.Podcast{}
- err := p.DB.Where("user_id=?", userID).Order("").Find(&podcasts).Error
- if err != nil {
- return nil, err
+ q := p.DB.Where("user_id=?", userID)
+ if id != 0 {
+ q = q.Where("id=?", id)
+ }
+ if err := q.Find(&podcasts).Error; err != nil {
+ return nil, fmt.Errorf("finding podcasts: %w", err)
+ }
+ if !includeEpisodes {
+ return podcasts, nil
}
- channels := []spec.PodcastChannel{}
for _, c := range podcasts {
- channel := spec.PodcastChannel{
- ID: *c.SID(),
- OriginalImageURL: c.ImageURL,
- Title: c.Title,
- Description: c.Description,
- URL: c.URL,
- Status: episodeSkipped,
+ episodes, err := p.GetPodcastEpisodes(id)
+ if err != nil {
+ return nil, fmt.Errorf("finding podcast episodes: %w", err)
}
- if includeEpisodes {
- channel.Episode, err = p.GetPodcastEpisodes(*c.SID())
- if err != nil {
- return nil, err
- }
- }
- channels = append(channels, channel)
+ c.Episodes = episodes
}
- return &spec.Podcasts{List: channels}, nil
+ return podcasts, nil
}
-func (p *Podcasts) GetPodcast(podcastID, userID int, includeEpisodes bool) (*spec.Podcasts, error) {
- podcasts := []*db.Podcast{}
- err := p.DB.Where("user_id=? AND id=?", userID, podcastID).
- Order("title DESC").
- Find(&podcasts).Error
- if err != nil {
- return nil, err
- }
-
- channels := []spec.PodcastChannel{}
- for _, c := range podcasts {
- channel := spec.PodcastChannel{
- ID: *c.SID(),
- OriginalImageURL: c.ImageURL,
- CoverArt: *c.SID(),
- Title: c.Title,
- Description: c.Description,
- URL: c.URL,
- Status: episodeSkipped,
- }
- if includeEpisodes {
- channel.Episode, err = p.GetPodcastEpisodes(*c.SID())
- if err != nil {
- return nil, err
- }
- }
- channels = append(channels, channel)
- }
- return &spec.Podcasts{List: channels}, nil
-}
-
-func (p *Podcasts) GetPodcastEpisodes(podcastID specid.ID) ([]spec.PodcastEpisode, error) {
- dbEpisodes := []*db.PodcastEpisode{}
- if err := p.DB.
- Where("podcast_id=?", podcastID.Value).
+func (p *Podcasts) GetPodcastEpisodes(podcastID int) ([]*db.PodcastEpisode, error) {
+ episodes := []*db.PodcastEpisode{}
+ err := p.DB.
+ Where("podcast_id=?", podcastID).
Order("publish_date DESC").
- Find(&dbEpisodes).Error; err != nil {
- return nil, err
+ Find(&episodes).
+ Error
+ if err != nil {
+ return nil, fmt.Errorf("find episodes by podcast id: %w", err)
}
- episodes := []spec.PodcastEpisode{}
- for _, dbe := range dbEpisodes {
- episodes = append(episodes, spec.PodcastEpisode{
- ID: *dbe.SID(),
- StreamID: *dbe.SID(),
- ContentType: dbe.MIME(),
- ChannelID: podcastID,
- Title: dbe.Title,
- Description: dbe.Description,
- Status: dbe.Status,
- CoverArt: podcastID,
- PublishDate: *dbe.PublishDate,
- Genre: "Podcast",
- Duration: dbe.Length,
- Year: dbe.PublishDate.Year(),
- Suffix: dbe.Ext(),
- BitRate: dbe.Bitrate,
- IsDir: false,
- Path: dbe.Path,
- Size: dbe.Size,
- })
- }
-
return episodes, nil
}
@@ -142,11 +84,14 @@ func (p *Podcasts) AddNewPodcast(feed *gofeed.Feed, userID int) (*db.Podcast, er
if err := p.DB.Save(&podcast).Error; err != nil {
return &podcast, err
}
- if err := p.AddNewEpisodes(userID, podcast.ID, feed.Items); err != nil {
+ if err := p.AddNewEpisodes(podcast.ID, feed.Items); err != nil {
return nil, err
}
- go p.downloadPodcastCover(podPath, &podcast)
-
+ go func() {
+ if err := p.downloadPodcastCover(podPath, &podcast); err != nil {
+ log.Printf("error downloading podcast cover: %v", err)
+ }
+ }()
return &podcast, nil
}
@@ -161,7 +106,7 @@ func getEntriesAfterDate(feed []*gofeed.Item, after time.Time) []*gofeed.Item {
return items
}
-func (p *Podcasts) AddNewEpisodes(userID int, podcastID int, items []*gofeed.Item) error {
+func (p *Podcasts) AddNewEpisodes(podcastID int, items []*gofeed.Item) error {
podcastEpisode := db.PodcastEpisode{}
err := p.DB.
Where("podcast_id=?", podcastID).
@@ -246,43 +191,65 @@ func (p *Podcasts) AddEpisode(podcastID int, item *gofeed.Item) error {
return nil
}
-func (p *Podcasts) RefreshPodcasts(userID int, serverWide bool) error {
+func (p *Podcasts) RefreshPodcasts() error {
podcasts := []*db.Podcast{}
- var err error
- if serverWide {
- err = p.DB.Find(&podcasts).Error
- } else {
- err = p.DB.Where("user_id=?", userID).Find(&podcasts).Error
+ if err := p.DB.Find(&podcasts).Error; err != nil {
+ return fmt.Errorf("find podcasts: %w", err)
}
- if err != nil {
- return err
+ if errs := p.refreshPodcasts(podcasts); len(errs) > 0 {
+ return fmt.Errorf("refresh podcasts: %v", errs)
}
+ return nil
+}
+func (p *Podcasts) RefreshPodcastsForUser(userID int) error {
+ podcasts := []*db.Podcast{}
+ err := p.DB.
+ Where("user_id=?", userID).
+ Find(&podcasts).
+ Error
+ if err != nil {
+ return fmt.Errorf("find podcasts: %w", err)
+ }
+ if errs := p.refreshPodcasts(podcasts); len(errs) > 0 {
+ return fmt.Errorf("refresh podcasts: %v", errs)
+ }
+ return nil
+}
+
+func (p *Podcasts) refreshPodcasts(podcasts []*db.Podcast) []error {
+ var errs []error
for _, podcast := range podcasts {
fp := gofeed.NewParser()
feed, err := fp.ParseURL(podcast.URL)
if err != nil {
- log.Printf("Error refreshing podcast with url %s: %s", podcast.URL, err)
+ errs = append(errs, fmt.Errorf("refreshing podcast with url %q: %w", podcast.URL, err))
continue
}
- err = p.AddNewEpisodes(userID, podcast.ID, feed.Items)
- if err != nil {
- log.Printf("Error adding episodes: %s", err)
+ if err = p.AddNewEpisodes(podcast.ID, feed.Items); err != nil {
+ errs = append(errs, fmt.Errorf("adding episodes: %w", err))
+ continue
}
}
- return nil
+ return errs
}
func (p *Podcasts) DownloadEpisode(episodeID int) error {
podcastEpisode := db.PodcastEpisode{}
podcast := db.Podcast{}
- err := p.DB.Where("id=?", episodeID).First(&podcastEpisode).Error
+ err := p.DB.
+ Where("id=?", episodeID).
+ First(&podcastEpisode).
+ Error
if err != nil {
- return err
+ return fmt.Errorf("get podcast episode by id: %w", err)
}
- err = p.DB.Where("id=?", podcastEpisode.PodcastID).First(&podcast).Error
+ err = p.DB.
+ Where("id=?", podcastEpisode.PodcastID).
+ First(&podcast).
+ Error
if err != nil {
- return err
+ return fmt.Errorf("get podcast by id: %w", err)
}
if podcastEpisode.Status == episodeDownloading {
log.Printf("Already downloading podcast episode with id %d", episodeID)
@@ -293,25 +260,29 @@ func (p *Podcasts) DownloadEpisode(episodeID int) error {
// nolint: bodyclose
resp, err := http.Get(podcastEpisode.AudioURL)
if err != nil {
- return err
+ return fmt.Errorf("fetch podcast audio: %w", err)
}
filename, ok := getContentDispositionFilename(resp.Header.Get("content-disposition"))
if !ok {
audioURL, err := url.Parse(podcastEpisode.AudioURL)
if err != nil {
- return err
+ return fmt.Errorf("parse podcast audio url: %w", err)
}
filename = path.Base(audioURL.Path)
}
filename = p.findUniqueEpisodeName(&podcast, &podcastEpisode, filename)
audioFile, err := os.Create(path.Join(podcast.Fullpath(p.PodcastBasePath), filename))
if err != nil {
- return err
+ return fmt.Errorf("create audio file: %w", err)
}
podcastEpisode.Filename = filename
podcastEpisode.Path = path.Join(filepath.Clean(podcast.Title), filename)
p.DB.Save(&podcastEpisode)
- go p.doPodcastDownload(&podcastEpisode, audioFile, resp.Body)
+ go func() {
+ if err := p.doPodcastDownload(&podcastEpisode, audioFile, resp.Body); err != nil {
+ log.Printf("error downloading podcast: %v", err)
+ }
+ }()
return nil
}
@@ -319,14 +290,13 @@ func (p *Podcasts) findUniqueEpisodeName(
podcast *db.Podcast,
podcastEpisode *db.PodcastEpisode,
filename string) string {
- fp := path.Join(podcast.Fullpath(p.PodcastBasePath), filename)
- if _, err := os.Stat(fp); os.IsNotExist(err) {
+ podcastPath := path.Join(podcast.Fullpath(p.PodcastBasePath), filename)
+ if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
return filename
}
- titlePath := fmt.Sprintf("%s%s", podcastEpisode.Title,
- filepath.Ext(filename))
- fp = path.Join(podcast.Fullpath(p.PodcastBasePath), titlePath)
- if _, err := os.Stat(fp); os.IsNotExist(err) {
+ titlePath := fmt.Sprintf("%s%s", podcastEpisode.Title, filepath.Ext(filename))
+ podcastPath = path.Join(podcast.Fullpath(p.PodcastBasePath), titlePath)
+ if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
return titlePath
}
// try to find a filename like FILENAME (1).mp3 incrementing
@@ -335,8 +305,8 @@ func (p *Podcasts) findUniqueEpisodeName(
func findEpisode(base, filename string, count int) string {
testFile := fmt.Sprintf("%s (%d)%s", filename, count, filepath.Ext(filename))
- fp := path.Join(base, testFile)
- if _, err := os.Stat(fp); os.IsNotExist(err) {
+ podcastPath := path.Join(base, testFile)
+ if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
return testFile
}
return findEpisode(base, filename, count+1)
@@ -348,92 +318,99 @@ func getContentDispositionFilename(header string) (string, bool) {
return filename, ok
}
-func (p *Podcasts) downloadPodcastCover(podPath string, podcast *db.Podcast) {
+func (p *Podcasts) downloadPodcastCover(podPath string, podcast *db.Podcast) error {
imageURL, err := url.Parse(podcast.ImageURL)
if err != nil {
- return
+ return fmt.Errorf("parse image url: %w", err)
}
ext := path.Ext(imageURL.Path)
resp, err := http.Get(podcast.ImageURL)
if err != nil {
- return
+ return fmt.Errorf("fetch image url: %w", err)
}
defer resp.Body.Close()
if ext == "" {
- filename, _ := getContentDispositionFilename(resp.Header.Get("content-disposition"))
+ contentHeader := resp.Header.Get("content-disposition")
+ filename, _ := getContentDispositionFilename(contentHeader)
ext = path.Ext(filename)
}
coverPath := path.Join(podPath, "cover"+ext)
coverFile, err := os.Create(coverPath)
if err != nil {
- log.Printf("Error creating podcast cover: %s", err)
- return
+ return fmt.Errorf("creating podcast cover: %w", err)
}
if _, err := io.Copy(coverFile, resp.Body); err != nil {
- log.Printf("Error while writing cover: %s", err)
- return
+ return fmt.Errorf("writing podcast cover: %w", err)
}
- podcast.ImagePath = path.Join(filepath.Clean(podcast.Title), "cover"+ext)
- p.DB.Save(podcast)
+ podcastPath := filepath.Clean(podcast.Title)
+ podcastFilename := fmt.Sprintf("cover%s", ext)
+ podcast.ImagePath = path.Join(podcastPath, podcastFilename)
+ if err := p.DB.Save(podcast).Error; err != nil {
+ return fmt.Errorf("save podcast: %w", err)
+ }
+ return nil
}
-func (p *Podcasts) doPodcastDownload(podcastEpisode *db.PodcastEpisode, pdFile *os.File, src io.Reader) {
- _, err := io.Copy(pdFile, src)
+func (p *Podcasts) doPodcastDownload(podcastEpisode *db.PodcastEpisode, file *os.File, src io.Reader) error {
+ if _, err := io.Copy(file, src); err != nil {
+ return fmt.Errorf("writing podcast episode: %w", err)
+ }
+ defer file.Close()
+ stat, _ := file.Stat()
+ podcastPath := path.Join(p.PodcastBasePath, podcastEpisode.Path)
+ podcastTags, err := tags.New(podcastPath)
if err != nil {
- log.Printf("Error while writing podcast episode: %s", err)
+ log.Printf("error parsing podcast: %e", err)
podcastEpisode.Status = "error"
p.DB.Save(podcastEpisode)
- return
+ return nil
}
- defer pdFile.Close()
- stat, _ := pdFile.Stat()
- podTags, err := tags.New(path.Join(p.PodcastBasePath, podcastEpisode.Path))
- if err != nil {
- log.Printf("Error parsing podcast: %e", err)
- podcastEpisode.Status = "error"
- p.DB.Save(podcastEpisode)
- return
- }
- podcastEpisode.Bitrate = podTags.Bitrate()
+ podcastEpisode.Bitrate = podcastTags.Bitrate()
podcastEpisode.Status = "completed"
- podcastEpisode.Length = podTags.Length()
+ podcastEpisode.Length = podcastTags.Length()
podcastEpisode.Size = int(stat.Size())
- p.DB.Save(podcastEpisode)
+ return p.DB.Save(podcastEpisode).Error
}
func (p *Podcasts) DeletePodcast(userID, podcastID int) error {
podcast := db.Podcast{}
- err := p.DB.Where("id=? AND user_id=?", podcastID, userID).First(&podcast).Error
+ err := p.DB.
+ Where("id=? AND user_id=?", podcastID, userID).
+ First(&podcast).
+ Error
if err != nil {
return err
}
- userCount := 0
- p.DB.Model(&db.Podcast{}).Where("title=?", podcast.Title).Count(&userCount)
+ var userCount int
+ p.DB.
+ Model(&db.Podcast{}).
+ Where("title=?", podcast.Title).
+ Count(&userCount)
if userCount == 1 {
// only delete the folder if there are not multiple listeners
- err = os.RemoveAll(podcast.Fullpath(p.PodcastBasePath))
- if err != nil {
- return err
+ if err = os.RemoveAll(podcast.Fullpath(p.PodcastBasePath)); err != nil {
+ return fmt.Errorf("delete podcast directory: %w", err)
}
}
err = p.DB.
Where("id=? AND user_id=?", podcastID, userID).
- Delete(db.Podcast{}).Error
+ Delete(db.Podcast{}).
+ Error
if err != nil {
- return err
+ return fmt.Errorf("delete podcast row: %w", err)
}
return nil
}
func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error {
- podcastEp := db.PodcastEpisode{}
- err := p.DB.First(&podcastEp, podcastEpisodeID).Error
+ episode := db.PodcastEpisode{}
+ err := p.DB.First(&episode, podcastEpisodeID).Error
if err != nil {
return err
}
- podcastEp.Status = episodeDeleted
- p.DB.Save(&podcastEp)
- if err := os.Remove(filepath.Join(p.PodcastBasePath, podcastEp.Path)); err != nil {
+ episode.Status = episodeDeleted
+ p.DB.Save(&episode)
+ if err := os.Remove(filepath.Join(p.PodcastBasePath, episode.Path)); err != nil {
return err
}
return err
diff --git a/server/podcasts/podcasts_test.go b/server/podcasts/podcasts_test.go
index 578b97a..279d96a 100644
--- a/server/podcasts/podcasts_test.go
+++ b/server/podcasts/podcasts_test.go
@@ -12,18 +12,18 @@ func TestGetMoreRecentEpisodes(t *testing.T) {
fp := gofeed.NewParser()
newFile, err := os.Open("testdata/rss.new")
if err != nil {
- t.Fatal(err)
+ t.Fatalf("open test data: %v", err)
}
newFeed, err := fp.Parse(newFile)
if err != nil {
- t.Fatal(err)
+ t.Fatalf("parse test data: %v", err)
}
after, err := time.Parse(time.RFC1123, "Mon, 27 Jun 2016 06:33:43 +0000")
if err != nil {
- t.Fatal(err)
+ t.Fatalf("parse time: %v", err)
}
entries := getEntriesAfterDate(newFeed.Items, after)
if len(entries) != 2 {
- t.Errorf("Expected 2 entries, got %d", len(entries))
+ t.Errorf("expected 2 entries, got %d", len(entries))
}
}
diff --git a/server/server.go b/server/server.go
index 299f85d..ec5fea0 100644
--- a/server/server.go
+++ b/server/server.go
@@ -291,7 +291,7 @@ func (s *Server) StartPodcastRefresher(dur time.Duration) (FuncExecute, FuncInte
case <-done:
return nil
case <-ticker.C:
- if err := s.podcast.RefreshPodcasts(0, true); err != nil {
+ if err := s.podcast.RefreshPodcasts(); err != nil {
log.Printf("failed to refresh some feeds: %s", err)
}
}