Internet radio
Objective
Melodee already supports a global, admin-managed list of radio stations. This story expands that into a complete Internet Radio feature area with:
- Personalization (favorites, hide, ordering)
- Reliability/operations (station health checks + diagnostics)
- Live metadata (Now Playing via ICY/Ogg metadata capture)
- UX completeness (logos + better browsing/search)
Non-goal: building a full Icecast/SHOUTcast directory crawler is not required for this story.
Definitions
Radio Station (existing)
A stored station record with a playable stream URL.
Internet Radio (this story)
A broader experience around radio stations including discovery/browsing UX, metadata, stability/health reporting, and per-user preferences.
Scope (what must be delivered)
Must-have capabilities
- Per-user favorites for stations
- Per-user ordering (pin/sort order)
- Per-user hide (station visibility)
- Station logo/artwork (URL-based + cached)
- Station health checks (periodic probe job)
- Now Playing extraction & display (ICY metadata OR Ogg/Vorbis comments where available)
- Admin UI enhancements for creating/updating stations with all new fields
- API endpoints to support the Blazor UI for the above
- OpenSubsonic compatibility remains working and continues returning stations reliably
Explicit out-of-scope (do not implement in this story)
- Recording/time-shifting/buffering
- Transcoding radio streams
- Full external directory search/integration (Icecast directory crawling, SHOUTcast APIs)
- OPML import/export workflows
(Those can be separate issues/phases later.)
Data Model (required schema changes)
1) Extend RadioStation
Add these columns/fields:
| Field | Type | Notes |
|---|---|---|
Description |
string? | Human-friendly description shown in UI |
TagsCsv |
string? | Comma-separated tags (e.g., rock,80s,classic) |
CountryCode |
string? | ISO 3166-1 alpha-2 (e.g., US, GB) |
LanguageCode |
string? | BCP-47 (e.g., en, en-US, es) |
LogoUrl |
string? | External URL for station logo |
LogoCacheKey |
string? | Key/filename for cached logo asset |
LastHealthCheckUtc |
DateTime? | Last probe time |
LastHealthOkUtc |
DateTime? | Last time probe succeeded |
LastHealthStatus |
enum | Unknown, Ok, Fail |
LastHealthError |
string? | Last failure reason (short message) |
LastResolvedStreamUrl |
string? | Final URL after redirects |
LastContentType |
string? | e.g., audio/mpeg, audio/aacp |
LastBitrateKbps |
int? | Best-effort; null if unknown |
NowPlayingRaw |
string? | Last captured title string (e.g., Artist - Track) |
NowPlayingCapturedUtc |
DateTime? | When NowPlayingRaw was last updated |
Keep existing fields (
Name,StreamUrl,HomePageUrl,Locked, etc.) intact.
2) New RadioStationUserPreference table
Purpose: store per-user personalization.
| Field | Type | Notes |
|---|---|---|
UserId |
Guid | FK to user |
RadioStationId |
Guid | FK to station |
IsFavorite |
bool | Default false |
IsHidden |
bool | Default false |
SortOrder |
int | Default 1000; lower = higher priority |
CreatedUtc |
DateTime | |
UpdatedUtc |
DateTime |
Constraints:
- Unique index on (
UserId,RadioStationId)
3) New RadioStationNowPlayingHistory table (required)
Store history for UX + troubleshooting.
| Field | Type | Notes |
|---|---|---|
RadioStationId |
Guid | FK |
CapturedUtc |
DateTime | |
NowPlayingRaw |
string | |
Source |
enum/string | Icy, Ogg, HttpHeader, Unknown |
Retention:
- Keep up to 200 rows per station
- Cleanup job runs daily and trims oldest rows over limit
API Requirements (Melodee REST API)
Namespace these under
/api/v1/radio/....
Auth
- All endpoints require authenticated user
- Admin endpoints require
Adminrole/claim (match existing patterns)
1) List stations (user-aware)
GET /api/v1/radio/stations
Query params:
q(string, optional): search by name/tags/country/languageincludeHidden(bool, default false)favoritesOnly(bool, default false)
Response: RadioStationDto[] containing:
- Station core fields
- Derived personalization:
isFavoriteisHiddensortOrder
- Derived operational:
lastHealthStatuslastHealthCheckUtclastHealthOkUtclastHealthErrornowPlayingRawnowPlayingCapturedUtc
logoUrl+logoCachedUrl(see logo caching section)
Server sorting:
- Favorites first (IsFavorite desc)
- SortOrder asc
- Name asc
2) Update preferences
PUT /api/v1/radio/stations/{id}/preferences
Body:
{
"isFavorite": true,
"isHidden": false,
"sortOrder": 10
}
Rules:
- Any omitted fields are left unchanged
- If preference row doesn’t exist, create it with defaults then apply patch
3) Admin: create station
POST /api/v1/radio/admin/stations
Body:
{
"name": "Example FM",
"streamUrl": "https://example.com/stream",
"homePageUrl": "https://example.com",
"description": "Optional description",
"tagsCsv": "rock,classic",
"countryCode": "US",
"languageCode": "en",
"logoUrl": "https://example.com/logo.png",
"locked": false
}
Validation:
namerequired, 2..120 charsstreamUrlrequired, must be absolute URLhomePageUrloptional, absolute URL if providedcountryCodeif provided: exactly 2 charslanguageCodeif provided: 2..12 chars
4) Admin: update station
PUT /api/v1/radio/admin/stations/{id}
Same payload/validation as create (full replace semantics).
5) Admin: delete station
DELETE /api/v1/radio/admin/stations/{id}
Rules:
- If station is
locked=true→ reject with 409 and messageStation is locked
6) Station diagnostics
GET /api/v1/radio/stations/{id}/diagnostics
Return:
- Health fields + last resolved URL
- Last content type / bitrate
- Now-playing current value
- Recent now-playing history (last 25 entries)
Background jobs (required)
Job A — Station health probe
Schedule:
- Run every 15 minutes
For each station:
-
Resolve the stream URL
- Use
HttpClient Timeout = 10 seconds- Follow redirects up to 5
- Use
-
Perform a probe request
- Prefer
HEAD - If
HEADfails (405/501), fallback toGETwithRange: bytes=0-8191 - Always include header:
Icy-MetaData: 1
- Prefer
-
Determine health
- Health = OK when:
- HTTP status is 200 or 206
- AND returned content-type starts with
audio/ORapplication/ogg
- Health = FAIL otherwise
- Health = OK when:
-
Capture diagnostics
- Store
LastResolvedStreamUrl - Store
LastContentType - Store
LastBitrateKbpsif derivable- If response header contains
icy-bruse that
- If response header contains
- Store
-
Update status fields
- Set
LastHealthCheckUtc = now - On success:
LastHealthStatus = OkLastHealthOkUtc = nowLastHealthError = null
- On failure:
LastHealthStatus = FailLastHealthError = <short message>
- Set
Logging:
- Log failures with station id + name + url + error
Job B — Now Playing capture
Schedule:
- Run every 5 minutes
Behavior:
- Only attempt capture for stations where:
LastHealthStatus = Ok- AND
LastHealthOkUtcwithin last 30 minutes
Capture algorithm:
-
Open
GETtoLastResolvedStreamUrl ?? StreamUrlTimeout = 10 seconds- Include header
Icy-MetaData: 1 - Read up to 64KB then stop
-
If response has
icy-metaintheader- Parse the stream metadata blocks
- Extract
StreamTitlevalue (if present)
-
Else if response is Ogg
- Attempt best-effort parse of Vorbis comments in initial buffer
- If
TITLEis found, use that
-
Normalize value
- Trim whitespace
- If empty/null → do not update now playing
-
Persist
- Update station:
NowPlayingRawNowPlayingCapturedUtc
- Insert history record (
RadioStationNowPlayingHistory) if value changed from previous value
- Update station:
Job C — Now Playing history retention cleanup
Schedule:
- Run daily
Rules:
- Ensure max 200 rows per station (delete oldest over limit)
Logo caching (required)
Purpose: avoid UI hotlinking and allow consistent rendering.
Rules:
- If
LogoUrlis set:- Download it via
HttpClient(timeout 10s) - Allow only content types:
image/png,image/jpeg,image/webp,image/svg+xml
- Enforce max size 512KB
- Store it in the existing/static assets storage used by Melodee (or add a dedicated
wwwroot/assets/radio-logos/path) - Save
LogoCacheKey= filename/key
- Download it via
Caching triggers:
- On station create/update when LogoUrl changes
- Daily job refresh for all LogoUrl stations (optional in this story: DO NOT implement refresh; only cache on change)
Expose logoCachedUrl in API as:
/assets/radio-logos/{LogoCacheKey}
Blazor UI requirements
Navigation
Add a new top-level entry:
- Internet Radio
Page: /radio
Layout:
- Search bar (filters by name/tags/country/language)
- Tabs:
- All Stations
- Favorites
Station row/card must show:
- Logo (cached if available; fallback icon otherwise)
- Name
- Optional: Country + Language (small text)
- Now Playing line (if available)
- Health badge:
- Green: Ok
- Red: Fail
- Gray: Unknown
- Actions:
- Favorite toggle (star)
- Hide/unhide toggle
Ordering:
- Favorites first
- Then sortOrder
Reordering:
- Provide “Move up” / “Move down” buttons (no drag/drop required)
- Each click adjusts
sortOrderby +/- 10 and persists via preferences endpoint
Page: /radio/station/{id}
Details view:
- Station core info
- Play button
- Home page link
- Diagnostics panel (calls
GET /diagnostics):- last status
- last error
- last ok time
- last check time
- resolved url
- content-type
- bitrate
- Now Playing history table (last 25)
Admin page: /data/radiostations
Enhancements required:
- Add edit/create fields for:
- Description
- Tags
- Country
- Language
- LogoUrl
- Add “Test station” button:
- Executes a probe call for that station and displays result inline
- This should call a server endpoint that runs the same probe logic as Job A (single-station)
Admin permissions:
- Only admins can create/update/delete
OpenSubsonic compatibility requirements
Existing OpenSubsonic endpoints MUST remain functional:
getInternetRadioStationscreateInternetRadioStationupdateInternetRadioStationdeleteInternetRadioStation
Behavior changes (safe / non-breaking):
getInternetRadioStationsshould return:- All stations except those hidden by the current user
- Sorted with favorites first and then by
SortOrder, thenName
Admin-only mutation remains enforced as it is today.
Tests (required)
Unit tests
Radio station probesuccess and failure pathsICY metadata parserextractsStreamTitlePreference patchcreates row if missing and updates fields correctly
Integration tests
- API authorization:
- non-admin cannot call admin endpoints
- admin can create/update/delete
- Diagnostics endpoint returns expected data
Acceptance criteria
Personalization
- [ ] A user can favorite/unfavorite a station and it persists
- [ ] A user can hide/unhide a station and it persists
- [ ] A user can reorder favorites using up/down and it persists
Reliability/ops
- [ ] Health probe job runs and populates status fields for stations
- [ ] Admin UI shows health state + last error
- [ ] Station diagnostics endpoint returns health + resolved url + content-type
Now Playing
- [ ] Now playing is captured for stations that provide ICY metadata
- [ ] Now playing is stored on the station record and displayed in UI
- [ ] History rows are written when Now Playing changes
- [ ] Daily retention cleanup enforces 200 rows max per station
Logo
- [ ] Setting
LogoUrlcaches the logo and displays it in UI - [ ] Only allowed image types are accepted
- [ ] Oversized images are rejected and logged
Subsonic compatibility
- [ ] Existing OpenSubsonic radio endpoints continue working
- [ ] getInternetRadioStations excludes hidden stations for current user
Implementation checklist (agent execution order)
Phase 1 — Data + API + personalization
- [ ] DB migrations for
RadioStationnew columns - [ ] Create
RadioStationUserPreferencetable + CRUD - [ ] Implement REST endpoints: list stations + update preferences
Phase 2 — Health probing
- [ ] Implement probe service + unit tests
- [ ] Implement Job A scheduler
- [ ] Implement diagnostics endpoint
Phase 3 — Now Playing
- [ ] Implement ICY parser + unit tests
- [ ] Implement Job B scheduler
- [ ] Create history table + retention job
Phase 4 — Logo caching + UI polish
- [ ] Implement logo caching pipeline
- [ ] Update REST DTOs with cached logo URL
- [ ] Update Blazor pages (
/radio, station details) - [ ] Update admin station edit UI
Notes for the coding agent
- Reuse existing Melodee patterns for:
- auth/claims checks
- background scheduling infrastructure
- DTO mapping
- logging conventions
- This story intentionally does not include external directory ingestion or streaming proxy/transcode.
- Keep the implementation additive and non-breaking.
This entire task was based out of confusion. Melodee has Radio Stations and this covers whatever this was trying to do.