Skip to content

🎧 Your Personal Streaming Service

Add Internet Radio support (#2063)

Kendall Garner8877b1695a44
diff --git a/db/migration/20230115103212_create_internet_radio.go b/db/migration/20230115103212_create_internet_radio.go
new file mode 100644
index 000000000..b8575fc5b
--- /dev/null
+++ b/db/migration/20230115103212_create_internet_radio.go
@@ -0,0 +1,30 @@
+package migrations
+
+import (
+ "database/sql"
+
+ "github.com/pressly/goose"
+)
+
+func init() {
+ goose.AddMigration(upCreateInternetRadio, downCreateInternetRadio)
+}
+
+func upCreateInternetRadio(tx *sql.Tx) error {
+ _, err := tx.Exec(`
+create table if not exists radio
+(
+ id varchar(255) not null primary key,
+ name varchar not null unique,
+ stream_url varchar not null,
+ home_page_url varchar default '' not null,
+ created_at datetime,
+ updated_at datetime
+);
+`)
+ return err
+}
+
+func downCreateInternetRadio(tx *sql.Tx) error {
+ return nil
+}
diff --git a/model/datastore.go b/model/datastore.go
index 19a08c05a..844c70d6f 100644
--- a/model/datastore.go
+++ b/model/datastore.go
@@ -29,6 +29,7 @@ type DataStore interface {
PlayQueue(ctx context.Context) PlayQueueRepository
Transcoding(ctx context.Context) TranscodingRepository
Player(ctx context.Context) PlayerRepository
+ Radio(ctx context.Context) RadioRepository
Share(ctx context.Context) ShareRepository
Property(ctx context.Context) PropertyRepository
User(ctx context.Context) UserRepository
diff --git a/model/radio.go b/model/radio.go
new file mode 100644
index 000000000..b07065777
--- /dev/null
+++ b/model/radio.go
@@ -0,0 +1,23 @@
+package model
+
+import "time"
+
+type Radio struct {
+ ID string `structs:"id" json:"id" orm:"pk;column(id)"`
+ StreamUrl string `structs:"stream_url" json:"streamUrl"`
+ Name string `structs:"name" json:"name"`
+ HomePageUrl string `structs:"home_page_url" json:"homePageUrl" orm:"column(home_page_url)"`
+ CreatedAt time.Time `structs:"created_at" json:"createdAt"`
+ UpdatedAt time.Time `structs:"updated_at" json:"updatedAt"`
+}
+
+type Radios []Radio
+
+type RadioRepository interface {
+ ResourceRepository
+ CountAll(options ...QueryOptions) (int64, error)
+ Delete(id string) error
+ Get(id string) (*Radio, error)
+ GetAll(options ...QueryOptions) (Radios, error)
+ Put(u *Radio) error
+}
diff --git a/persistence/persistence.go b/persistence/persistence.go
index c9c99fc60..277cd9659 100644
--- a/persistence/persistence.go
+++ b/persistence/persistence.go
@@ -52,6 +52,10 @@ func (s *SQLStore) Property(ctx context.Context) model.PropertyRepository {
return NewPropertyRepository(ctx, s.getOrmer())
}
+func (s *SQLStore) Radio(ctx context.Context) model.RadioRepository {
+ return NewRadioRepository(ctx, s.getOrmer())
+}
+
func (s *SQLStore) UserProps(ctx context.Context) model.UserPropsRepository {
return NewUserPropsRepository(ctx, s.getOrmer())
}
@@ -94,6 +98,8 @@ func (s *SQLStore) Resource(ctx context.Context, m interface{}) model.ResourceRe
return s.Genre(ctx).(model.ResourceRepository)
case model.Playlist:
return s.Playlist(ctx).(model.ResourceRepository)
+ case model.Radio:
+ return s.Radio(ctx).(model.ResourceRepository)
case model.Share:
return s.Share(ctx).(model.ResourceRepository)
}
diff --git a/persistence/persistence_suite_test.go b/persistence/persistence_suite_test.go
index b2d5016d9..212671217 100644
--- a/persistence/persistence_suite_test.go
+++ b/persistence/persistence_suite_test.go
@@ -69,6 +69,12 @@ var (
}
)
+var (
+ radioWithoutHomePage = model.Radio{ID: "1235", StreamUrl: "https://example.com:8000/1/stream.mp3", HomePageUrl: "", Name: "No Homepage"}
+ radioWithHomePage = model.Radio{ID: "5010", StreamUrl: "https://example.com/stream.mp3", Name: "Example Radio", HomePageUrl: "https://example.com"}
+ testRadios = model.Radios{radioWithoutHomePage, radioWithHomePage}
+)
+
var (
plsBest model.Playlist
plsCool model.Playlist
@@ -84,7 +90,7 @@ func P(path string) string {
var _ = BeforeSuite(func() {
o := orm.NewOrm()
ctx := log.NewContext(context.TODO())
- user := model.User{ID: "userid", UserName: "userid"}
+ user := model.User{ID: "userid", UserName: "userid", IsAdmin: true}
ctx = request.WithUser(ctx, user)
ur := NewUserRepository(ctx, o)
@@ -129,6 +135,15 @@ var _ = BeforeSuite(func() {
}
}
+ rar := NewRadioRepository(ctx, o)
+ for i := range testRadios {
+ r := testRadios[i]
+ err := rar.Put(&r)
+ if err != nil {
+ panic(err)
+ }
+ }
+
plsBest = model.Playlist{
Name: "Best",
Comment: "No Comments",
diff --git a/persistence/radio_repository.go b/persistence/radio_repository.go
new file mode 100644
index 000000000..17e4d2499
--- /dev/null
+++ b/persistence/radio_repository.go
@@ -0,0 +1,142 @@
+package persistence
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "time"
+
+ . "github.com/Masterminds/squirrel"
+ "github.com/beego/beego/v2/client/orm"
+ "github.com/deluan/rest"
+ "github.com/google/uuid"
+ "github.com/navidrome/navidrome/model"
+)
+
+type radioRepository struct {
+ sqlRepository
+ sqlRestful
+}
+
+func NewRadioRepository(ctx context.Context, o orm.QueryExecutor) model.RadioRepository {
+ r := &radioRepository{}
+ r.ctx = ctx
+ r.ormer = o
+ r.tableName = "radio"
+ r.filterMappings = map[string]filterFunc{
+ "name": containsFilter,
+ }
+ return r
+}
+
+func (r *radioRepository) isPermitted() bool {
+ user := loggedUser(r.ctx)
+ return user.IsAdmin
+}
+
+func (r *radioRepository) CountAll(options ...model.QueryOptions) (int64, error) {
+ sql := r.newSelect(options...)
+ return r.count(sql, options...)
+}
+
+func (r *radioRepository) Delete(id string) error {
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+
+ return r.delete(Eq{"id": id})
+}
+
+func (r *radioRepository) Get(id string) (*model.Radio, error) {
+ sel := r.newSelect().Where(Eq{"id": id}).Columns("*")
+ res := model.Radio{}
+ err := r.queryOne(sel, &res)
+ return &res, err
+}
+
+func (r *radioRepository) GetAll(options ...model.QueryOptions) (model.Radios, error) {
+ sel := r.newSelect(options...).Columns("*")
+ res := model.Radios{}
+ err := r.queryAll(sel, &res)
+ return res, err
+}
+
+func (r *radioRepository) Put(radio *model.Radio) error {
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+
+ var values map[string]interface{}
+
+ radio.UpdatedAt = time.Now()
+
+ if radio.ID == "" {
+ radio.CreatedAt = time.Now()
+ radio.ID = strings.ReplaceAll(uuid.NewString(), "-", "")
+ values, _ = toSqlArgs(*radio)
+ } else {
+ values, _ = toSqlArgs(*radio)
+ update := Update(r.tableName).Where(Eq{"id": radio.ID}).SetMap(values)
+ count, err := r.executeSQL(update)
+
+ if err != nil {
+ return err
+ } else if count > 0 {
+ return nil
+ }
+ }
+
+ values["created_at"] = time.Now()
+ insert := Insert(r.tableName).SetMap(values)
+ _, err := r.executeSQL(insert)
+ return err
+}
+
+func (r *radioRepository) Count(options ...rest.QueryOptions) (int64, error) {
+ return r.CountAll(r.parseRestOptions(options...))
+}
+
+func (r *radioRepository) EntityName() string {
+ return "radio"
+}
+
+func (r *radioRepository) NewInstance() interface{} {
+ return &model.Radio{}
+}
+
+func (r *radioRepository) Read(id string) (interface{}, error) {
+ return r.Get(id)
+}
+
+func (r *radioRepository) ReadAll(options ...rest.QueryOptions) (interface{}, error) {
+ return r.GetAll(r.parseRestOptions(options...))
+}
+
+func (r *radioRepository) Save(entity interface{}) (string, error) {
+ t := entity.(*model.Radio)
+ if !r.isPermitted() {
+ return "", rest.ErrPermissionDenied
+ }
+ err := r.Put(t)
+ if errors.Is(err, model.ErrNotFound) {
+ return "", rest.ErrNotFound
+ }
+ return t.ID, err
+}
+
+func (r *radioRepository) Update(id string, entity interface{}, cols ...string) error {
+ t := entity.(*model.Radio)
+ t.ID = id
+ if !r.isPermitted() {
+ return rest.ErrPermissionDenied
+ }
+ err := r.Put(t)
+ if errors.Is(err, model.ErrNotFound) {
+ return rest.ErrNotFound
+ }
+ return err
+}
+
+var _ model.RadioRepository = (*radioRepository)(nil)
+var _ rest.Repository = (*radioRepository)(nil)
+var _ rest.Persistable = (*radioRepository)(nil)
diff --git a/persistence/radio_repository_test.go b/persistence/radio_repository_test.go
new file mode 100644
index 000000000..b87b1fc15
--- /dev/null
+++ b/persistence/radio_repository_test.go
@@ -0,0 +1,176 @@
+package persistence
+
+import (
+ "context"
+
+ "github.com/beego/beego/v2/client/orm"
+ "github.com/deluan/rest"
+ "github.com/navidrome/navidrome/log"
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/model/request"
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var (
+ NewId string = "123-456-789"
+)
+
+var _ = Describe("RadioRepository", func() {
+ var repo model.RadioRepository
+
+ Describe("Admin User", func() {
+ BeforeEach(func() {
+ ctx := log.NewContext(context.TODO())
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true})
+ repo = NewRadioRepository(ctx, orm.NewOrm())
+ _ = repo.Put(&radioWithHomePage)
+ })
+
+ AfterEach(func() {
+ all, _ := repo.GetAll()
+
+ for _, radio := range all {
+ _ = repo.Delete(radio.ID)
+ }
+
+ for i := range testRadios {
+ r := testRadios[i]
+ err := repo.Put(&r)
+ if err != nil {
+ panic(err)
+ }
+ }
+ })
+
+ Describe("Count", func() {
+ It("returns the number of radios in the DB", func() {
+ Expect(repo.CountAll()).To(Equal(int64(2)))
+ })
+ })
+
+ Describe("Delete", func() {
+ It("deletes existing item", func() {
+ err := repo.Delete(radioWithHomePage.ID)
+
+ Expect(err).To(BeNil())
+
+ _, err = repo.Get(radioWithHomePage.ID)
+ Expect(err).To(MatchError(model.ErrNotFound))
+ })
+ })
+
+ Describe("Get", func() {
+ It("returns an existing item", func() {
+ res, err := repo.Get(radioWithHomePage.ID)
+
+ Expect(err).To(BeNil())
+ Expect(res.ID).To(Equal(radioWithHomePage.ID))
+ })
+
+ It("errors when missing", func() {
+ _, err := repo.Get("notanid")
+
+ Expect(err).To(MatchError(model.ErrNotFound))
+ })
+ })
+
+ Describe("GetAll", func() {
+ It("returns all items from the DB", func() {
+ all, err := repo.GetAll()
+ Expect(err).To(BeNil())
+ Expect(all[0].ID).To(Equal(radioWithoutHomePage.ID))
+ Expect(all[1].ID).To(Equal(radioWithHomePage.ID))
+ })
+ })
+
+ Describe("Put", func() {
+ It("successfully updates item", func() {
+ err := repo.Put(&model.Radio{
+ ID: radioWithHomePage.ID,
+ Name: "New Name",
+ StreamUrl: "https://example.com:4533/app",
+ })
+
+ Expect(err).To(BeNil())
+
+ item, err := repo.Get(radioWithHomePage.ID)
+ Expect(err).To(BeNil())
+
+ Expect(item.HomePageUrl).To(Equal(""))
+ })
+
+ It("successfully creates item", func() {
+ err := repo.Put(&model.Radio{
+ Name: "New radio",
+ StreamUrl: "https://example.com:4533/app",
+ })
+
+ Expect(err).To(BeNil())
+ Expect(repo.CountAll()).To(Equal(int64(3)))
+
+ all, err := repo.GetAll()
+ Expect(err).To(BeNil())
+ Expect(all[2].StreamUrl).To(Equal("https://example.com:4533/app"))
+ })
+ })
+ })
+
+ Describe("Regular User", func() {
+ BeforeEach(func() {
+ ctx := log.NewContext(context.TODO())
+ ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: false})
+ repo = NewRadioRepository(ctx, orm.NewOrm())
+ })
+
+ Describe("Count", func() {
+ It("returns the number of radios in the DB", func() {
+ Expect(repo.CountAll()).To(Equal(int64(2)))
+ })
+ })
+
+ Describe("Delete", func() {
+ It("fails to delete items", func() {
+ err := repo.Delete(radioWithHomePage.ID)
+
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+
+ Describe("Get", func() {
+ It("returns an existing item", func() {
+ res, err := repo.Get(radioWithHomePage.ID)
+
+ Expect(err).To((BeNil()))
+ Expect(res.ID).To(Equal(radioWithHomePage.ID))
+ })
+
+ It("errors when missing", func() {
+ _, err := repo.Get("notanid")
+
+ Expect(err).To(MatchError(model.ErrNotFound))
+ })
+ })
+
+ Describe("GetAll", func() {
+ It("returns all items from the DB", func() {
+ all, err := repo.GetAll()
+ Expect(err).To(BeNil())
+ Expect(all[0].ID).To(Equal(radioWithoutHomePage.ID))
+ Expect(all[1].ID).To(Equal(radioWithHomePage.ID))
+ })
+ })
+
+ Describe("Put", func() {
+ It("fails to update item", func() {
+ err := repo.Put(&model.Radio{
+ ID: radioWithHomePage.ID,
+ Name: "New Name",
+ StreamUrl: "https://example.com:4533/app",
+ })
+
+ Expect(err).To(Equal(rest.ErrPermissionDenied))
+ })
+ })
+ })
+})
diff --git a/server/nativeapi/native_api.go b/server/nativeapi/native_api.go
index fb53c4e4d..499f617b3 100644
--- a/server/nativeapi/native_api.go
+++ b/server/nativeapi/native_api.go
@@ -44,6 +44,7 @@ func (n *Router) routes() http.Handler {
n.R(r, "/player", model.Player{}, true)
n.R(r, "/playlist", model.Playlist{}, true)
n.R(r, "/transcoding", model.Transcoding{}, conf.Server.EnableTranscodingConfig)
+ n.R(r, "/radio", model.Radio{}, true)
n.RX(r, "/share", n.share.NewRepository, true)
n.addPlaylistTrackRoute(r)
diff --git a/server/subsonic/api.go b/server/subsonic/api.go
index b2c59316c..d16dad4af 100644
--- a/server/subsonic/api.go
+++ b/server/subsonic/api.go
@@ -153,6 +153,12 @@ func (api *Router) routes() http.Handler {
hr(r, "stream", api.Stream)
hr(r, "download", api.Download)
})
+ r.Group(func(r chi.Router) {
+ h(r, "createInternetRadioStation", api.CreateInternetRadio)
+ h(r, "deleteInternetRadioStation", api.DeleteInternetRadio)
+ h(r, "getInternetRadioStations", api.GetInternetRadios)
+ h(r, "updateInternetRadioStation", api.UpdateInternetRadio)
+ })
// Not Implemented (yet?)
h501(r, "jukeboxControl")
@@ -160,8 +166,6 @@ func (api *Router) routes() http.Handler {
h501(r, "getShares", "createShare", "updateShare", "deleteShare")
h501(r, "getPodcasts", "getNewestPodcasts", "refreshPodcasts", "createPodcastChannel", "deletePodcastChannel",
"deletePodcastEpisode", "downloadPodcastEpisode")
- h501(r, "getInternetRadioStations", "createInternetRadioStation", "updateInternetRadioStation",
- "deleteInternetRadioStation")
h501(r, "createUser", "updateUser", "deleteUser", "changePassword")
// Deprecated/Won't implement/Out of scope endpoints
diff --git a/server/subsonic/radio.go b/server/subsonic/radio.go
new file mode 100644
index 000000000..c2953212e
--- /dev/null
+++ b/server/subsonic/radio.go
@@ -0,0 +1,108 @@
+package subsonic
+
+import (
+ "net/http"
+
+ "github.com/navidrome/navidrome/model"
+ "github.com/navidrome/navidrome/server/subsonic/responses"
+ "github.com/navidrome/navidrome/utils"
+)
+
+func (api *Router) CreateInternetRadio(r *http.Request) (*responses.Subsonic, error) {
+ streamUrl, err := requiredParamString(r, "streamUrl")
+ if err != nil {
+ return nil, err
+ }
+
+ name, err := requiredParamString(r, "name")
+ if err != nil {
+ return nil, err
+ }
+
+ homepageUrl := utils.ParamString(r, "homepageUrl")
+ ctx := r.Context()
+
+ radio := &model.Radio{
+ StreamUrl: streamUrl,
+ HomePageUrl: homepageUrl,
+ Name: name,
+ }
+
+ err = api.ds.Radio(ctx).Put(radio)
+ if err != nil {
+ return nil, err
+ }
+ return newResponse(), nil
+}
+
+func (api *Router) DeleteInternetRadio(r *http.Request) (*responses.Subsonic, error) {
+ id, err := requiredParamString(r, "id")
+
+ if err != nil {
+ return nil, err
+ }
+
+ err = api.ds.Radio(r.Context()).Delete(id)
+ if err != nil {
+ return nil, err
+ }
+ return newResponse(), nil
+}
+
+func (api *Router) GetInternetRadios(r *http.Request) (*responses.Subsonic, error) {
+ ctx := r.Context()
+ radios, err := api.ds.Radio(ctx).GetAll()
+ if err != nil {
+ return nil, err
+ }
+
+ res := make([]responses.Radio, len(radios))
+ for i, g := range radios {
+ res[i] = responses.Radio{
+ ID: g.ID,
+ Name: g.Name,
+ StreamUrl: g.StreamUrl,
+ HomepageUrl: g.HomePageUrl,
+ }
+ }
+
+ response := newResponse()
+ response.InternetRadioStations = &responses.InternetRadioStations{
+ Radios: res,
+ }
+
+ return response, nil
+}
+
+func (api *Router) UpdateInternetRadio(r *http.Request) (*responses.Subsonic, error) {
+ id, err := requiredParamString(r, "id")
+ if err != nil {
+ return nil, err
+ }
+
+ streamUrl, err := requiredParamString(r, "streamUrl")
+ if err != nil {
+ return nil, err
+ }
+
+ name, err := requiredParamString(r, "name")
+ if err != nil {
+ return nil, err
+ }
+
+ homepageUrl := utils.ParamString(r, "homepageUrl")
+ ctx := r.Context()
+
+ radio := &model.Radio{
+ ID: id,
+ StreamUrl: streamUrl,
+ HomePageUrl: homepageUrl,
+ Name: name,
+ }
+
+ err = api.ds.Radio(ctx).Put(radio)
+ if err != nil {
+ return nil, err
+ }
+ return newResponse(), nil
+}
diff --git a/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .JSON b/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .JSON
new file mode 100644
index 000000000..be2147775
--- /dev/null
+++ b/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .JSON
@@ -0,0 +1 @@
+{"status":"ok","version":"1.8.0","type":"navidrome","serverVersion":"v0.0.0","internetRadioStations":{"internetRadioStation":[{"id":"12345678","streamUrl":"https://example.com/stream","name":"Example Stream","homePageUrl":"https://example.com"}]}}
diff --git a/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .XML b/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .XML
new file mode 100644
index 000000000..e86f63223
--- /dev/null
+++ b/server/subsonic/responses/.snapshots/Responses InternetRadioStations with data should match .XML
@@ -0,0 +1 @@
+<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.8.0" type="navidrome" serverVersion="v0.0.0"><internetRadioStations><internetRadioStation><id>12345678</id><streamUrl>https://example.com/stream</streamUrl><name>Example Stream</name><homePageUrl>https://example.com</homePageUrl></internetRadioStation></internetRadioStations></subsonic-response>
diff --git a/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .JSON b/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .JSON
new file mode 100644
index 000000000..d08b59080
--- /dev/null
+++ b/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .JSON
@@ -0,0 +1 @@
+{"status":"ok","version":"1.8.0","type":"navidrome","serverVersion":"v0.0.0","internetRadioStations":{}}
diff --git a/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .XML b/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .XML
new file mode 100644
index 000000000..e2ed13e4b
--- /dev/null
+++ b/server/subsonic/responses/.snapshots/Responses InternetRadioStations without data should match .XML
@@ -0,0 +1 @@
+<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.8.0" type="navidrome" serverVersion="v0.0.0"><internetRadioStations></internetRadioStations></subsonic-response>
diff --git a/server/subsonic/responses/responses.go b/server/subsonic/responses/responses.go
index 798751233..0e1c4d570 100644
--- a/server/subsonic/responses/responses.go
+++ b/server/subsonic/responses/responses.go
@@ -47,6 +47,8 @@ type Subsonic struct {
Bookmarks *Bookmarks `xml:"bookmarks,omitempty" json:"bookmarks,omitempty"`
ScanStatus *ScanStatus `xml:"scanStatus,omitempty" json:"scanStatus,omitempty"`
Lyrics *Lyrics `xml:"lyrics,omitempty" json:"lyrics,omitempty"`
+
+ InternetRadioStations *InternetRadioStations `xml:"internetRadioStations,omitempty" json:"internetRadioStations,omitempty"`
}
type JsonWrapper struct {
@@ -359,3 +361,14 @@ type Lyrics struct {
Title string `xml:"title,omitempty,attr" json:"title,omitempty"`
Value string `xml:",chardata" json:"value"`
}
+
+type InternetRadioStations struct {
+ Radios []Radio `xml:"internetRadioStation" json:"internetRadioStation,omitempty"`
+}
+
+type Radio struct {
+ ID string `xml:"id" json:"id"`
+ StreamUrl string `xml:"streamUrl" json:"streamUrl"`
+ Name string `xml:"name" json:"name"`
+ HomepageUrl string `xml:"homePageUrl" json:"homePageUrl"`
+}
diff --git a/server/subsonic/responses/responses_test.go b/server/subsonic/responses/responses_test.go
index 6c2752490..c133e5d7a 100644
--- a/server/subsonic/responses/responses_test.go
+++ b/server/subsonic/responses/responses_test.go
@@ -594,4 +594,39 @@ var _ = Describe("Responses", func() {
})
})
+
+ Describe("InternetRadioStations", func() {
+ BeforeEach(func() {
+ response.InternetRadioStations = &InternetRadioStations{}
+ })
+
+ Describe("without data", func() {
+ It("should match .XML", func() {
+ Expect(xml.Marshal(response)).To(MatchSnapshot())
+ })
+ It("should match .JSON", func() {
+ Expect(json.Marshal(response)).To(MatchSnapshot())
+ })
+ })
+
+ Describe("with data", func() {
+ BeforeEach(func() {
+ radio := make([]Radio, 1)
+ radio[0] = Radio{
+ ID: "12345678",
+ StreamUrl: "https://example.com/stream",
+ Name: "Example Stream",
+ HomepageUrl: "https://example.com",
+ }
+ response.InternetRadioStations.Radios = radio
+ })
+
+ It("should match .XML", func() {
+ Expect(xml.Marshal(response)).To(MatchSnapshot())
+ })
+ It("should match .JSON", func() {
+ Expect(json.Marshal(response)).To(MatchSnapshot())
+ })
+ })
+ })
})
diff --git a/tests/mock_persistence.go b/tests/mock_persistence.go
index b68f559ad..8df0547bb 100644
--- a/tests/mock_persistence.go
+++ b/tests/mock_persistence.go
@@ -19,6 +19,7 @@ type MockDataStore struct {
MockedTranscoding model.TranscodingRepository
MockedUserProps model.UserPropsRepository
MockedScrobbleBuffer model.ScrobbleBufferRepository
+ MockedRadioBuffer model.RadioRepository
}
func (db *MockDataStore) Album(context.Context) model.AlbumRepository {
@@ -113,6 +114,13 @@ func (db *MockDataStore) ScrobbleBuffer(ctx context.Context) model.ScrobbleBuffe
return db.MockedScrobbleBuffer
}
+func (db *MockDataStore) Radio(ctx context.Context) model.RadioRepository {
+ if db.MockedRadioBuffer == nil {
+ db.MockedRadioBuffer = CreateMockedRadioRepo()
+ }
+ return db.MockedRadioBuffer
+}
+
func (db *MockDataStore) WithTx(block func(db model.DataStore) error) error {
return block(db)
}
diff --git a/tests/mock_radio_repository.go b/tests/mock_radio_repository.go
new file mode 100644
index 000000000..ec5af68fc
--- /dev/null
+++ b/tests/mock_radio_repository.go
@@ -0,0 +1,85 @@
+package tests
+
+import (
+ "errors"
+
+ "github.com/google/uuid"
+ "github.com/navidrome/navidrome/model"
+)
+
+type MockedRadioRepo struct {
+ model.RadioRepository
+ data map[string]*model.Radio
+ all model.Radios
+ err bool
+ Options model.QueryOptions
+}
+
+func CreateMockedRadioRepo() *MockedRadioRepo {
+ return &MockedRadioRepo{}
+}
+
+func (m *MockedRadioRepo) SetError(err bool) {
+ m.err = err
+}
+
+func (m *MockedRadioRepo) CountAll(options ...model.QueryOptions) (int64, error) {
+ if m.err {
+ return 0, errors.New("error")
+ }
+ return int64(len(m.data)), nil
+}
+
+func (m *MockedRadioRepo) Delete(id string) error {
+ if m.err {
+ return errors.New("Error!")
+ }
+
+ _, found := m.data[id]
+
+ if !found {
+ return errors.New("not found")
+ }
+
+ delete(m.data, id)
+ return nil
+}
+
+func (m *MockedRadioRepo) Exists(id string) (bool, error) {
+ if m.err {
+ return false, errors.New("Error!")
+ }
+ _, found := m.data[id]
+ return found, nil
+}
+
+func (m *MockedRadioRepo) Get(id string) (*model.Radio, error) {
+ if m.err {
+ return nil, errors.New("Error!")
+ }
+ if d, ok := m.data[id]; ok {
+ return d, nil
+ }
+ return nil, model.ErrNotFound
+}
+
+func (m *MockedRadioRepo) GetAll(qo ...model.QueryOptions) (model.Radios, error) {
+ if len(qo) > 0 {
+ m.Options = qo[0]
+ }
+ if m.err {
+ return nil, errors.New("Error!")
+ }
+ return m.all, nil
+}
+
+func (m *MockedRadioRepo) Put(radio *model.Radio) error {
+ if m.err {
+ return errors.New("error")
+ }
+ if radio.ID == "" {
+ radio.ID = uuid.NewString()
+ }
+ m.data[radio.ID] = radio
+ return nil
+}
diff --git a/ui/public/internet-radio-icon.svg b/ui/public/internet-radio-icon.svg
new file mode 100644
index 000000000..d658eab93
--- /dev/null
+++ b/ui/public/internet-radio-icon.svg
@@ -0,0 +1 @@
+<svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><text x="729.64" y="231.36"><tspan x="729.64" y="231.36"/></text><text transform="scale(4.0128 .2492)" x="378.91" y="579.26"/><text x="1310.91" y="151.36"><tspan x="1310.91" y="151.36"/></text><text transform="scale(4.0128 .2492)" x="523.76" y="258.22"/><text x="239.33" y="-29.9"><tspan x="239.33" y="-29.9"/></text><text transform="scale(4.0128 .2492)" x="256.72" y="-469.13"/><text x="1337.38" y="-246.37"><tspan x="1337.38" y="-246.37"/></text><text transform="scale(4.0128 .2492)" x="530.36" y="-1337.8"/><text x="1918.65" y="-326.37"><tspan x="1918.65" y="-326.37"/></text><text transform="scale(4.0128 .2492)" x="675.21" y="-1658.83"/><text x="1529.53" y="-798.77"><tspan x="1529.53" y="-798.77"/></text><text transform="scale(4.0128 .2492)" x="578.24" y="-3554.48"/><text x="2110.79" y="-878.78"><tspan x="2110.79" y="-878.78"/></text><text transform="scale(4.0128 .2492)" x="723.09" y="-3875.52"/><text x="277.99" y="535.94"><tspan x="277.99" y="535.94"/></text><g fill-rule="evenodd"><path d="m471.95 253.05c0 120.9-98.01 218.91-218.91 218.91s-218.91-98.01-218.91-218.91 98.01-218.91 218.91-218.91 218.91 98.01 218.91 218.91" fill="#703f92"/><path d="m256 1c-140.83 0-255 114.17-255 255s114.17 255 255 255 255-114.17 255-255-114.17-255-255-255m8.827 44.931c120.9 0 218.9 98 218.9 218.9s-98 218.9-218.9 218.9-218.93-98-218.93-218.9 98.03-218.9 218.93-218.9" fill-opacity=".067"/><g fill-opacity=".129"><path d="m256 4.43c-138.94 0-251.57 112.63-251.57 251.57s112.63 251.57 251.57 251.57 251.57-112.63 251.57-251.57-112.63-251.57-251.57-251.57m5.885 38.556c120.9 0 218.9 98 218.9 218.9s-98 218.9-218.9 218.9-218.93-98-218.93-218.9 98.03-218.9 218.93-218.9"/><path d="m256 8.36c-136.77 0-247.64 110.87-247.64 247.64s110.87 247.64 247.64 247.64 247.64-110.87 247.64-247.64-110.87-247.64-247.64-247.64m2.942 31.691c120.9 0 218.9 98 218.9 218.9s-98 218.9-218.9 218.9-218.93-98-218.93-218.9 98.03-218.9 218.93-218.9"/></g><path d="m253.04 7.86c-135.42 0-245.19 109.78-245.19 245.19 0 135.42 109.78 245.19 245.19 245.19 135.42 0 245.19-109.78 245.19-245.19 0-135.42-109.78-245.19-245.19-245.19m0 26.297c120.9 0 218.9 98 218.9 218.9s-98 218.9-218.9 218.9-218.93-98-218.93-218.9 98.03-218.9 218.93-218.9z" fill="#fff" stroke="#000" stroke-opacity=".31" stroke-width="4.904"/></g><text x="729.64" y="231.36"><tspan x="729.64" y="231.36"/></text><text transform="scale(4.0128 .2492)" x="378.91" y="579.26"/><text x="1310.91" y="151.36"><tspan x="1310.91" y="151.36"/></text><text transform="scale(4.0128 .2492)" x="523.76" y="258.22"/><text x="239.33" y="-29.9"><tspan x="239.33" y="-29.9"/></text><text transform="scale(4.0128 .2492)" x="256.72" y="-469.13"/><text x="1337.38" y="-246.37"><tspan x="1337.38" y="-246.37"/></text><text transform="scale(4.0128 .2492)" x="530.36" y="-1337.79"/><text x="1918.65" y="-326.37"><tspan x="1918.65" y="-326.37"/></text><text transform="scale(4.0128 .2492)" x="675.21" y="-1658.82"/><text x="1529.53" y="-798.77"><tspan x="1529.53" y="-798.77"/></text><text transform="scale(4.0128 .2492)" x="578.24" y="-3554.46"/><text x="2110.79" y="-878.78"><tspan x="2110.79" y="-878.78"/></text><text transform="scale(4.0128 .2492)" x="723.09" y="-3875.5"/><text x="277.99" y="535.94"><tspan x="277.99" y="535.94"/></text><path d="m165.95 145.7c-6.734-.021-9.536 1.52-17.08 9.395-20.802 21.71-34.44 50.16-38.811 80.939-1.469 10.342-1.469 29.367 0 39.709 2.302 16.215 6.91 31.03 14.217 45.707.425.853.861 1.705 1.305 2.555.288.552.587 1.101.883 1.65.175.324.346.649.523.973.217.395.441.788.662 1.182.271.483.54.967.816 1.447.164.285.332.567.498.852.348.597.696 1.193 1.053 1.785.157.26.316.518.475.777.335.549.671 1.097 1.012 1.641.238.38.481.755.723 1.133.296.464.592.927.893 1.387.232.355.468.706.703 1.059.304.456.608.912.916 1.363.254.372.511.74.768 1.109.301.432.602.863.906 1.291.265.372.53.741.797 1.109.305.42.61.839.918 1.254.258.348.519.693.779 1.037.315.417.63.831.947 1.242.274.354.549.705.824 1.055.322.409.646.814.971 1.217.255.316.511.631.768.943.341.415.682.825 1.025 1.232.265.314.529.626.795.936.315.366.631.727.947 1.086.308.35.616.699.926 1.043.281.312.564.617.846.924.324.352.648.703.973 1.047.321.34.643.672.965 1 .266.275.532.551.799.82.105.106.209.217.314.322l113.77 113.77c112.48-5.432 202.67-95.75 207.92-208.27l-110.81-110.81c-.178-.178-.335-.315-.508-.484-.322-.315-.644-.623-.951-.91-.37-.345-.732-.671-1.084-.977-.373-.325-.752-.655-1.109-.938-.091-.072-.185-.15-.275-.219-.099-.076-.197-.146-.295-.219-.2-.149-.4-.295-.598-.432-.127-.088-.253-.169-.379-.252-.152-.099-.304-.199-.455-.291-.145-.089-.291-.172-.436-.254-.154-.088-.309-.173-.463-.254-.132-.069-.266-.135-.398-.199-.149-.072-.299-.143-.449-.209-.143-.063-.287-.124-.432-.182-.157-.062-.315-.122-.473-.178-.131-.046-.262-.093-.395-.135-.18-.058-.363-.11-.547-.16-.115-.031-.23-.063-.346-.092-.193-.047-.389-.089-.586-.129-.126-.025-.251-.052-.379-.074-.18-.032-.365-.058-.549-.084-.145-.02-.288-.043-.436-.061-.212-.025-.433-.042-.652-.061-.116-.01-.229-.023-.348-.031-.714-.048-1.465-.067-2.271-.061-5.472.044-9.03 1.486-12.691 5.143-3.809 3.806-5.15 7.186-5.141 12.947.01 6.074 1.315 8.877 7.03 15.05 14.8 15.986 24.458 34.04 28.721 53.52.135.617.259 1.238.383 1.857l-43.543-43.543-.029-.029c-6.657-6.653-9.667-8.172-16.16-8.158-4.183.009-4.945.199-8.344 2.061-6.655 3.646-10.232 10.127-9.643 17.467.389 4.849 2.465 8.624 7.684 13.971 7.783 7.975 12.999 17.212 15.607 27.643.687 2.745.971 6.317.971 12.223 0 1.091-.021 2.026-.041 2.967l-28.945-28.945c-.073-.073-.153-.14-.227-.213-.39-.383-.788-.758-1.195-1.125-.101-.091-.201-.183-.303-.273-.496-.437-1-.862-1.525-1.273-.101-.08-.205-.157-.307-.236-.436-.338-.881-.665-1.334-.984-.135-.095-.268-.192-.404-.285-.541-.371-1.093-.73-1.656-1.074-.111-.068-.224-.131-.336-.197-.485-.289-.977-.568-1.477-.836-.152-.082-.304-.163-.457-.242-.599-.311-1.206-.612-1.826-.893-.06-.027-.122-.051-.182-.078-.567-.253-1.143-.49-1.727-.717-.168-.065-.335-.13-.504-.193-.651-.243-1.308-.474-1.979-.684-3.4-1.061-8.609-1.461-13.367-1.195-.415.023-.807.072-1.213.105l-31.652-31.652c-3.084-3.084-5.797-4.549-9.639-5.061l-31.986-31.986c-.14-.14-.294-.268-.439-.404-.171-.16-.34-.32-.518-.475-.247-.215-.506-.419-.766-.623-.18-.141-.355-.287-.541-.422-.322-.234-.658-.454-.998-.67-.136-.086-.266-.178-.404-.262-.495-.298-1-.58-1.535-.838-2.303-1.12-3.797-1.403-7.482-1.414" opacity=".25"/><path d="m160.77 365.62c-3.7-1.223-4.937-2.061-9.42-6.376-10.06-9.679-19.959-23.501-27.07-37.79-7.307-14.677-11.916-29.493-14.218-45.708-1.469-10.342-1.469-29.366 0-39.708 4.371-30.78 18.01-59.23 38.812-80.94 7.544-7.875 10.346-9.416 17.08-9.395 3.685.011 5.178.294 7.481 1.414 8.807 4.285 12.837 14.254 9.436 23.343-.881 2.353-2.412 4.514-5.625 7.934-9.376 9.982-15.321 18.52-20.792 29.856-14.557 30.16-14.557 65.12 0 95.28 5.471 11.337 11.417 19.874 20.792 29.856 3.213 3.421 4.744 5.581 5.625 7.934 3.308 8.84-.579 19.02-8.797 23.04-3.721 1.821-9.843 2.399-13.299 1.256m181.27.229c-5.166-1.25-9.941-5.152-12.372-10.111-1.161-2.368-1.411-3.743-1.411-7.769 0-6.212 1.225-8.877 6.849-14.906 20.646-22.13 31.391-48.545 31.391-77.17 0-28.538-10.639-54.779-31.23-77.02-5.714-6.174-7.02-8.976-7.03-15.05-.009-5.761 1.332-9.141 5.141-12.947 3.659-3.657 7.219-5.1 12.691-5.144 6.574-.053 9.655 1.507 16.01 8.105 10.833 11.245 18.97 22.911 26.03 37.32 7.208 14.709 11.08 27 13.592 43.16 1.663 10.689 1.803 31.01.286 41.43-3.676 25.26-13.551 49.13-28.497 68.889-5.218 6.898-13.957 16.414-16.939 18.446-4.143 2.822-9.815 3.904-14.513 2.767m-139.94-37.09c-3.32-1.086-6.05-2.862-8.411-5.48-1.103-1.221-2.269-2.316-2.591-2.433s-2.029-1.835-3.793-3.818c-18.647-20.961-26.697-49.37-21.891-77.25 1.972-11.442 7.4-24.962 13.937-34.716 3.456-5.158 10.914-14.199 11.712-14.199.258 0 1.538-1.16 2.845-2.578s3.837-3.295 5.623-4.172c2.77-1.36 3.923-1.587 7.85-1.543 5.726.063 8.992 1.405 12.878 5.291 5.04 5.04 6.602 12.581 4.03 19.464-.948 2.533-2.317 4.384-6.083 8.222-8.297 8.456-13.461 17.462-16.13 28.12-1.341 5.361-1.341 19.08 0 24.443 2.667 10.664 7.829 19.673 16.13 28.15 3.762 3.841 5.154 5.722 6.09 8.222 4.399 11.757-3.574 24.2-15.93 24.854-2.276.121-4.849-.117-6.265-.581m98.51.292c-5.29-1.384-9.95-5.205-12.372-10.145-1.159-2.363-1.412-3.751-1.417-7.769-.006-4.249.206-5.296 1.606-7.967.886-1.691 3.56-5.058 5.942-7.481 7.721-7.855 12.966-17.14 15.575-27.576.686-2.744.97-6.315.97-12.222 0-5.906-.283-9.477-.97-12.222-2.608-10.431-7.825-19.669-15.608-27.644-5.219-5.347-7.295-9.122-7.684-13.971-.589-7.34 2.988-13.82 9.643-17.466 3.399-1.862 4.161-2.051 8.344-2.06 6.493-.014 9.503 1.505 16.16 8.158 36.34 36.31 36.32 94.38-.048 130.45-6.03 5.978-9.505 7.888-14.882 8.18-1.943.105-4.31-.012-5.259-.26m-51.22-36.876c-3.914-.843-8.975-2.805-12.303-4.77-4.097-2.419-10.183-8.515-12.621-12.643-12.154-20.579-1.877-46.994 21.07-54.16 5.44-1.698 15.515-1.698 20.955 0 16.388 5.115 27.12 20.434 26.17 37.35-.519 9.264-4.123 17.224-10.789 23.829-7.02 6.961-14.696 10.314-24.424 10.672-3.165.117-6.793-.012-8.06-.285" fill="#fff"/></svg>
\ No newline at end of file
diff --git a/ui/src/App.js b/ui/src/App.js
index 9281964f9..bcf5894bc 100644
--- a/ui/src/App.js
+++ b/ui/src/App.js
@@ -14,6 +14,7 @@ import song from './song'
import album from './album'
import artist from './artist'
import playlist from './playlist'
+import radio from './radio'
import { Player } from './audioplayer'
import customRoutes from './routes'
import {
@@ -99,6 +100,10 @@ const Admin = (props) => {
<Resource name="album" {...album} options={{ subMenu: 'albumList' }} />,
<Resource name="artist" {...artist} />,
<Resource name="song" {...song} />,
+ <Resource
+ name="radio"
+ {...(permissions === 'admin' ? radio.admin : radio.all)}
+ />,
<Resource
name="playlist"
{...playlist}
diff --git a/ui/src/audioplayer/AudioTitle.js b/ui/src/audioplayer/AudioTitle.js
index bf509c668..b8ba77a8d 100644
--- a/ui/src/audioplayer/AudioTitle.js
+++ b/ui/src/audioplayer/AudioTitle.js
@@ -18,7 +18,14 @@ const AudioTitle = React.memo(({ audioInfo, isMobile }) => {
const qi = { suffix: song.suffix, bitRate: song.bitRate }
return (
- <Link to={`/album/${song.albumId}/show`} className={className}>
+ <Link
+ to={
+ audioInfo.isRadio
+ ? `/radio/${audioInfo.trackId}/show`
+ : `/album/${song.albumId}/show`
+ }
+ className={className}
+ >
<span>
<span className={clsx(classes.songTitle, 'songTitle')}>
{song.title}
diff --git a/ui/src/audioplayer/Player.js b/ui/src/audioplayer/Player.js
index 4df031ae5..7f4314516 100644
--- a/ui/src/audioplayer/Player.js
+++ b/ui/src/audioplayer/Player.js
@@ -41,7 +41,9 @@ const Player = () => {
)
const { authenticated } = useAuthState()
const visible = authenticated && playerState.queue.length > 0
+ const isRadio = playerState.current?.isRadio || false
const classes = useStyle({
+ isRadio,
visible,
enableCoverAnimation: config.enableCoverAnimation,
})
@@ -88,8 +90,11 @@ const Player = () => {
playIndex: playerState.playIndex,
autoPlay: playerState.clear || playerState.playIndex === 0,
clearPriorAudioLists: playerState.clear,
- extendsContent: <PlayerToolbar id={current.trackId} />,
+ extendsContent: (
+ <PlayerToolbar id={current.trackId} isRadio={current.isRadio} />
+ ),
defaultVolume: isMobilePlayer ? 1 : playerState.volume,
+ showMediaSession: !current.isRadio,
}
}, [playerState, defaultOptions, isMobilePlayer])
@@ -116,6 +121,10 @@ const Player = () => {
return
}
+ if (info.isRadio) {
+ return
+ }
+
if (!preloaded) {
const next = nextSong()
if (next != null) {
@@ -149,7 +158,9 @@ const Player = () => {
if (info.duration) {
const song = info.song
document.title = `${song.title} - ${song.artist} - Navidrome`
- subsonic.nowPlaying(info.trackId)
+ if (!info.isRadio) {
+ subsonic.nowPlaying(info.trackId)
+ }
setPreload(false)
if (config.gaTrackingId) {
ReactGA.event({
diff --git a/ui/src/audioplayer/PlayerToolbar.js b/ui/src/audioplayer/PlayerToolbar.js
index 9e79d056f..c44a93097 100644
--- a/ui/src/audioplayer/PlayerToolbar.js
+++ b/ui/src/audioplayer/PlayerToolbar.js
@@ -29,6 +29,7 @@ const Toolbar = ({ id }) => {
)
}
-const PlayerToolbar = ({ id }) => (id ? <Toolbar id={id} /> : <Placeholder />)
+const PlayerToolbar = ({ id, isRadio }) =>
+ id && !isRadio ? <Toolbar id={id} /> : <Placeholder />
export default PlayerToolbar
diff --git a/ui/src/audioplayer/styles.js b/ui/src/audioplayer/styles.js
index 955bcf1e1..0573ac440 100644
--- a/ui/src/audioplayer/styles.js
+++ b/ui/src/audioplayer/styles.js
@@ -78,6 +78,17 @@ const useStyle = makeStyles(
{
display: 'none',
},
+ '& .music-player-panel .panel-content .progress-bar-content section.audio-main':
+ {
+ display: (props) => {
+ return props.isRadio ? 'none' : 'inline-flex'
+ },
+ },
+ '& .react-jinke-music-player-mobile-progress': {
+ display: (props) => {
+ return props.isRadio ? 'none' : 'flex'
+ },
+ },
},
}),
{ name: 'NDAudioPlayer' }
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 0eb574188..dd4a4942e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -160,6 +160,24 @@
"duplicate_song": "Add duplicated songs",
"song_exist": "There are duplicates being added to the playlist. Would you like to add the duplicates or skip them?"
}
+ },
+ "radio": {
+ "name": "Radio |||| Radios",
+ "fields": {
+ "name": "Name",
+ "streamUrl": "Stream URL",
+ "homePageUrl": "Home Page URL",
+ "updatedAt": "Updated at",
+ "createdAt": "Created at"
+ },
+ "notifications": {
+ "created": "Radio created",
+ "updated": "Radio updated",
+ "deleted": "Radio deleted"
+ },
+ "actions": {
+ "playNow": "Play Now"
+ }
}
},
"ra": {
@@ -188,7 +206,8 @@
"email": "Must be a valid email",
"oneOf": "Must be one of: %{options}",
"regex": "Must match a specific format (regexp): %{pattern}",
- "unique": "Must be unique"
+ "unique": "Must be unique",
+ "url": "Must be a valid URL"
},
"action": {
"add_filter": "Add filter",
@@ -310,6 +329,8 @@
"noPlaylistsAvailable": "None available",
"delete_user_title": "Delete user '%{name}'",
"delete_user_content": "Are you sure you want to delete this user and all their data (including playlists and preferences)?",
+ "delete_radio_title": "Delete radio '%{name}'",
+ "delete_radio_content": "Are you sure you want to remove this radio?",
"notifications_blocked": "You have blocked Notifications for this site in your browser's settings",
"notifications_not_available": "This browser does not support desktop notifications or you are not accessing Navidrome over https",
"lastfmLinkSuccess": "Last.fm successfully linked and scrobbling enabled",
@@ -402,4 +423,4 @@
"toggle_love": "Add this track to favourites"
}
}
-}
\ No newline at end of file
+}
diff --git a/ui/src/radio/DeleteRadioButton.js b/ui/src/radio/DeleteRadioButton.js
new file mode 100644
index 000000000..75257a584
--- /dev/null
+++ b/ui/src/radio/DeleteRadioButton.js
@@ -0,0 +1,76 @@
+import { fade, makeStyles } from '@material-ui/core'
+import DeleteIcon from '@material-ui/icons/Delete'
+import clsx from 'clsx'
+import React from 'react'
+import {
+ Button,
+ Confirm,
+ useDeleteWithConfirmController,
+ useNotify,
+ useRedirect,
+} from 'react-admin'
+
+const useStyles = makeStyles(
+ (theme) => ({
+ deleteButton: {
+ color: theme.palette.error.main,
+ '&:hover': {
+ backgroundColor: fade(theme.palette.error.main, 0.12),
+ // Reset on mouse devices
+ '@media (hover: none)': {
+ backgroundColor: 'transparent',
+ },
+ },
+ },
+ }),
+ { name: 'RaDeleteWithConfirmButton' }
+)
+
+const DeleteRadioButton = (props) => {
+ const { resource, record, basePath, className, onClick, ...rest } = props
+
+ const notify = useNotify()
+ const redirect = useRedirect()
+
+ const onSuccess = () => {
+ notify('resources.radio.notifications.deleted')
+ redirect('/radio')
+ }
+
+ const { open, loading, handleDialogOpen, handleDialogClose, handleDelete } =
+ useDeleteWithConfirmController({
+ resource,
+ record,
+ basePath,
+ onClick,
+ onSuccess,
+ })
+
+ const classes = useStyles(props)
+ return (
+ <>
+ <Button
+ onClick={handleDialogOpen}
+ label="ra.action.delete"
+ key="button"
+ className={clsx('ra-delete-button', classes.deleteButton, className)}
+ {...rest}
+ >
+ <DeleteIcon />
+ </Button>
+ <Confirm
+ isOpen={open}
+ loading={loading}
+ title="message.delete_radio_title"
+ content="message.delete_radio_content"
+ translateOptions={{
+ name: record.name,
+ }}
+ onConfirm={handleDelete}
+ onClose={handleDialogClose}
+ />
+ </>
+ )
+}
+
+export default DeleteRadioButton
diff --git a/ui/src/radio/RadioCreate.js b/ui/src/radio/RadioCreate.js
new file mode 100644
index 000000000..0b7b7a555
--- /dev/null
+++ b/ui/src/radio/RadioCreate.js
@@ -0,0 +1,60 @@
+import React, { useCallback } from 'react'
+import {
+ Create,
+ required,
+ SimpleForm,
+ TextInput,
+ useMutation,
+ useNotify,
+ useRedirect,
+ useTranslate,
+} from 'react-admin'
+import { Title } from '../common'
+
+const RadioCreate = (props) => {
+ const translate = useTranslate()
+ const [mutate] = useMutation()
+ const notify = useNotify()
+ const redirect = useRedirect()
+
+ const resourceName = translate('resources.radio.name', { smart_count: 1 })
+ const title = translate('ra.page.create', {
+ name: `${resourceName}`,
+ })
+
+ const save = useCallback(
+ async (values) => {
+ try {
+ await mutate(
+ {
+ type: 'create',
+ resource: 'radio',
+ payload: { data: values },
+ },
+ { returnPromise: true }
+ )
+ notify('resources.radio.notifications.created', 'info', {
+ smart_count: 1,
+ })
+ redirect('/radio')
+ } catch (error) {
+ if (error.body.errors) {
+ return error.body.errors
+ }
+ }
+ },
+ [mutate, notify, redirect]
+ )
+
+ return (
+ <Create title={<Title subTitle={title} />} {...props}>
+ <SimpleForm save={save} variant={'outlined'}>
+ <TextInput source="name" validate={[required()]} />
+ <TextInput type="url" source="streamUrl" validate={[required()]} />
+ <TextInput type="url" source="homepageUrl" />
+ </SimpleForm>
+ </Create>
+ )
+}
+
+export default RadioCreate
diff --git a/ui/src/radio/RadioEdit.js b/ui/src/radio/RadioEdit.js
new file mode 100644
index 000000000..6e9e87145
--- /dev/null
+++ b/ui/src/radio/RadioEdit.js
@@ -0,0 +1,134 @@
+import { Card, makeStyles } from '@material-ui/core'
+import React, { useCallback } from 'react'
+import {
+ DateField,
+ EditContextProvider,
+ required,
+ SaveButton,
+ SimpleForm,
+ TextInput,
+ Toolbar,
+ useEditController,
+ useMutation,
+ useNotify,
+ useRedirect,
+} from 'react-admin'
+import DeleteRadioButton from './DeleteRadioButton'
+
+const useStyles = makeStyles({
+ toolbar: {
+ display: 'flex',
+ justifyContent: 'space-between',
+ },
+})
+
+function urlValidate(value) {
+ if (!value) {
+ return undefined
+ }
+
+ try {
+ new URL(value)
+ return undefined
+ } catch (_) {
+ return 'ra.validation.url'
+ }
+}
+
+const RadioToolbar = (props) => (
+ <Toolbar {...props} classes={useStyles()}>
+ <SaveButton disabled={props.pristine} />
+ <DeleteRadioButton />
+ </Toolbar>
+)
+
+const RadioEditLayout = ({
+ hasCreate,
+ hasShow,
+ hasEdit,
+ hasList,
+ ...props
+}) => {
+ const [mutate] = useMutation()
+ const notify = useNotify()
+ const redirect = useRedirect()
+
+ const { record } = props
+
+ const save = useCallback(
+ async (values) => {
+ try {
+ await mutate(
+ {
+ type: 'update',
+ resource: 'radio',
+ payload: {
+ id: values.id,
+ data: {
+ name: values.name,
+ streamUrl: values.streamUrl,
+ homePageUrl: values.homePageUrl,
+ },
+ },
+ },
+ { returnPromise: true }
+ )
+ notify('resources.radio.notifications.updated', 'info', {
+ smart_count: 1,
+ })
+ redirect('/radio')
+ } catch (error) {
+ if (error.body.errors) {
+ return error.body.errors
+ }
+ }
+ },
+ [mutate, notify, redirect]
+ )
+
+ if (!record) {
+ return null
+ }
+
+ return (
+ <>
+ {record && (
+ <Card>
+ <SimpleForm
+ variant="outlined"
+ save={save}
+ toolbar={<RadioToolbar />}
+ {...props}
+ >
+ <TextInput source="name" validate={[required()]} />
+ <TextInput
+ type="url"
+ source="streamUrl"
+ fullWidth
+ validate={[required(), urlValidate]}
+ />
+ <TextInput
+ type="url"
+ source="homePageUrl"
+ fullWidth
+ validate={[urlValidate]}
+ />
+ <DateField variant="body1" source="updatedAt" showTime />
+ <DateField variant="body1" source="createdAt" showTime />
+ </SimpleForm>
+ </Card>
+ )}
+ </>
+ )
+}
+
+const RadioEdit = (props) => {
+ const controllerProps = useEditController(props)
+ return (
+ <EditContextProvider value={controllerProps}>
+ <RadioEditLayout {...props} record={controllerProps.record} />
+ </EditContextProvider>
+ )
+}
+
+export default RadioEdit
diff --git a/ui/src/radio/RadioList.js b/ui/src/radio/RadioList.js
new file mode 100644
index 000000000..d5bf46f61
--- /dev/null
+++ b/ui/src/radio/RadioList.js
@@ -0,0 +1,139 @@
+import { makeStyles, useMediaQuery } from '@material-ui/core'
+import React, { cloneElement } from 'react'
+import {
+ CreateButton,
+ Datagrid,
+ DateField,
+ Filter,
+ List,
+ sanitizeListRestProps,
+ SearchInput,
+ SimpleList,
+ TextField,
+ TopToolbar,
+ UrlField,
+ useTranslate,
+} from 'react-admin'
+import { ToggleFieldsMenu, useSelectedFields } from '../common'
+import { StreamField } from './StreamField'
+
+const useStyles = makeStyles({
+ row: {
+ '&:hover': {
+ '& $contextMenu': {
+ visibility: 'visible',
+ },
+ },
+ },
+ contextMenu: {
+ visibility: 'hidden',
+ },
+})
+
+const RadioFilter = (props) => (
+ <Filter {...props} variant={'outlined'}>
+ <SearchInput id="search" source="name" alwaysOn />
+ </Filter>
+)
+
+const RadioListActions = ({
+ className,
+ filters,
+ resource,
+ showFilter,
+ displayedFilters,
+ filterValues,
+ isAdmin,
+ ...rest
+}) => {
+ const isNotSmall = useMediaQuery((theme) => theme.breakpoints.up('sm'))
+ const translate = useTranslate()
+
+ return (
+ <TopToolbar className={className} {...sanitizeListRestProps(rest)}>
+ {isAdmin && (
+ <CreateButton basePath="/radio">
+ {translate('ra.action.create')}
+ </CreateButton>
+ )}
+ {filters &&
+ cloneElement(filters, {
+ resource,
+ showFilter,
+ displayedFilters,
+ filterValues,
+ context: 'button',
+ })}
+ {isNotSmall && <ToggleFieldsMenu resource="radio" />}
+ </TopToolbar>
+ )
+}
+
+const RadioList = ({ permissions, ...props }) => {
+ const isXsmall = useMediaQuery((theme) => theme.breakpoints.down('xs'))
+
+ const classes = useStyles()
+
+ const isAdmin = permissions === 'admin'
+
+ const toggleableFields = {
+ name: <TextField source="name" />,
+ homePageUrl: (
+ <UrlField
+ source="homePageUrl"
+ onClick={(e) => e.stopPropagation()}
+ target="_blank"
+ rel="noopener noreferrer"
+ />
+ ),
+ streamUrl: <StreamField source="streamUrl" />,
+ createdAt: <DateField source="createdAt" showTime />,
+ updatedAt: <DateField source="updatedAt" showTime />,
+ }
+
+ const columns = useSelectedFields({
+ resource: 'radio',
+ columns: toggleableFields,
+ defaultOff: ['updatedAt'],
+ })
+
+ return (
+ <List
+ {...props}
+ exporter={false}
+ bulkActionButtons={isAdmin ? undefined : false}
+ hasCreate={isAdmin}
+ actions={<RadioListActions isAdmin={isAdmin} />}
+ filters={<RadioFilter />}
+ perPage={isXsmall ? 25 : 10}
+ >
+ {isXsmall ? (
+ <SimpleList
+ linkType={isAdmin ? 'edit' : 'show'}
+ leftIcon={(r) => (
+ <StreamField
+ record={r}
+ source={'streamUrl'}
+ hideUrl
+ onClick={(e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ }}
+ />
+ )}
+ primaryText={(r) => r.name}
+ secondaryText={(r) => r.homePageUrl}
+ />
+ ) : (
+ <Datagrid
+ rowClick={isAdmin ? 'edit' : 'show'}
+ classes={{ row: classes.row }}
+ >
+ {columns}
+ </Datagrid>
+ )}
+ </List>
+ )
+}
+
+export default RadioList
diff --git a/ui/src/radio/RadioShow.js b/ui/src/radio/RadioShow.js
new file mode 100644
index 000000000..ae9500bcf
--- /dev/null
+++ b/ui/src/radio/RadioShow.js
@@ -0,0 +1,52 @@
+import { Card } from '@material-ui/core'
+import React from 'react'
+import {
+ DateField,
+ required,
+ ShowContextProvider,
+ SimpleShowLayout,
+ TextField,
+ UrlField,
+ useShowController,
+} from 'react-admin'
+import { StreamField } from './StreamField'
+
+const RadioShowLayout = ({ ...props }) => {
+ const { record } = props
+
+ if (!record) {
+ return null
+ }
+
+ return (
+ <>
+ {record && (
+ <Card>
+ <SimpleShowLayout>
+ <TextField source="name" validate={[required()]} />
+ <StreamField source="streamUrl" />
+ <UrlField
+ type="url"
+ source="homePageUrl"
+ rel="noreferrer noopener"
+ target="_blank"
+ />
+ <DateField variant="body1" source="updatedAt" showTime />
+ <DateField variant="body1" source="createdAt" showTime />
+ </SimpleShowLayout>
+ </Card>
+ )}
+ </>
+ )
+}
+
+const RadioShow = (props) => {
+ const controllerProps = useShowController(props)
+ return (
+ <ShowContextProvider value={controllerProps}>
+ <RadioShowLayout {...props} record={controllerProps.record} />
+ </ShowContextProvider>
+ )
+}
+
+export default RadioShow
diff --git a/ui/src/radio/StreamField.js b/ui/src/radio/StreamField.js
new file mode 100644
index 000000000..57c8731c8
--- /dev/null
+++ b/ui/src/radio/StreamField.js
@@ -0,0 +1,50 @@
+import { Button, makeStyles } from '@material-ui/core'
+import PropTypes from 'prop-types'
+import React, { useCallback } from 'react'
+import { useRecordContext } from 'react-admin'
+import { useDispatch } from 'react-redux'
+import { setTrack } from '../actions'
+import { songFromRadio } from './helper'
+import PlayArrowIcon from '@material-ui/icons/PlayArrow'
+
+const useStyles = makeStyles((theme) => ({
+ button: {
+ padding: '5px 0px',
+ textTransform: 'none',
+ marginRight: theme.spacing(1.5),
+ },
+}))
+
+export const StreamField = ({ hideUrl, ...rest }) => {
+ const record = useRecordContext(rest)
+ const dispatch = useDispatch()
+ const classes = useStyles()
+
+ const playTrack = useCallback(
+ async (evt) => {
+ evt.stopPropagation()
+ evt.preventDefault()
+ dispatch(setTrack(await songFromRadio(record)))
+ },
+ [dispatch, record]
+ )
+
+ return (
+ <Button className={classes.button} onClick={playTrack}>
+ <PlayArrowIcon />
+ {!hideUrl && record.streamUrl}
+ </Button>
+ )
+}
+
+StreamField.propTypes = {
+ label: PropTypes.string,
+ record: PropTypes.object,
+ source: PropTypes.string.isRequired,
+ hideUrl: PropTypes.bool,
+}
+
+StreamField.defaultProps = {
+ addLabel: true,
+ hideUrl: false,
+}
diff --git a/ui/src/radio/helper.js b/ui/src/radio/helper.js
new file mode 100644
index 000000000..5fc4098f1
--- /dev/null
+++ b/ui/src/radio/helper.js
@@ -0,0 +1,35 @@
+export async function songFromRadio(radio) {
+ if (!radio) {
+ return undefined
+ }
+
+ let cover = 'internet-radio-icon.svg'
+ try {
+ const url = new URL(radio.homePageUrl ?? radio.streamUrl)
+ url.pathname = '/favicon.ico'
+ await resourceExists(url)
+ cover = url.toString()
+ } catch {}
+
+ return {
+ ...radio,
+ title: radio.name,
+ album: radio.homePageUrl || radio.name,
+ artist: radio.name,
+ cover,
+ isRadio: true,
+ }
+}
+
+const resourceExists = (url) => {
+ return new Promise((resolve, reject) => {
+ const img = new Image()
+ img.onload = function () {
+ resolve(url)
+ }
+ img.onerror = function () {
+ reject('not found')
+ }
+ img.src = url
+ })
+}
diff --git a/ui/src/radio/index.js b/ui/src/radio/index.js
new file mode 100644
index 000000000..1e49b7cc9
--- /dev/null
+++ b/ui/src/radio/index.js
@@ -0,0 +1,28 @@
+import RadioCreate from './RadioCreate'
+import RadioEdit from './RadioEdit'
+import RadioList from './RadioList'
+import RadioShow from './RadioShow'
+import DynamicMenuIcon from '../layout/DynamicMenuIcon'
+import RadioIcon from '@material-ui/icons/Radio'
+import RadioOutlinedIcon from '@material-ui/icons/RadioOutlined'
+import React from 'react'
+
+const all = {
+ list: RadioList,
+ icon: (
+ <DynamicMenuIcon
+ path={'radio'}
+ icon={RadioOutlinedIcon}
+ activeIcon={RadioIcon}
+ />
+ ),
+ show: RadioShow,
+}
+
+const admin = {
+ ...all,
+ create: RadioCreate,
+ edit: RadioEdit,
+}
+
+export default { all, admin }
diff --git a/ui/src/reducers/playerReducer.js b/ui/src/reducers/playerReducer.js
index dc642e527..be9f42a8c 100644
--- a/ui/src/reducers/playerReducer.js
+++ b/ui/src/reducers/playerReducer.js
@@ -23,6 +23,19 @@ const initialState = {
const mapToAudioLists = (item) => {
// If item comes from a playlist, trackId is mediaFileId
const trackId = item.mediaFileId || item.id
+
+ if (item.isRadio) {
+ return {
+ trackId,
+ uuid: uuidv4(),
+ name: item.name,
+ song: item,
+ musicSrc: item.streamUrl,
+ cover: item.cover,
+ isRadio: true,
+ }
+ }
+
const { lyrics } = item
const timestampRegex =
/(\[([0-9]{1,2}:)?([0-9]{1,2}:)([0-9]{1,2})(\.[0-9]{1,2})?\])/g