melodee icon indicating copy to clipboard operation
melodee copied to clipboard

Internet radio

Open sphildreth opened this issue 10 months ago • 1 comments

Objective

Melodee already supports a global, admin-managed list of radio stations. This story expands that into a complete Internet Radio feature area with:

  1. Personalization (favorites, hide, ordering)
  2. Reliability/operations (station health checks + diagnostics)
  3. Live metadata (Now Playing via ICY/Ogg metadata capture)
  4. 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 Admin role/claim (match existing patterns)

1) List stations (user-aware)

GET /api/v1/radio/stations

Query params:

  • q (string, optional): search by name/tags/country/language
  • includeHidden (bool, default false)
  • favoritesOnly (bool, default false)

Response: RadioStationDto[] containing:

  • Station core fields
  • Derived personalization:
    • isFavorite
    • isHidden
    • sortOrder
  • Derived operational:
    • lastHealthStatus
    • lastHealthCheckUtc
    • lastHealthOkUtc
    • lastHealthError
    • nowPlayingRaw
    • nowPlayingCapturedUtc
  • logoUrl + logoCachedUrl (see logo caching section)

Server sorting:

  1. Favorites first (IsFavorite desc)
  2. SortOrder asc
  3. 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:

  • name required, 2..120 chars
  • streamUrl required, must be absolute URL
  • homePageUrl optional, absolute URL if provided
  • countryCode if provided: exactly 2 chars
  • languageCode if 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 message Station 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:

  1. Resolve the stream URL

    • Use HttpClient
    • Timeout = 10 seconds
    • Follow redirects up to 5
  2. Perform a probe request

    • Prefer HEAD
    • If HEAD fails (405/501), fallback to GET with Range: bytes=0-8191
    • Always include header: Icy-MetaData: 1
  3. Determine health

    • Health = OK when:
      • HTTP status is 200 or 206
      • AND returned content-type starts with audio/ OR application/ogg
    • Health = FAIL otherwise
  4. Capture diagnostics

    • Store LastResolvedStreamUrl
    • Store LastContentType
    • Store LastBitrateKbps if derivable
      • If response header contains icy-br use that
  5. Update status fields

    • Set LastHealthCheckUtc = now
    • On success:
      • LastHealthStatus = Ok
      • LastHealthOkUtc = now
      • LastHealthError = null
    • On failure:
      • LastHealthStatus = Fail
      • LastHealthError = <short message>

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 LastHealthOkUtc within last 30 minutes

Capture algorithm:

  1. Open GET to LastResolvedStreamUrl ?? StreamUrl

    • Timeout = 10 seconds
    • Include header Icy-MetaData: 1
    • Read up to 64KB then stop
  2. If response has icy-metaint header

    • Parse the stream metadata blocks
    • Extract StreamTitle value (if present)
  3. Else if response is Ogg

    • Attempt best-effort parse of Vorbis comments in initial buffer
    • If TITLE is found, use that
  4. Normalize value

    • Trim whitespace
    • If empty/null → do not update now playing
  5. Persist

    • Update station:
      • NowPlayingRaw
      • NowPlayingCapturedUtc
    • Insert history record (RadioStationNowPlayingHistory) if value changed from previous value

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 LogoUrl is set:
    1. Download it via HttpClient (timeout 10s)
    2. Allow only content types:
      • image/png, image/jpeg, image/webp, image/svg+xml
    3. Enforce max size 512KB
    4. Store it in the existing/static assets storage used by Melodee (or add a dedicated wwwroot/assets/radio-logos/ path)
    5. Save LogoCacheKey = filename/key

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 sortOrder by +/- 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:

  • getInternetRadioStations
  • createInternetRadioStation
  • updateInternetRadioStation
  • deleteInternetRadioStation

Behavior changes (safe / non-breaking):

  • getInternetRadioStations should return:
    • All stations except those hidden by the current user
    • Sorted with favorites first and then by SortOrder, then Name

Admin-only mutation remains enforced as it is today.


Tests (required)

Unit tests

  • Radio station probe success and failure paths
  • ICY metadata parser extracts StreamTitle
  • Preference patch creates 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 LogoUrl caches 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 RadioStation new columns
  • [ ] Create RadioStationUserPreference table + 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.

sphildreth avatar Jan 10 '26 15:01 sphildreth

This entire task was based out of confusion. Melodee has Radio Stations and this covers whatever this was trying to do.

sphildreth avatar Jan 20 '26 20:01 sphildreth