add support for subsonic podcast api
This commit is contained in:
committed by
Senan Kelly
parent
ce96b9f6fa
commit
9c4286b0e2
@@ -29,6 +29,7 @@ func main() {
|
||||
set := flag.NewFlagSet(version.NAME, flag.ExitOnError)
|
||||
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")
|
||||
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)")
|
||||
@@ -60,6 +61,9 @@ 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) {
|
||||
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)
|
||||
@@ -87,6 +91,7 @@ func main() {
|
||||
CoverCachePath: coverCachePath,
|
||||
ProxyPrefix: *confProxyPrefix,
|
||||
GenreSplit: *confGenreSplit,
|
||||
PodcastPath: *confPodcastPath,
|
||||
})
|
||||
|
||||
var g run.Group
|
||||
@@ -99,6 +104,10 @@ 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)
|
||||
}
|
||||
|
||||
@@ -5,3 +5,4 @@ jukebox-enabled false
|
||||
listen-addr 127.0.0.1:4747
|
||||
proxy-prefix /gonic
|
||||
scan-interval 0
|
||||
podcast-path
|
||||
|
||||
1
go.mod
1
go.mod
@@ -24,6 +24,7 @@ require (
|
||||
github.com/mewkiz/pkg v0.0.0-20200702171441-dd47075182ea // indirect
|
||||
github.com/mitchellh/copystructure v1.0.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.1 // indirect
|
||||
github.com/mmcdole/gofeed v1.1.0
|
||||
github.com/nicksellen/audiotags v0.0.0-20160226222119-94015fa599bd
|
||||
github.com/oklog/run v1.1.0
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c
|
||||
|
||||
23
go.sum
23
go.sum
@@ -11,10 +11,13 @@ github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZC
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
|
||||
github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
github.com/PuerkitoBio/goquery v1.5.1 h1:PSPBGne8NIUWw+/7vFBV+kG2J/5MOjbzc7154OaKCSE=
|
||||
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
|
||||
github.com/andybalholm/cascadia v1.1.0 h1:BuuO6sSfQNFRu1LppgbD25Hr2vLYW25JvxHs5zzsLTo=
|
||||
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
|
||||
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
|
||||
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/d4l3k/messagediff v1.2.2-0.20190829033028-7e0a312ae40b/go.mod h1:Oozbb1TVXFac9FtSIxHBMnBCq2qeH/2KkEQxENCrlLo=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -46,6 +49,7 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20180628210949-0892b62f0d9f/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
@@ -99,6 +103,8 @@ github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
|
||||
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
|
||||
github.com/josephburnett/jd v0.0.0-20191228205456-aa1a7c66b42f h1:ijUonnyvDekPD7lUF4oQ1LV+dKaTnchEzmenMFa6NL4=
|
||||
github.com/josephburnett/jd v0.0.0-20191228205456-aa1a7c66b42f/go.mod h1:aeV+6oc13ogwzcRNHBe4vbyLmoQxMfEDoqyqCU9oE30=
|
||||
github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
|
||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
github.com/karrick/godirwalk v1.16.1 h1:DynhcF+bztK8gooS0+NDJFrdNZjJ3gzVzC545UNA9iw=
|
||||
github.com/karrick/godirwalk v1.16.1/go.mod h1:j4mkqPuvaLI8mp1DroR3P6ad7cyYd4c1qeJ3RV7ULlk=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
@@ -134,6 +140,14 @@ github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/I
|
||||
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/mitchellh/reflectwalk v1.0.1 h1:FVzMWA5RllMAKIdUSC8mdWo3XtwoecrH79BY70sEEpE=
|
||||
github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
|
||||
github.com/mmcdole/gofeed v1.1.0 h1:T2WrGLVJRV04PY2qwhEJLHCt9JiCtBhb6SmC8ZvJH08=
|
||||
github.com/mmcdole/gofeed v1.1.0/go.mod h1:PPiVwgDXLlz2N83KB4TrIim2lyYM5Zn7ZWH9Pi4oHUk=
|
||||
github.com/mmcdole/goxpp v0.0.0-20181012175147-0068e33feabf h1:sWGE2v+hO0Nd4yFU/S/mDBM5plIU8v/Qhfz41hkDIAI=
|
||||
github.com/mmcdole/goxpp v0.0.0-20181012175147-0068e33feabf/go.mod h1:pasqhqstspkosTneA62Nc+2p9SOBBYAPbnmRRWPQ0V8=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/nicksellen/audiotags v0.0.0-20160226222119-94015fa599bd h1:xKn/gU8lZupoZt/HE7a/R3aH93iUO6JwyRsYelQUsRI=
|
||||
github.com/nicksellen/audiotags v0.0.0-20160226222119-94015fa599bd/go.mod h1:B6icauz2l4tkYQxmDtCH4qmNWz/evSW5CsOqp6IE5IE=
|
||||
github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
|
||||
@@ -151,11 +165,14 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ=
|
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/urfave/cli v1.22.3/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/wader/gormstore v0.0.0-20200328121358-65a111a20c23 h1:gtfR002LWpH9vQ1/GLbWBOTcS92cBi5PAR021lArKF8=
|
||||
github.com/wader/gormstore v0.0.0-20200328121358-65a111a20c23/go.mod h1:2z7nYWeR0xUeFNCmlyH6Qt6qigF+Kl/k4LbQbj6Ksus=
|
||||
golang.org/x/crypto v0.0.0-20181112202954-3d3f9f413869/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
@@ -201,6 +218,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2eP
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k=
|
||||
golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -217,6 +236,9 @@ golang.org/x/sys v0.0.0-20201223074533-0d417f636930 h1:vRgIt+nup/B/BwIS0g2oC0haq
|
||||
golang.org/x/sys v0.0.0-20201223074533-0d417f636930/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||
@@ -232,6 +254,7 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/gormigrate.v1 v1.6.0 h1:XpYM6RHQPmzwY7Uyu+t+xxMXc86JYFJn4nEc9HzQjsI=
|
||||
gopkg.in/gormigrate.v1 v1.6.0/go.mod h1:Lf00lQrHqfSYWiTtPcyQabsDdM6ejZaMgV0OU6JMSlw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,7 @@ import (
|
||||
"go.senan.xyz/gonic/server/assets"
|
||||
"go.senan.xyz/gonic/server/ctrlbase"
|
||||
"go.senan.xyz/gonic/server/db"
|
||||
"go.senan.xyz/gonic/server/podcasts"
|
||||
"go.senan.xyz/gonic/version"
|
||||
)
|
||||
|
||||
@@ -82,9 +83,10 @@ type Controller struct {
|
||||
buffPool *bpool.BufferPool
|
||||
templates map[string]*template.Template
|
||||
sessDB *gormstore.Store
|
||||
Podcasts *podcasts.Podcasts
|
||||
}
|
||||
|
||||
func New(b *ctrlbase.Controller, sessDB *gormstore.Store) *Controller {
|
||||
func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts) *Controller {
|
||||
tmplBase := template.
|
||||
New("layout").
|
||||
Funcs(sprig.FuncMap()).
|
||||
@@ -99,6 +101,7 @@ func New(b *ctrlbase.Controller, sessDB *gormstore.Store) *Controller {
|
||||
buffPool: bpool.NewBufferPool(64),
|
||||
templates: pagesFromPaths(tmplBase, prefixPages),
|
||||
sessDB: sessDB,
|
||||
Podcasts: podcasts,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +127,9 @@ type templateData struct {
|
||||
CurrentLastFMAPISecret string
|
||||
DefaultListenBrainzURL string
|
||||
SelectedUser *db.User
|
||||
//
|
||||
PodcastsEnabled bool
|
||||
Podcasts []*db.Podcast
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/mmcdole/gofeed"
|
||||
"go.senan.xyz/gonic/server/db"
|
||||
"go.senan.xyz/gonic/server/encode"
|
||||
"go.senan.xyz/gonic/server/scanner"
|
||||
@@ -45,6 +46,10 @@ 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
|
||||
@@ -415,3 +420,47 @@ func (c *Controller) ServeDeleteTranscodePrefDo(r *http.Request) *Response {
|
||||
redirect: "/admin/home",
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) ServePodcastAddDo(r *http.Request) *Response {
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
rssURL := r.FormValue("feed")
|
||||
fp := gofeed.NewParser()
|
||||
feed, err := fp.ParseURL(rssURL)
|
||||
if err != nil {
|
||||
return &Response{
|
||||
redirect: "/admin/home",
|
||||
flashW: []string{fmt.Sprintf("could not create feed: %v", err)},
|
||||
}
|
||||
}
|
||||
_, err = c.Podcasts.AddNewPodcast(feed, user.ID)
|
||||
if err != nil {
|
||||
return &Response{
|
||||
redirect: "/admin/home",
|
||||
flashW: []string{fmt.Sprintf("could not create feed: %v", err)},
|
||||
}
|
||||
}
|
||||
return &Response{
|
||||
redirect: "/admin/home",
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Controller) ServePodcastDeleteDo(r *http.Request) *Response {
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
id, err := strconv.Atoi(r.URL.Query().Get("id"))
|
||||
if err != nil {
|
||||
return &Response{
|
||||
err: "please provide a valid podcast id",
|
||||
code: 400,
|
||||
}
|
||||
}
|
||||
err = c.Podcasts.DeletePodcast(user.ID, id)
|
||||
if err != nil {
|
||||
return &Response{
|
||||
err: "please provide a valid podcast id",
|
||||
code: 400,
|
||||
}
|
||||
}
|
||||
return &Response{
|
||||
redirect: "/admin/home",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"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"
|
||||
)
|
||||
|
||||
type CtxKey int
|
||||
@@ -30,6 +31,7 @@ type Controller struct {
|
||||
CoverCachePath string
|
||||
Jukebox *jukebox.Jukebox
|
||||
Scrobblers []scrobble.Scrobbler
|
||||
Podcasts *podcasts.Podcasts
|
||||
}
|
||||
|
||||
type metaResponse struct {
|
||||
|
||||
@@ -41,6 +41,9 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
|
||||
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")
|
||||
}
|
||||
// fetch user to get lastfm session
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
// fetch track for getting info to send to last.fm function
|
||||
@@ -107,6 +110,7 @@ func (c *Controller) ServeGetUser(r *http.Request) *spec.Response {
|
||||
AdminRole: user.IsAdmin,
|
||||
JukeboxRole: true,
|
||||
ScrobblingEnabled: hasLastFM || hasListenBrainz,
|
||||
PodcastRole: c.Podcasts.PodcastBasePath != "",
|
||||
Folder: []int{1},
|
||||
}
|
||||
return sub
|
||||
|
||||
95
server/ctrlsubsonic/handlers_podcast.go
Normal file
95
server/ctrlsubsonic/handlers_podcast.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package ctrlsubsonic
|
||||
|
||||
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"
|
||||
"go.senan.xyz/gonic/server/db"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
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, _ = c.Podcasts.GetPodcast(id.Value, user.ID, isIncludeEpisodes)
|
||||
return sub
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
if err := c.Podcasts.DownloadEpisode(id.Value); err != nil {
|
||||
return spec.NewError(10, "Failed to download episode: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
|
||||
func (c *Controller) ServeCreatePodcastChannel(r *http.Request) *spec.Response {
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
params := r.Context().Value(CtxParams).(params.Params)
|
||||
rssURL, _ := params.Get("url")
|
||||
fp := gofeed.NewParser()
|
||||
feed, err := fp.ParseURL(rssURL)
|
||||
if err != nil {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
|
||||
func (c *Controller) ServeDeletePodcastChannel(r *http.Request) *spec.Response {
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
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")
|
||||
}
|
||||
err = c.Podcasts.DeletePodcast(user.ID, id.Value)
|
||||
if err != nil {
|
||||
return spec.NewError(10, "Failed to delete podcast: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
err = c.Podcasts.DeletePodcastEpisode(id.Value)
|
||||
if err != nil {
|
||||
return spec.NewError(10, "Failed to delete podcast: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
|
||||
"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/encode"
|
||||
)
|
||||
@@ -44,6 +45,12 @@ func streamGetTrack(dbc *db.DB, trackID int) (*db.Track, error) {
|
||||
return &track, err
|
||||
}
|
||||
|
||||
func streamGetPodcast(dbc *db.DB, podcastID int) (*db.PodcastEpisode, error) {
|
||||
podcast := db.PodcastEpisode{}
|
||||
err := dbc.First(&podcast, podcastID).Error
|
||||
return &podcast, err
|
||||
}
|
||||
|
||||
func streamUpdateStats(dbc *db.DB, userID, albumID int) {
|
||||
play := db.Play{
|
||||
AlbumID: albumID,
|
||||
@@ -67,24 +74,51 @@ var (
|
||||
errCoverEmpty = errors.New("no cover found for that folder")
|
||||
)
|
||||
|
||||
func coverGetPath(dbc *db.DB, musicPath string, id int) (string, error) {
|
||||
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.
|
||||
err = dbc.DB.
|
||||
Select("id, left_path, right_path, cover").
|
||||
First(folder, id).
|
||||
First(folder, id.Value).
|
||||
Error
|
||||
if gorm.IsRecordNotFoundError(err) {
|
||||
return "", errCoverNotFound
|
||||
}
|
||||
if folder.Cover == "" {
|
||||
return "", errCoverEmpty
|
||||
}
|
||||
return path.Join(
|
||||
coverPath = path.Join(
|
||||
musicPath,
|
||||
folder.LeftPath,
|
||||
folder.RightPath,
|
||||
folder.Cover,
|
||||
), nil
|
||||
)
|
||||
if folder.Cover == "" {
|
||||
return "", errCoverEmpty
|
||||
}
|
||||
case specid.Podcast:
|
||||
podcast := &db.Podcast{}
|
||||
err = dbc.First(podcast, id.Value).Error
|
||||
|
||||
if podcast.ImagePath == "" {
|
||||
return "", errCoverEmpty
|
||||
}
|
||||
coverPath = path.Join(podcastPath, podcast.ImagePath)
|
||||
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)
|
||||
default:
|
||||
}
|
||||
if gorm.IsRecordNotFoundError(err) {
|
||||
return "", errCoverNotFound
|
||||
}
|
||||
return coverPath, nil
|
||||
}
|
||||
|
||||
func coverScaleAndSave(absPath, cachePath string, size int) error {
|
||||
@@ -118,7 +152,7 @@ func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *s
|
||||
_, err = os.Stat(cachePath)
|
||||
switch {
|
||||
case os.IsNotExist(err):
|
||||
coverPath, err := coverGetPath(c.DB, c.MusicPath, id.Value)
|
||||
coverPath, err := coverGetPath(c.DB, c.MusicPath, c.Podcasts.PodcastBasePath, id)
|
||||
if err != nil {
|
||||
return spec.NewError(10, "couldn't find cover `%s`: %v", id, err)
|
||||
}
|
||||
@@ -140,35 +174,53 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
|
||||
if err != nil {
|
||||
return spec.NewError(10, "please provide an `id` parameter")
|
||||
}
|
||||
track, err := streamGetTrack(c.DB, id.Value)
|
||||
var audioFile db.AudioFile
|
||||
var audioPath string
|
||||
if id.Type == 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 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil && id.Type != specid.Podcast {
|
||||
return spec.NewError(70, "media with id `%d` was not found", id.Value)
|
||||
}
|
||||
user := r.Context().Value(CtxUser).(*db.User)
|
||||
defer streamUpdateStats(c.DB, user.ID, track.Album.ID)
|
||||
if id.Type == specid.Track {
|
||||
defer streamUpdateStats(c.DB, user.ID, audioFile.(*db.Track).Album.ID)
|
||||
}
|
||||
pref := streamGetTransPref(c.DB, user.ID, params.GetOr("c", ""))
|
||||
trackPath := path.Join(c.MusicPath, track.RelPath())
|
||||
//
|
||||
onInvalidProfile := func() error {
|
||||
log.Printf("serving raw `%s`\n", track.Filename)
|
||||
w.Header().Set("Content-Type", track.MIME())
|
||||
http.ServeFile(w, r, trackPath)
|
||||
log.Printf("serving raw `%s`\n", audioFile.AudioFilename())
|
||||
w.Header().Set("Content-Type", audioFile.MIME())
|
||||
http.ServeFile(w, r, audioPath)
|
||||
return nil
|
||||
}
|
||||
onCacheHit := func(profile encode.Profile, path string) error {
|
||||
log.Printf("serving transcode `%s`: cache [%s/%dk] hit!\n",
|
||||
track.Filename, profile.Format, profile.Bitrate)
|
||||
audioFile.AudioFilename(), profile.Format, profile.Bitrate)
|
||||
http.ServeFile(w, r, path)
|
||||
return nil
|
||||
}
|
||||
onCacheMiss := func(profile encode.Profile) (io.Writer, error) {
|
||||
log.Printf("serving transcode `%s`: cache [%s/%dk] miss!\n",
|
||||
track.Filename, profile.Format, profile.Bitrate)
|
||||
audioFile.AudioFilename(), profile.Format, profile.Bitrate)
|
||||
return w, nil
|
||||
}
|
||||
encodeOptions := encode.Options{
|
||||
TrackPath: trackPath,
|
||||
TrackBitrate: track.Bitrate,
|
||||
TrackPath: audioPath,
|
||||
TrackBitrate: audioFile.AudioBitrate(),
|
||||
CachePath: c.CachePath,
|
||||
ProfileName: pref.Profile,
|
||||
PreferredBitrate: params.GetOrInt("maxBitRate", 0),
|
||||
@@ -177,7 +229,7 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
|
||||
OnCacheMiss: onCacheMiss,
|
||||
}
|
||||
if err := encode.Encode(encodeOptions); err != nil {
|
||||
log.Printf("serving transcode `%s`: error: %v\n", track.Filename, err)
|
||||
log.Printf("serving transcode `%s`: error: %v\n", audioFile.AudioFilename(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -188,13 +240,25 @@ func (c *Controller) ServeDownload(w http.ResponseWriter, r *http.Request) *spec
|
||||
if err != nil {
|
||||
return spec.NewError(10, "please provide an `id` parameter")
|
||||
}
|
||||
track, err := streamGetTrack(c.DB, id.Value)
|
||||
var filePath string
|
||||
var audioFile db.AudioFile
|
||||
if id.Type == specid.Track {
|
||||
track, _ := streamGetTrack(c.DB, id.Value)
|
||||
audioFile = track
|
||||
filePath = path.Join(c.MusicPath, track.RelPath())
|
||||
if err != nil {
|
||||
return spec.NewError(70, "media with id `%s` was not found", id)
|
||||
return spec.NewError(70, "track with id `%s` was not found", id)
|
||||
}
|
||||
log.Printf("serving raw `%s`\n", track.Filename)
|
||||
w.Header().Set("Content-Type", track.MIME())
|
||||
trackPath := path.Join(c.MusicPath, track.RelPath())
|
||||
http.ServeFile(w, r, trackPath)
|
||||
} else if id.Type == specid.PodcastEpisode {
|
||||
podcast, err := streamGetPodcast(c.DB, id.Value)
|
||||
audioFile = podcast
|
||||
filePath = path.Join(c.Podcasts.PodcastBasePath, podcast.Path)
|
||||
if err != nil {
|
||||
return spec.NewError(70, "podcast with id `%s` was not found", id)
|
||||
}
|
||||
}
|
||||
log.Printf("serving raw `%s`\n", audioFile.AudioFilename())
|
||||
w.Header().Set("Content-Type", audioFile.MIME())
|
||||
http.ServeFile(w, r, filePath)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package ctrlsubsonic
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
|
||||
)
|
||||
|
||||
func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
|
||||
sub := spec.NewResponse()
|
||||
sub.Podcasts = &spec.Podcasts{
|
||||
List: []struct{}{},
|
||||
}
|
||||
return sub
|
||||
}
|
||||
@@ -288,5 +288,37 @@ type JukeboxPlaylist struct {
|
||||
}
|
||||
|
||||
type Podcasts struct {
|
||||
List []struct{} `xml:"channel" json:"channel"`
|
||||
List []PodcastChannel `xml:"channel" json:"channel"`
|
||||
}
|
||||
|
||||
type PodcastChannel struct {
|
||||
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"`
|
||||
OriginalImageURL string `xml:"originalImageUrl,attr" json:"originalImageUrl,omitempty"`
|
||||
Status string `xml:"status,attr" json:"status"`
|
||||
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"`
|
||||
Title string `xml:"title,attr" json:"title"`
|
||||
Description string `xml:"description,attr" json:"description"`
|
||||
PublishDate time.Time `xml:"publishDate,attr" json:"publishDate"`
|
||||
Status string `xml:"status,attr" json:"status"`
|
||||
Parent string `xml:"parent,attr" json:"parent"`
|
||||
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"`
|
||||
Size int `xml:"size,attr" json:"size"`
|
||||
ContentType string `xml:"contentType,attr" json:"contentType"`
|
||||
Suffix string `xml:"suffix,attr" json:"suffix"`
|
||||
Duration int `xml:"duration,attr" json:"duration"`
|
||||
BitRate int `xml:"bitRate,attr" json:"bitrate"`
|
||||
Path string `xml:"path,attr" json:"path"`
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ const (
|
||||
Artist IDT = "ar"
|
||||
Album IDT = "al"
|
||||
Track IDT = "tr"
|
||||
Podcast IDT = "pd"
|
||||
PodcastEpisode IDT = "pe"
|
||||
separator = "-"
|
||||
)
|
||||
|
||||
@@ -49,6 +51,10 @@ func New(in string) (ID, error) {
|
||||
return ID{Type: Album, Value: val}, nil
|
||||
case Track:
|
||||
return ID{Type: Track, Value: val}, nil
|
||||
case Podcast:
|
||||
return ID{Type: Podcast, Value: val}, nil
|
||||
case PodcastEpisode:
|
||||
return ID{Type: PodcastEpisode, Value: val}, nil
|
||||
default:
|
||||
return ID{}, fmt.Errorf("%q: %w", partType, ErrBadPrefix)
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ func New(path string) (*DB, error) {
|
||||
migrateAddAlbumIDX(),
|
||||
migrateMultiGenre(),
|
||||
migrateListenBrainz(),
|
||||
migratePodcast(),
|
||||
))
|
||||
if err = migr.Migrate(); err != nil {
|
||||
return nil, fmt.Errorf("migrating to latest version: %w", err)
|
||||
|
||||
@@ -211,6 +211,7 @@ func migrateMultiGenre() gormigrate.Migration {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func migrateListenBrainz() gormigrate.Migration {
|
||||
return gormigrate.Migration{
|
||||
ID: "202101081149",
|
||||
@@ -225,3 +226,16 @@ func migrateListenBrainz() gormigrate.Migration {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func migratePodcast() gormigrate.Migration {
|
||||
return gormigrate.Migration{
|
||||
ID: "202101111537",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
step := tx.AutoMigrate(
|
||||
Podcast{},
|
||||
PodcastEpisode{},
|
||||
)
|
||||
return step.Error
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ package db
|
||||
|
||||
import (
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -67,6 +68,15 @@ type Genre struct {
|
||||
TrackCount int `sql:"-"`
|
||||
}
|
||||
|
||||
// AudioFile is used to avoid some duplication in handlers_raw.go
|
||||
// between Track and Podcast
|
||||
type AudioFile interface {
|
||||
AudioFilename() string
|
||||
Ext() string
|
||||
MIME() string
|
||||
AudioBitrate() int
|
||||
}
|
||||
|
||||
type Track struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
@@ -109,6 +119,14 @@ func (t *Track) Ext() string {
|
||||
return longExt[1:]
|
||||
}
|
||||
|
||||
func (t *Track) AudioFilename() string {
|
||||
return t.Filename
|
||||
}
|
||||
|
||||
func (t *Track) AudioBitrate() int {
|
||||
return t.Bitrate
|
||||
}
|
||||
|
||||
func (t *Track) MIME() string {
|
||||
v, _ := mime.FromExtension(t.Ext())
|
||||
return v
|
||||
@@ -270,3 +288,68 @@ type AlbumGenre struct {
|
||||
Genre *Genre
|
||||
GenreID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
|
||||
}
|
||||
|
||||
type Podcast struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
UpdatedAt time.Time
|
||||
ModifiedAt time.Time
|
||||
UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
URL string
|
||||
Title string
|
||||
Description string
|
||||
ImageURL string
|
||||
ImagePath string
|
||||
Error string
|
||||
}
|
||||
|
||||
func (p *Podcast) Fullpath(podcastPath string) string {
|
||||
return filepath.Join(podcastPath, filepath.Clean(p.Title))
|
||||
}
|
||||
|
||||
func (p *Podcast) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.Podcast, Value: p.ID}
|
||||
}
|
||||
|
||||
type PodcastEpisode struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ModifiedAt time.Time
|
||||
PodcastID int `gorm:"not null" sql:"default: null; type:int REFERENCES podcasts(id) ON DELETE CASCADE"`
|
||||
Title string
|
||||
Description string
|
||||
PublishDate *time.Time
|
||||
AudioURL string
|
||||
Bitrate int
|
||||
Length int
|
||||
Size int
|
||||
Path string
|
||||
Filename string
|
||||
Status string
|
||||
Error string
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) SID() *specid.ID {
|
||||
return &specid.ID{Type: specid.PodcastEpisode, Value: pe.ID}
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) AudioFilename() string {
|
||||
return pe.Filename
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) Ext() string {
|
||||
longExt := path.Ext(pe.Filename)
|
||||
if len(longExt) < 1 {
|
||||
return ""
|
||||
}
|
||||
return longExt[1:]
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) MIME() string {
|
||||
v, _ := mime.FromExtension(pe.Ext())
|
||||
return v
|
||||
}
|
||||
|
||||
func (pe *PodcastEpisode) AudioBitrate() int {
|
||||
return pe.Bitrate
|
||||
}
|
||||
|
||||
440
server/podcasts/podcasts.go
Normal file
440
server/podcasts/podcasts.go
Normal file
@@ -0,0 +1,440 @@
|
||||
package podcasts
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type Podcasts struct {
|
||||
DB *db.DB
|
||||
PodcastBasePath string
|
||||
}
|
||||
|
||||
const (
|
||||
episodeDownloading = "downloading"
|
||||
episodeSkipped = "skipped"
|
||||
episodeDeleted = "deleted"
|
||||
)
|
||||
|
||||
func (p *Podcasts) GetAllPodcasts(userID int, includeEpisodes bool) (*spec.Podcasts, error) {
|
||||
podcasts := []*db.Podcast{}
|
||||
err := p.DB.Where("user_id=?", userID).Order("").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,
|
||||
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) 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).
|
||||
Order("publish_date DESC").
|
||||
Find(&dbEpisodes).Error; err != nil {
|
||||
return nil, 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
|
||||
}
|
||||
|
||||
func (p *Podcasts) AddNewPodcast(feed *gofeed.Feed, userID int) (*db.Podcast, error) {
|
||||
podcast := db.Podcast{
|
||||
Description: feed.Description,
|
||||
ImageURL: feed.Image.URL,
|
||||
UserID: userID,
|
||||
Title: feed.Title,
|
||||
URL: feed.FeedLink,
|
||||
}
|
||||
podPath := podcast.Fullpath(p.PodcastBasePath)
|
||||
err := os.Mkdir(podPath, 0755)
|
||||
if err != nil && !os.IsExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.DB.Save(&podcast).Error; err != nil {
|
||||
return &podcast, err
|
||||
}
|
||||
if err := p.AddNewEpisodes(userID, podcast.ID, feed.Items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
go p.downloadPodcastCover(podPath, &podcast)
|
||||
|
||||
return &podcast, nil
|
||||
}
|
||||
|
||||
func getEntriesAfterDate(feed []*gofeed.Item, after time.Time) []*gofeed.Item {
|
||||
items := []*gofeed.Item{}
|
||||
for _, item := range feed {
|
||||
if item.PublishedParsed.Before(after) || item.PublishedParsed.Equal(after) {
|
||||
continue
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (p *Podcasts) AddNewEpisodes(userID int, podcastID int, items []*gofeed.Item) error {
|
||||
podcastEpisode := db.PodcastEpisode{}
|
||||
err := p.DB.
|
||||
Where("podcast_id=?", podcastID).
|
||||
Order("publish_date DESC").
|
||||
First(&podcastEpisode).Error
|
||||
itemFound := true
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
itemFound = false
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
if !itemFound {
|
||||
for _, item := range items {
|
||||
if err := p.AddEpisode(podcastID, item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, item := range getEntriesAfterDate(items, *podcastEpisode.PublishDate) {
|
||||
if err := p.AddEpisode(podcastID, item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSecondsFromString(time string) int {
|
||||
duration, err := strconv.Atoi(time)
|
||||
if err == nil {
|
||||
return duration
|
||||
}
|
||||
splitTime := strings.Split(time, ":")
|
||||
if len(splitTime) == 3 {
|
||||
hours, _ := strconv.Atoi(splitTime[0])
|
||||
minutes, _ := strconv.Atoi(splitTime[1])
|
||||
seconds, _ := strconv.Atoi(splitTime[2])
|
||||
return (3600 * hours) + (60 * minutes) + seconds
|
||||
}
|
||||
if len(splitTime) == 2 {
|
||||
minutes, _ := strconv.Atoi(splitTime[0])
|
||||
seconds, _ := strconv.Atoi(splitTime[1])
|
||||
return (60 * minutes) + seconds
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (p *Podcasts) AddEpisode(podcastID int, item *gofeed.Item) error {
|
||||
duration := 0
|
||||
// if it has the media extension use it
|
||||
for _, content := range item.Extensions["media"]["content"] {
|
||||
durationExt := content.Attrs["duration"]
|
||||
duration = getSecondsFromString(durationExt)
|
||||
if duration != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
// if the itunes extension is available, use AddEpisode
|
||||
if duration == 0 {
|
||||
duration = getSecondsFromString(item.ITunesExt.Duration)
|
||||
}
|
||||
|
||||
for _, enc := range item.Enclosures {
|
||||
if !strings.HasPrefix(enc.Type, "audio") {
|
||||
continue
|
||||
}
|
||||
size, _ := strconv.Atoi(enc.Length)
|
||||
podcastEpisode := db.PodcastEpisode{
|
||||
PodcastID: podcastID,
|
||||
Description: item.Description,
|
||||
Title: item.Title,
|
||||
Length: duration,
|
||||
Size: size,
|
||||
PublishDate: item.PublishedParsed,
|
||||
AudioURL: enc.URL,
|
||||
Status: episodeSkipped,
|
||||
}
|
||||
if err := p.DB.Save(&podcastEpisode).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) RefreshPodcasts(userID int, serverWide bool) 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 != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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)
|
||||
continue
|
||||
}
|
||||
err = p.AddNewEpisodes(userID, podcast.ID, feed.Items)
|
||||
if err != nil {
|
||||
log.Printf("Error adding episodes: %s", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) DownloadEpisode(episodeID int) error {
|
||||
podcastEpisode := db.PodcastEpisode{}
|
||||
podcast := db.Podcast{}
|
||||
err := p.DB.Where("id=?", episodeID).First(&podcastEpisode).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = p.DB.Where("id=?", podcastEpisode.PodcastID).First(&podcast).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if podcastEpisode.Status == episodeDownloading {
|
||||
log.Printf("Already downloading podcast episode with id %d", episodeID)
|
||||
return nil
|
||||
}
|
||||
podcastEpisode.Status = episodeDownloading
|
||||
p.DB.Save(&podcastEpisode)
|
||||
// nolint: bodyclose
|
||||
resp, err := http.Get(podcastEpisode.AudioURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
filename, ok := getContentDispositionFilename(resp.Header.Get("content-disposition"))
|
||||
if !ok {
|
||||
audioURL, err := url.Parse(podcastEpisode.AudioURL)
|
||||
if err != nil {
|
||||
return 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
|
||||
}
|
||||
podcastEpisode.Filename = filename
|
||||
podcastEpisode.Path = path.Join(filepath.Clean(podcast.Title), filename)
|
||||
p.DB.Save(&podcastEpisode)
|
||||
go p.doPodcastDownload(&podcastEpisode, audioFile, resp.Body)
|
||||
return nil
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
return titlePath
|
||||
}
|
||||
// try to find a filename like FILENAME (1).mp3 incrementing
|
||||
return findEpisode(podcast.Fullpath(p.PodcastBasePath), filename, 1)
|
||||
}
|
||||
|
||||
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) {
|
||||
return testFile
|
||||
}
|
||||
return findEpisode(base, filename, count+1)
|
||||
}
|
||||
|
||||
func getContentDispositionFilename(header string) (string, bool) {
|
||||
_, params, _ := mime.ParseMediaType(header)
|
||||
filename, ok := params["filename"]
|
||||
return filename, ok
|
||||
}
|
||||
|
||||
func (p *Podcasts) downloadPodcastCover(podPath string, podcast *db.Podcast) {
|
||||
imageURL, err := url.Parse(podcast.ImageURL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ext := path.Ext(imageURL.Path)
|
||||
resp, err := http.Get(podcast.ImageURL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if ext == "" {
|
||||
filename, _ := getContentDispositionFilename(resp.Header.Get("content-disposition"))
|
||||
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
|
||||
}
|
||||
if _, err := io.Copy(coverFile, resp.Body); err != nil {
|
||||
log.Printf("Error while writing cover: %s", err)
|
||||
return
|
||||
}
|
||||
podcast.ImagePath = path.Join(filepath.Clean(podcast.Title), "cover"+ext)
|
||||
p.DB.Save(podcast)
|
||||
}
|
||||
|
||||
func (p *Podcasts) doPodcastDownload(podcastEpisode *db.PodcastEpisode, pdFile *os.File, src io.Reader) {
|
||||
_, err := io.Copy(pdFile, src)
|
||||
if err != nil {
|
||||
log.Printf("Error while writing podcast episode: %s", err)
|
||||
podcastEpisode.Status = "error"
|
||||
p.DB.Save(podcastEpisode)
|
||||
return
|
||||
}
|
||||
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.Status = "completed"
|
||||
podcastEpisode.Length = podTags.Length()
|
||||
podcastEpisode.Size = int(stat.Size())
|
||||
p.DB.Save(podcastEpisode)
|
||||
}
|
||||
|
||||
func (p *Podcasts) DeletePodcast(userID, podcastID int) error {
|
||||
podcast := db.Podcast{}
|
||||
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)
|
||||
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
|
||||
}
|
||||
}
|
||||
err = p.DB.
|
||||
Where("id=? AND user_id=?", podcastID, userID).
|
||||
Delete(db.Podcast{}).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error {
|
||||
podcastEp := db.PodcastEpisode{}
|
||||
err := p.DB.First(&podcastEp, 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 {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
29
server/podcasts/podcasts_test.go
Normal file
29
server/podcasts/podcasts_test.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package podcasts
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mmcdole/gofeed"
|
||||
)
|
||||
|
||||
func TestGetMoreRecentEpisodes(t *testing.T) {
|
||||
fp := gofeed.NewParser()
|
||||
newFile, err := os.Open("testdata/rss.new")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newFeed, err := fp.Parse(newFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := time.Parse(time.RFC1123, "Mon, 27 Jun 2016 06:33:43 +0000")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries := getEntriesAfterDate(newFeed.Items, after)
|
||||
if len(entries) != 2 {
|
||||
t.Errorf("Expected 2 entries, got %d", len(entries))
|
||||
}
|
||||
}
|
||||
83
server/podcasts/testdata/rss.new
vendored
Normal file
83
server/podcasts/testdata/rss.new
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:cc="http://web.resource.org/cc/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<channel>
|
||||
<atom:link href="https://internetbox.libsyn.com/rss" rel="self" type="application/rss+xml"/>
|
||||
<title>Internet Box</title>
|
||||
<pubDate>Mon, 01 Apr 2019 04:35:43 +0000</pubDate>
|
||||
<lastBuildDate>Sun, 10 Jan 2021 00:07:33 +0000</lastBuildDate>
|
||||
<generator>Libsyn WebEngine 2.0</generator>
|
||||
<link>https://internetboxpodcast.com</link>
|
||||
<language>en</language>
|
||||
<copyright><![CDATA[]]></copyright>
|
||||
<docs>https://internetboxpodcast.com</docs>
|
||||
<managingEditor>admin@internetboxpodcast.com (admin@internetboxpodcast.com)</managingEditor>
|
||||
<itunes:summary><![CDATA[Michael, Mike, Barbara, Ray, Andrew, Dylon, Lindsay, and Kerry from the AH community talk about various subjects.]]></itunes:summary>
|
||||
<image>
|
||||
<url>https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png</url>
|
||||
<title>Internet Box</title>
|
||||
<link><![CDATA[https://internetboxpodcast.com]]></link>
|
||||
</image>
|
||||
<itunes:author>Internet Box Crew</itunes:author>
|
||||
<itunes:keywords>achievement,box,friendship,hunter,internet,is,little,magic,mlp,my,pony,rooster,teeth</itunes:keywords>
|
||||
<itunes:category text="Leisure">
|
||||
<itunes:category text="Video Games"/>
|
||||
</itunes:category>
|
||||
<itunes:category text="Comedy"/>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:owner>
|
||||
<itunes:name><![CDATA[Mike]]></itunes:name>
|
||||
<itunes:email>admin@internetboxpodcast.com</itunes:email>
|
||||
</itunes:owner>
|
||||
<description><![CDATA[Michael, Mike, Barbara, Ray, Andrew, Dylon, Lindsay, and Kerry from the AH community talk about various subjects.]]></description>
|
||||
<itunes:subtitle><![CDATA[Various members from the AH community discuss games, ponies, and life in general.]]></itunes:subtitle>
|
||||
<itunes:type>episodic</itunes:type>
|
||||
|
||||
|
||||
|
||||
|
||||
<item>
|
||||
<title>Episode 128</title>
|
||||
<pubDate>Mon, 01 Apr 2019 04:35:43 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[c60f174610d44b408901d6a8d98366b4]]></guid>
|
||||
<link><![CDATA[https://internetboxpodcast.com/episode-128/]]></link>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<description><![CDATA[<p> </p> <p>The Internet Box is fooling around this week!</p> <p> </p>]]></description>
|
||||
<content:encoded><![CDATA[<p> </p> <p>The Internet Box is fooling around this week!</p> <p> </p>]]></content:encoded>
|
||||
<enclosure length="14637384" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode128.mp3?dest-id=79492" />
|
||||
<itunes:duration>44:41</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,meme,fools,april,reddit,copypaste,inernet</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[ The Internet Box is fooling around this week! ]]></itunes:subtitle>
|
||||
<itunes:episodeType>full</itunes:episodeType>
|
||||
</item>
|
||||
<item>
|
||||
<title>Episode 127</title>
|
||||
<pubDate>Sat, 06 Aug 2016 04:46:28 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[99b830789a90b2b6a712382fe4bffc6b]]></guid>
|
||||
<link><![CDATA[http://internetboxpodcast.com/episode-127/]]></link>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<description><![CDATA[<p>The Internet Box is a national treasure this week!</p>]]></description>
|
||||
<content:encoded><![CDATA[<p>The Internet Box is a national treasure this week!</p>]]></content:encoded>
|
||||
<enclosure length="152364335" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode127.mp3?dest-id=79492" />
|
||||
<itunes:duration>01:45:48</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,2,internet,cage,movies,national,go,season,treasure,nic,bane,pokemon</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[The Internet Box is a national treasure this week!]]></itunes:subtitle>
|
||||
</item>
|
||||
<item>
|
||||
<title>Episode 126</title>
|
||||
<pubDate>Mon, 27 Jun 2016 06:33:43 +0000</pubDate>
|
||||
<guid isPermaLink="false"><![CDATA[d5113fc98b7baf005bf66b225b166ee0]]></guid>
|
||||
<link><![CDATA[http://internetboxpodcast.com/episode-126/]]></link>
|
||||
<itunes:image href="https://ssl-static.libsyn.com/p/assets/d/d/3/3/dd338b309838f617/iTunes.png" />
|
||||
<description><![CDATA[<p>The Internet Box is clicking this week!</p>]]></description>
|
||||
<content:encoded><![CDATA[<p>The Internet Box is clicking this week!</p>]]></content:encoded>
|
||||
<enclosure length="66139165" type="audio/mpeg" url="https://traffic.libsyn.com/secure/internetbox/InternetBoxEpisode126.mp3?dest-id=79492" />
|
||||
<itunes:duration>01:20:42</itunes:duration>
|
||||
<itunes:explicit>yes</itunes:explicit>
|
||||
<itunes:keywords>box,2,factory,internet,pizza,future,robots,season,farts,cake,via,reddit,313,vorarephilia</itunes:keywords>
|
||||
<itunes:subtitle><![CDATA[The Internet Box is clicking this week!]]></itunes:subtitle>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic"
|
||||
"go.senan.xyz/gonic/server/db"
|
||||
"go.senan.xyz/gonic/server/jukebox"
|
||||
"go.senan.xyz/gonic/server/podcasts"
|
||||
"go.senan.xyz/gonic/server/scanner"
|
||||
"go.senan.xyz/gonic/server/scrobble"
|
||||
"go.senan.xyz/gonic/server/scrobble/lastfm"
|
||||
@@ -26,6 +27,7 @@ import (
|
||||
type Options struct {
|
||||
DB *db.DB
|
||||
MusicPath string
|
||||
PodcastPath string
|
||||
CachePath string
|
||||
CoverCachePath string
|
||||
ProxyPrefix string
|
||||
@@ -37,12 +39,14 @@ type Server struct {
|
||||
jukebox *jukebox.Jukebox
|
||||
router *mux.Router
|
||||
sessDB *gormstore.Store
|
||||
podcast *podcasts.Podcasts
|
||||
}
|
||||
|
||||
func New(opts Options) *Server {
|
||||
// ** begin sanitation
|
||||
opts.MusicPath = filepath.Clean(opts.MusicPath)
|
||||
opts.CachePath = filepath.Clean(opts.CachePath)
|
||||
opts.PodcastPath = filepath.Clean(opts.PodcastPath)
|
||||
// ** begin controllers
|
||||
scanner := scanner.New(opts.MusicPath, opts.DB, opts.GenreSplit)
|
||||
jukebox := jukebox.New(opts.MusicPath)
|
||||
@@ -64,7 +68,8 @@ func New(opts Options) *Server {
|
||||
sessDB.SessionOpts.HttpOnly = true
|
||||
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode
|
||||
//
|
||||
ctrlAdmin := ctrladmin.New(base, sessDB)
|
||||
pcInit := &podcasts.Podcasts{DB: opts.DB, PodcastBasePath: opts.PodcastPath}
|
||||
ctrlAdmin := ctrladmin.New(base, sessDB, pcInit)
|
||||
scrobblers := []scrobble.Scrobbler{
|
||||
&lastfm.Scrobbler{DB: opts.DB},
|
||||
&listenbrainz.Scrobbler{},
|
||||
@@ -75,6 +80,7 @@ func New(opts Options) *Server {
|
||||
CoverCachePath: opts.CoverCachePath,
|
||||
Jukebox: jukebox,
|
||||
Scrobblers: scrobblers,
|
||||
Podcasts: pcInit,
|
||||
}
|
||||
setupMisc(r, base)
|
||||
setupAdmin(r.PathPrefix("/admin").Subrouter(), ctrlAdmin)
|
||||
@@ -85,6 +91,7 @@ func New(opts Options) *Server {
|
||||
jukebox: jukebox,
|
||||
router: r,
|
||||
sessDB: sessDB,
|
||||
podcast: &podcasts.Podcasts{DB: opts.DB, PodcastBasePath: opts.PodcastPath},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +142,10 @@ func setupAdmin(r *mux.Router, ctrl *ctrladmin.Controller) {
|
||||
routUser.Handle("/delete_playlist_do", ctrl.H(ctrl.ServeDeletePlaylistDo))
|
||||
routUser.Handle("/create_transcode_pref_do", ctrl.H(ctrl.ServeCreateTranscodePrefDo))
|
||||
routUser.Handle("/delete_transcode_pref_do", ctrl.H(ctrl.ServeDeleteTranscodePrefDo))
|
||||
if ctrl.Podcasts.PodcastBasePath != "" {
|
||||
routUser.Handle("/add_podcast_do", ctrl.H(ctrl.ServePodcastAddDo))
|
||||
routUser.Handle("/delete_podcast_do", ctrl.H(ctrl.ServePodcastDeleteDo))
|
||||
}
|
||||
// ** begin admin routes (if session is valid, and is admin)
|
||||
routAdmin := routUser.NewRoute().Subrouter()
|
||||
routAdmin.Use(ctrl.WithAdminSession)
|
||||
@@ -198,8 +209,15 @@ func setupSubsonic(r *mux.Router, ctrl *ctrlsubsonic.Controller) {
|
||||
r.Handle("/search2{_:(?:\\.view)?}", ctrl.H(ctrl.ServeSearchTwo))
|
||||
r.Handle("/getGenres{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetGenres))
|
||||
r.Handle("/getArtistInfo{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetArtistInfo))
|
||||
// ** begin unimplemented
|
||||
// ** begin podcasts
|
||||
if ctrl.Podcasts.PodcastBasePath != "" {
|
||||
r.Handle("/getPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeGetPodcasts))
|
||||
r.Handle("/downloadPodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDownloadPodcastEpisode))
|
||||
r.Handle("/createPodcastChannel{_:(?:\\.view)?}", ctrl.H(ctrl.ServeCreatePodcastChannel))
|
||||
r.Handle("/refreshPodcasts{_:(?:\\.view)?}", ctrl.H(ctrl.ServeRefreshPodcasts))
|
||||
r.Handle("/deletePodcastChannel{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastChannel))
|
||||
r.Handle("/deletePodcastEpisode{_:(?:\\.view)?}", ctrl.H(ctrl.ServeDeletePodcastEpisode))
|
||||
}
|
||||
// middlewares should be run for not found handler
|
||||
// https://github.com/gorilla/mux/issues/416
|
||||
notFoundHandler := ctrl.H(ctrl.ServeNotFound)
|
||||
@@ -264,6 +282,31 @@ func (s *Server) StartJukebox() (FuncExecute, FuncInterrupt) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) StartPodcastRefresher(dur time.Duration) (FuncExecute, FuncInterrupt) {
|
||||
ticker := time.NewTicker(dur)
|
||||
done := make(chan struct{})
|
||||
waitFor := func() error {
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if err := s.podcast.RefreshPodcasts(0, true); err != nil {
|
||||
log.Printf("failed to refresh some feeds: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return func() error {
|
||||
log.Printf("starting job 'podcast refresher'\n")
|
||||
return waitFor()
|
||||
}, func(_ error) {
|
||||
// stop job
|
||||
ticker.Stop()
|
||||
done <- struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) StartSessionClean(dur time.Duration) (FuncExecute, FuncInterrupt) {
|
||||
ticker := time.NewTicker(dur)
|
||||
done := make(chan struct{})
|
||||
|
||||
Reference in New Issue
Block a user