feat: Stream Now instant-play of a random track from the nav button

This commit is contained in:
daniel-c-harvey
2026-06-07 18:33:08 -04:00
parent 2b4cdeaf72
commit 0d4ef369b9
11 changed files with 287 additions and 2 deletions
@@ -72,6 +72,30 @@ public class TrackController : ControllerBase
return Ok(result.Value); return Ok(result.Value);
} }
// GET api/track/random (unauthenticated)
// Picks one track at random from the full library and returns its metadata. Public, same auth
// posture as GET api/track/page. Selection math lives in the SQL service/repository, not here.
// 404 when the library is empty (a valid state the client renders as "no tracks yet"), 200 +
// TrackDto otherwise. Literal segment, declared before "{trackId}" so it never routes there.
[HttpGet("random")]
public async Task<ActionResult> GetRandom(CancellationToken cancellationToken = default)
{
var result = await _sqlTrackService.GetRandom(cancellationToken);
if (!result.Success)
{
var error = result.Messages.FirstOrDefault()?.Message ?? "Unknown error";
_logger.LogError("GetRandom failed: {Error}", error);
return StatusCode(500, "Failed to load track");
}
if (result.Value is null)
{
return NotFound();
}
return Ok(result.Value);
}
// GET api/track/waveform-status ([ApiKeyAuthorize]) // GET api/track/waveform-status ([ApiKeyAuthorize])
// Admin backfill view: returns every track with a flag for whether a waveform profile is // Admin backfill view: returns every track with a flag for whether a waveform profile is
// stored in the WaveformProfiles vault. The catalogue is small enough that the CMS panel reads // stored in the WaveformProfiles vault. The catalogue is small enough that the CMS panel reads
+6
View File
@@ -13,6 +13,12 @@ public interface ITrackService
{ {
Task<ResultContainer<TrackDto?>> GetById(long id); Task<ResultContainer<TrackDto?>> GetById(long id);
Task<ResultContainer<TrackDto?>> GetByEntryKey(string entryKey); Task<ResultContainer<TrackDto?>> GetByEntryKey(string entryKey);
/// <summary>
/// Returns a single track chosen uniformly at random, or null when the library is empty
/// (a valid state, not a failure). Backs the public "Stream Now" instant-play feature.
/// </summary>
Task<ResultContainer<TrackDto?>> GetRandom(CancellationToken cancellationToken = default);
Task<ResultContainer<List<TrackDto>>> GetAll(); Task<ResultContainer<List<TrackDto>>> GetAll();
Task<ResultContainer<PagedResult<TrackDto>>> GetPaged(int pageNumber, int pageSize, string? sortColumn, bool sortDescending, CancellationToken cancellationToken = default); Task<ResultContainer<PagedResult<TrackDto>>> GetPaged(int pageNumber, int pageSize, string? sortColumn, bool sortDescending, CancellationToken cancellationToken = default);
Task<ResultContainer<TrackDto>> Create(TrackDto newTrack); Task<ResultContainer<TrackDto>> Create(TrackDto newTrack);
@@ -25,6 +25,25 @@ public class TrackRepository : Repository<DeepDrftContext, TrackEntity>
public async Task<TrackEntity?> GetByEntryKeyAsync(string entryKey) public async Task<TrackEntity?> GetByEntryKeyAsync(string entryKey)
=> await _context.Tracks.FirstOrDefaultAsync(t => t.EntryKey == entryKey); => await _context.Tracks.FirstOrDefaultAsync(t => t.EntryKey == entryKey);
// Picks one track uniformly at random. Two round-trips (count, then a single offset row)
// rather than ORDER BY random() so the database never sorts the whole table — the catalogue
// is small today but this keeps the cost flat as it grows. Returns null when empty so the
// service surfaces a valid empty-library state, not an error. Queries the DbSet directly,
// mirroring GetByEntryKeyAsync, since the base Repository<> exposes only id-based reads.
public async Task<TrackEntity?> GetRandomAsync(CancellationToken cancellationToken = default)
{
var count = await _context.Tracks.CountAsync(cancellationToken);
if (count == 0)
return null;
var index = Random.Shared.Next(count);
return await _context.Tracks
.OrderBy(t => t.Id)
.Skip(index)
.Take(1)
.FirstOrDefaultAsync(cancellationToken);
}
protected override void UpdateEntity(TrackEntity target, TrackEntity source) protected override void UpdateEntity(TrackEntity target, TrackEntity source)
{ {
base.UpdateEntity(target, source); // copies CreatedAt, UpdatedAt, IsDeleted base.UpdateEntity(target, source); // copies CreatedAt, UpdatedAt, IsDeleted
+16
View File
@@ -62,6 +62,22 @@ public class TrackManager
} }
} }
// No base-name conflict, so this is a plain public method. Mirrors the nullable-on-empty
// shape of GetById: pass with null when the library has no tracks.
public async Task<ResultContainer<TrackDto?>> GetRandom(CancellationToken cancellationToken = default)
{
try
{
var entity = await Repository.GetRandomAsync(cancellationToken);
return ResultContainer<TrackDto?>.CreatePassResult(
entity is null ? null : TrackConverter.Convert(entity));
}
catch (Exception e)
{
return ResultContainer<TrackDto?>.CreateFailResult(e.Message);
}
}
public async Task<ResultContainer<List<TrackDto>>> GetAll() public async Task<ResultContainer<List<TrackDto>>> GetAll()
{ {
try try
@@ -51,6 +51,32 @@ public class TrackClient
: ApiResult<PagedResult<TrackDto>>.CreateFailResult("Failed to deserialize response"); : ApiResult<PagedResult<TrackDto>>.CreateFailResult("Failed to deserialize response");
} }
/// <summary>
/// Fetches a random track from the public library. A 404 means the library is empty — a valid
/// state, not an error — so it returns a pass result with a null value. Any other non-success
/// status is a genuine failure.
/// </summary>
public async Task<ApiResult<TrackDto?>> GetRandom()
{
var response = await _http.GetAsync("api/track/random");
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
return ApiResult<TrackDto?>.CreatePassResult(null);
if (!response.IsSuccessStatusCode)
return ApiResult<TrackDto?>.CreateFailResult($"HTTP {(int)response.StatusCode}");
var json = await response.Content.ReadAsStringAsync();
var track = JsonSerializer.Deserialize<TrackDto>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return track is not null
? ApiResult<TrackDto?>.CreatePassResult(track)
: ApiResult<TrackDto?>.CreateFailResult("Failed to deserialize response");
}
public async Task<ApiResult<TrackDto>> GetTrack(string entryKey) public async Task<ApiResult<TrackDto>> GetTrack(string entryKey)
{ {
var response = await _http.GetAsync($"api/track/meta/by-key/{Uri.EscapeDataString(entryKey)}"); var response = await _http.GetAsync($"api/track/meta/by-key/{Uri.EscapeDataString(entryKey)}");
+135 -2
View File
@@ -16,7 +16,20 @@
</ul> </ul>
<div class="dd-nav-actions"> <div class="dd-nav-actions">
<a href="/tracks" class="dd-nav-cta">Stream Now &#9654;</a> <button type="button"
class="dd-nav-cta"
disabled="@_streamLoading"
aria-busy="@_streamLoading.ToString().ToLowerInvariant()"
@onclick="StreamNow">
@if (_streamLoading)
{
<span>Finding a track&#8230;</span>
}
else
{
<span>Stream Now &#9654;</span>
}
</button>
@* <button type="button" *@ @* <button type="button" *@
@* class="dd-nav-toggle" *@ @* class="dd-nav-toggle" *@
@* aria-label="Toggle dark mode" *@ @* aria-label="Toggle dark mode" *@
@@ -25,6 +38,11 @@
@* @((MarkupString)DarkLightModeIconSvg) *@ @* @((MarkupString)DarkLightModeIconSvg) *@
@* </button> *@ @* </button> *@
</div> </div>
@if (_streamMessage is not null)
{
<p class="dd-nav-stream-message" role="status">@_streamMessage</p>
}
</nav> </nav>
</div> </div>
@@ -60,15 +78,37 @@
</li> </li>
} }
<li> <li>
<a href="/tracks" class="dd-nav-cta" @onclick="CloseMobileMenu">Stream Now &#9654;</a> <button type="button"
class="dd-nav-cta"
disabled="@_streamLoading"
aria-busy="@_streamLoading.ToString().ToLowerInvariant()"
@onclick="StreamNowMobile">
@if (_streamLoading)
{
<span>Finding a track&#8230;</span>
}
else
{
<span>Stream Now &#9654;</span>
}
</button>
</li> </li>
</ul> </ul>
} }
@if (_streamMessage is not null)
{
<p class="dd-nav-stream-message" role="status">@_streamMessage</p>
}
</nav> </nav>
</div> </div>
@implements IDisposable
@code { @code {
[Inject] public required DarkModeCookieService DarkModeCookieService { get; set; } [Inject] public required DarkModeCookieService DarkModeCookieService { get; set; }
[Inject] public required ITrackDataService TrackData { get; set; }
[CascadingParameter] public IStreamingPlayerService? PlayerService { get; set; }
// Elevation is vestigial under the frosted-glass design but kept on the parameter // Elevation is vestigial under the frosted-glass design but kept on the parameter
// surface so MainLayout's <DeepDrftMenu Elevation="..."> call site stays intact. // surface so MainLayout's <DeepDrftMenu Elevation="..."> call site stays intact.
@@ -77,6 +117,99 @@
[Parameter] public required EventCallback<bool> IsDarkModeChanged { get; set; } [Parameter] public required EventCallback<bool> IsDarkModeChanged { get; set; }
private bool _mobileMenuOpen; private bool _mobileMenuOpen;
private bool _streamLoading;
private string? _streamMessage;
private CancellationTokenSource? _messageCts;
private const string EmptyLibraryMessage = "No tracks yet — check back soon.";
private const string FetchFailedMessage = "Couldn't reach the library — try again.";
private Task StreamNow() => StreamNowCore(closeMobileMenu: false);
private Task StreamNowMobile() => StreamNowCore(closeMobileMenu: true);
private async Task StreamNowCore(bool closeMobileMenu)
{
// Re-entrancy guard: the button is disabled while loading, but guard in code too so a
// double-dispatch can never start two concurrent streams.
if (_streamLoading) return;
_streamLoading = true;
_streamMessage = null;
// Warm the AudioContext FIRST, inside the gesture's call stack and before the network
// await below. Safari only lets a suspended AudioContext resume while the originating
// user gesture is still active; awaiting GetRandomTrack() first would consume the gesture
// and leave playback silently refused. PlayerService is null only outside the
// AudioPlayerProvider cascade (it should always be present in the public layout).
var warmTask = PlayerService?.WarmAudioContext() ?? Task.CompletedTask;
try
{
await warmTask;
var result = await TrackData.GetRandomTrack();
if (!result.Success)
{
ShowTransientMessage(FetchFailedMessage);
return;
}
if (result.Value is not { } track)
{
ShowTransientMessage(EmptyLibraryMessage);
return;
}
if (closeMobileMenu)
_mobileMenuOpen = false;
if (PlayerService is not null)
await PlayerService.SelectTrackStreaming(track);
}
catch (Exception)
{
ShowTransientMessage(FetchFailedMessage);
}
finally
{
_streamLoading = false;
}
}
private void ShowTransientMessage(string message)
{
_streamMessage = message;
// Cancel any in-flight clear timer so the newest message gets its full display window.
_messageCts?.Cancel();
_messageCts?.Dispose();
_messageCts = new CancellationTokenSource();
var token = _messageCts.Token;
_ = ClearMessageAfterDelayAsync(token);
}
private async Task ClearMessageAfterDelayAsync(CancellationToken token)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(4), token);
}
catch (TaskCanceledException)
{
return;
}
_streamMessage = null;
await InvokeAsync(StateHasChanged);
}
public void Dispose()
{
_messageCts?.Cancel();
_messageCts?.Dispose();
}
protected override async Task OnAfterRenderAsync(bool firstRender) protected override async Task OnAfterRenderAsync(bool firstRender)
{ {
@@ -63,6 +63,17 @@ public interface IStreamingPlayerService : IPlayerService
// Streaming control methods // Streaming control methods
Task SelectTrackStreaming(TrackDto track); Task SelectTrackStreaming(TrackDto track);
/// <summary>
/// Initializes the player (if needed) and resumes the AudioContext. Call this synchronously at
/// the very start of a user-gesture handler — before any <c>await</c> on network I/O — so the
/// gesture is still "active" when the context resumes. Safari refuses to start a suspended
/// AudioContext once the originating gesture has been consumed by an intervening await
/// (e.g. fetching which track to play), so warming here and streaming after is load-bearing.
/// <see cref="SelectTrackStreaming"/> also resumes the context, but only after its own internal
/// awaits — too late for a handler that must first fetch the track to play.
/// </summary>
Task WarmAudioContext();
/// <summary> /// <summary>
/// Stages a track as the current track without touching the audio context or starting the /// Stages a track as the current track without touching the audio context or starting the
/// stream. Used by the embed player, where there is no user gesture on initial load: the track /// stream. Used by the embed player, where there is no user gesture on initial load: the track
@@ -20,4 +20,11 @@ public interface ITrackDataService
bool sortDescending = false); bool sortDescending = false);
Task<ApiResult<TrackDto>> GetTrack(string trackId); Task<ApiResult<TrackDto>> GetTrack(string trackId);
/// <summary>
/// Fetches a random track from the public library for instant play. Success with a value on a
/// hit; success with a null value when the library is empty (a valid state, not a failure);
/// failure on any other transport error.
/// </summary>
Task<ApiResult<TrackDto?>> GetRandomTrack();
} }
@@ -46,6 +46,13 @@ public class StreamingAudioPlayerService : AudioPlayerService, IStreamingPlayerS
await SelectTrackStreaming(track); await SelectTrackStreaming(track);
} }
/// <inheritdoc />
public async Task WarmAudioContext()
{
await EnsureInitializedAsync();
await _audioInterop.EnsureAudioContextReady(PlayerId);
}
public async Task SelectTrackStreaming(TrackDto track) public async Task SelectTrackStreaming(TrackDto track)
{ {
await EnsureInitializedAsync(); await EnsureInitializedAsync();
@@ -28,4 +28,7 @@ public class TrackClientDataService : ITrackDataService
public Task<ApiResult<TrackDto>> GetTrack(string trackId) public Task<ApiResult<TrackDto>> GetTrack(string trackId)
=> _trackClient.GetTrack(trackId); => _trackClient.GetTrack(trackId);
public Task<ApiResult<TrackDto?>> GetRandomTrack()
=> _trackClient.GetRandom();
} }
@@ -59,6 +59,39 @@ public class TrackProxyController : ControllerBase
} }
} }
/// <summary>
/// Proxies the random-track metadata lookup from DeepDrftAPI. Unauthenticated, same posture as
/// the paged listing. Small JSON, buffered and relayed; a 404 from upstream (empty library)
/// passes through so the client renders it as a valid empty state. Declared before the
/// parameterized "{trackId}" route so the literal segment is never treated as a trackId.
/// </summary>
[HttpGet("random")]
public async Task<ActionResult> GetRandom(CancellationToken ct = default)
{
HttpResponseMessage upstream;
try
{
upstream = await _upstream.GetAsync("api/track/random", HttpCompletionOption.ResponseHeadersRead, ct);
}
catch (Exception ex)
{
_logger.LogError(ex, "Upstream call to DeepDrftAPI track/random failed");
return StatusCode(502, "Upstream unavailable");
}
using (upstream)
{
if (!upstream.IsSuccessStatusCode)
{
_logger.LogWarning("DeepDrftAPI track/random returned {Status}", (int)upstream.StatusCode);
return StatusCode((int)upstream.StatusCode);
}
var json = await upstream.Content.ReadAsStringAsync(ct);
return Content(json, "application/json");
}
}
/// <summary> /// <summary>
/// Proxies single-track metadata lookup by vault entry key from DeepDrftAPI. Unauthenticated, /// Proxies single-track metadata lookup by vault entry key from DeepDrftAPI. Unauthenticated,
/// same posture as the paged listing. Small JSON, so it is buffered and relayed; a 404 from /// same posture as the paged listing. Small JSON, so it is buffered and relayed; a 404 from