feat: Stream Now instant-play of a random track from the nav button
This commit is contained in:
@@ -51,6 +51,32 @@ public class TrackClient
|
||||
: 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)
|
||||
{
|
||||
var response = await _http.GetAsync($"api/track/meta/by-key/{Uri.EscapeDataString(entryKey)}");
|
||||
|
||||
@@ -16,7 +16,20 @@
|
||||
</ul>
|
||||
|
||||
<div class="dd-nav-actions">
|
||||
<a href="/tracks" class="dd-nav-cta">Stream Now ▶</a>
|
||||
<button type="button"
|
||||
class="dd-nav-cta"
|
||||
disabled="@_streamLoading"
|
||||
aria-busy="@_streamLoading.ToString().ToLowerInvariant()"
|
||||
@onclick="StreamNow">
|
||||
@if (_streamLoading)
|
||||
{
|
||||
<span>Finding a track…</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Stream Now ▶</span>
|
||||
}
|
||||
</button>
|
||||
@* <button type="button" *@
|
||||
@* class="dd-nav-toggle" *@
|
||||
@* aria-label="Toggle dark mode" *@
|
||||
@@ -25,6 +38,11 @@
|
||||
@* @((MarkupString)DarkLightModeIconSvg) *@
|
||||
@* </button> *@
|
||||
</div>
|
||||
|
||||
@if (_streamMessage is not null)
|
||||
{
|
||||
<p class="dd-nav-stream-message" role="status">@_streamMessage</p>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -60,15 +78,37 @@
|
||||
</li>
|
||||
}
|
||||
<li>
|
||||
<a href="/tracks" class="dd-nav-cta" @onclick="CloseMobileMenu">Stream Now ▶</a>
|
||||
<button type="button"
|
||||
class="dd-nav-cta"
|
||||
disabled="@_streamLoading"
|
||||
aria-busy="@_streamLoading.ToString().ToLowerInvariant()"
|
||||
@onclick="StreamNowMobile">
|
||||
@if (_streamLoading)
|
||||
{
|
||||
<span>Finding a track…</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Stream Now ▶</span>
|
||||
}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
}
|
||||
|
||||
@if (_streamMessage is not null)
|
||||
{
|
||||
<p class="dd-nav-stream-message" role="status">@_streamMessage</p>
|
||||
}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
@code {
|
||||
[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
|
||||
// surface so MainLayout's <DeepDrftMenu Elevation="..."> call site stays intact.
|
||||
@@ -77,6 +117,99 @@
|
||||
[Parameter] public required EventCallback<bool> IsDarkModeChanged { get; set; }
|
||||
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -63,6 +63,17 @@ public interface IStreamingPlayerService : IPlayerService
|
||||
// Streaming control methods
|
||||
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>
|
||||
/// 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
|
||||
|
||||
@@ -20,4 +20,11 @@ public interface ITrackDataService
|
||||
bool sortDescending = false);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task WarmAudioContext()
|
||||
{
|
||||
await EnsureInitializedAsync();
|
||||
await _audioInterop.EnsureAudioContextReady(PlayerId);
|
||||
}
|
||||
|
||||
public async Task SelectTrackStreaming(TrackDto track)
|
||||
{
|
||||
await EnsureInitializedAsync();
|
||||
|
||||
@@ -28,4 +28,7 @@ public class TrackClientDataService : ITrackDataService
|
||||
|
||||
public Task<ApiResult<TrackDto>> GetTrack(string trackId)
|
||||
=> _trackClient.GetTrack(trackId);
|
||||
|
||||
public Task<ApiResult<TrackDto?>> GetRandomTrack()
|
||||
=> _trackClient.GetRandom();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user