Generalize YouTube-backed endpoints behind a source parameter
Removes the last YouTube-specific routes (/youtube/*) and merges them
into the general track/album/playlist endpoints, keyed by a `source`
string validated against TrackSource. This mirrors the earlier track
search merge for albums and playlist-track additions:
- GetAlbums now merges local albums with live YouTube Music search
results, paginated via a youtubeContinuationToken, deduped against
already-materialized ExternalAlbum rows.
- New GET /albums/external/{source}/{externalId} and
GET /tracks/external/{source}/{externalId}/stream replace the
YouTube-only equivalents.
- POST /playlists/{id}/tracks replaces the separate
.../youtube-tracks endpoint, accepting an optional Source/ExternalId
pair alongside TrackId.
- AlbumSearchItemResponse/AlbumsSearchResponse follow the same
discriminated-union + trailing-HasNextPage-field pattern already
used for track search, so HasNextPage stays a required field in the
generated OpenAPI schema.
- Frontend routes renamed accordingly (/albums/youtube/[albumId] ->
/albums/external/[source]/[externalId], etc.) with a single
/api/thumbnail proxy replacing /api/youtube/thumbnail.
Musify.Api.Endpoints.YouTubeEndpoints and the standalone
SearchYouTubeAlbums query are removed as a result.
This commit is contained in:
@@ -1,23 +1,32 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>;
|
||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize, string? YoutubeContinuationToken = null)
|
||||
: IQuery<ErrorOr<AlbumsSearchResponse>>;
|
||||
|
||||
public class GetAlbumsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumsQuery, ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>
|
||||
public class GetAlbumsQueryHandler(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
ILogger<GetAlbumsQueryHandler> logger)
|
||||
: IQueryHandler<GetAlbumsQuery, ErrorOr<AlbumsSearchResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<AlbumApplicationResponse>>> Handle(GetAlbumsQuery request, CancellationToken cancellationToken)
|
||||
// Mirrors GetTracksQueryHandler's threshold: a title shorter than this is too likely to
|
||||
// still be mid-keystroke to justify a live call to the external search API.
|
||||
private const int MinTitleLengthForYouTubeSearch = 2;
|
||||
|
||||
public async ValueTask<ErrorOr<AlbumsSearchResponse>> Handle(GetAlbumsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var albumsQuery = database.UserAlbums
|
||||
var albumsQuery = database.Albums
|
||||
.AsNoTracking()
|
||||
.AsQueryable();
|
||||
|
||||
@@ -43,11 +52,62 @@ namespace Musify.Application.Albums
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedAlbums = new StaticPagedList<AlbumApplicationResponse>(
|
||||
pagedEntities.Select(entry => AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
var localItems = pagedEntities
|
||||
.Select(entry => AlbumSearchItemResponse.FromAlbum(
|
||||
AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)))
|
||||
.ToList();
|
||||
|
||||
return PaginatedResponse<AlbumApplicationResponse>.FromPagedList(pagedAlbums);
|
||||
var knownExternalIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in pagedEntities)
|
||||
{
|
||||
if (entry.Album is ExternalAlbum { Source: TrackSource.YouTube } external)
|
||||
knownExternalIds.Add(external.ExternalId);
|
||||
}
|
||||
|
||||
var youtubeItems = new List<AlbumSearchItemResponse>();
|
||||
string? nextContinuationToken = null;
|
||||
var youtubeUnavailable = false;
|
||||
|
||||
if (request.Title?.Trim().Length >= MinTitleLengthForYouTubeSearch)
|
||||
(youtubeItems, nextContinuationToken, youtubeUnavailable) =
|
||||
await SearchYouTubeAsync(request.Title, request.YoutubeContinuationToken, knownExternalIds, cancellationToken);
|
||||
|
||||
return AlbumsSearchResponse.Create(
|
||||
[.. localItems, .. youtubeItems],
|
||||
pagedEntities.PageNumber,
|
||||
pagedEntities.PageSize,
|
||||
pagedEntities.PageCount,
|
||||
pagedEntities.TotalItemCount,
|
||||
pagedEntities.HasPreviousPage,
|
||||
pagedEntities.HasNextPage,
|
||||
nextContinuationToken,
|
||||
youtubeUnavailable);
|
||||
}
|
||||
|
||||
private async Task<(List<AlbumSearchItemResponse> Items, string? NextContinuationToken, bool Unavailable)> SearchYouTubeAsync(
|
||||
string title,
|
||||
string? continuationToken,
|
||||
HashSet<string> knownExternalIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var searchResult = await youTubeMusicService.SearchAlbumsAsync(title, continuationToken ?? string.Empty, cancellationToken);
|
||||
if (searchResult.IsError)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"YouTube album search unavailable while combining album results: {Error}", searchResult.FirstError.Description);
|
||||
return ([], null, true);
|
||||
}
|
||||
|
||||
var items = searchResult.Value.Items
|
||||
.Where(album => knownExternalIds.Add(album.AlbumId))
|
||||
.Select(AlbumSearchItemResponse.FromYouTubeAlbum)
|
||||
.ToList();
|
||||
|
||||
var nextToken = string.IsNullOrEmpty(searchResult.Value.ContinuationToken)
|
||||
? null
|
||||
: searchResult.Value.ContinuationToken;
|
||||
|
||||
return (items, nextToken, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
/// <summary>One item of a combined local/external album listing. Exactly one of
|
||||
/// <see cref="Album"/> or <see cref="YouTubeAlbum"/> is populated: <see cref="Album"/> for
|
||||
/// anything already in the catalog (locally created albums and external albums materialized
|
||||
/// earlier), <see cref="YouTubeAlbum"/> for a live external search hit that hasn't been
|
||||
/// materialized yet, so it has no album id.</summary>
|
||||
public record AlbumSearchItemResponse(
|
||||
TrackSource Source,
|
||||
AlbumApplicationResponse? Album,
|
||||
YouTubeAlbumResult? YouTubeAlbum)
|
||||
{
|
||||
public static AlbumSearchItemResponse FromAlbum(AlbumApplicationResponse album) =>
|
||||
new(album.YouTubeAlbumId is not null ? TrackSource.YouTube : TrackSource.Local, album, null);
|
||||
|
||||
public static AlbumSearchItemResponse FromYouTubeAlbum(YouTubeAlbumResult album) =>
|
||||
new(TrackSource.YouTube, null, album);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
/// <summary>Result of a combined albums listing/search: a page of local catalog albums
|
||||
/// (user-created and previously materialized external albums), plus, when a search term was
|
||||
/// given, live external hits appended after them. Pagination metadata (<see cref="PageNumber"/>,
|
||||
/// <see cref="PageSize"/>, <see cref="PageCount"/>, <see cref="TotalItemCount"/>) describes only
|
||||
/// the local page — the external source has no stable total, so its continuation is tracked
|
||||
/// separately via <see cref="NextYoutubeContinuationToken"/>.</summary>
|
||||
public record AlbumsSearchResponse(
|
||||
IReadOnlyList<AlbumSearchItemResponse> Items,
|
||||
int PageNumber,
|
||||
int PageSize,
|
||||
int PageCount,
|
||||
int TotalItemCount,
|
||||
bool HasPreviousPage,
|
||||
bool HasNextLocalPage,
|
||||
string? NextYoutubeContinuationToken,
|
||||
bool YoutubeUnavailable,
|
||||
bool HasNextPage)
|
||||
{
|
||||
// HasNextPage is a real field (not a computed property) so it shows up as a required member
|
||||
// of the generated OpenAPI schema, same as every other field here — a get-only property added
|
||||
// outside the primary constructor gets reflected as optional instead, which is never true here.
|
||||
public static AlbumsSearchResponse Create(
|
||||
IReadOnlyList<AlbumSearchItemResponse> items,
|
||||
int pageNumber,
|
||||
int pageSize,
|
||||
int pageCount,
|
||||
int totalItemCount,
|
||||
bool hasPreviousPage,
|
||||
bool hasNextLocalPage,
|
||||
string? nextYoutubeContinuationToken,
|
||||
bool youtubeUnavailable) =>
|
||||
new(items, pageNumber, pageSize, pageCount, totalItemCount, hasPreviousPage, hasNextLocalPage,
|
||||
nextYoutubeContinuationToken, youtubeUnavailable,
|
||||
HasNextPage: hasNextLocalPage || !string.IsNullOrEmpty(nextYoutubeContinuationToken));
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,7 @@ namespace Musify.Application.Tracks
|
||||
(youtubeItems, nextContinuationToken, youtubeUnavailable) =
|
||||
await SearchYouTubeAsync(request.Name, request.YoutubeContinuationToken, knownVideoIds, cancellationToken);
|
||||
|
||||
return new TracksSearchResponse(
|
||||
return TracksSearchResponse.Create(
|
||||
[.. localItems, .. youtubeItems],
|
||||
pagedEntities.PageNumber,
|
||||
pagedEntities.PageSize,
|
||||
|
||||
@@ -15,8 +15,24 @@ namespace Musify.Application.Tracks.Responses
|
||||
bool HasPreviousPage,
|
||||
bool HasNextLocalPage,
|
||||
string? NextYoutubeContinuationToken,
|
||||
bool YoutubeUnavailable)
|
||||
bool YoutubeUnavailable,
|
||||
bool HasNextPage)
|
||||
{
|
||||
public bool HasNextPage => HasNextLocalPage || !string.IsNullOrEmpty(NextYoutubeContinuationToken);
|
||||
// HasNextPage is a real field (not a computed property) so it shows up as a required member
|
||||
// of the generated OpenAPI schema, same as every other field here — a get-only property added
|
||||
// outside the primary constructor gets reflected as optional instead, which is never true here.
|
||||
public static TracksSearchResponse Create(
|
||||
IReadOnlyList<TrackSearchItemResponse> items,
|
||||
int pageNumber,
|
||||
int pageSize,
|
||||
int pageCount,
|
||||
int totalItemCount,
|
||||
bool hasPreviousPage,
|
||||
bool hasNextLocalPage,
|
||||
string? nextYoutubeContinuationToken,
|
||||
bool youtubeUnavailable) =>
|
||||
new(items, pageNumber, pageSize, pageCount, totalItemCount, hasPreviousPage, hasNextLocalPage,
|
||||
nextYoutubeContinuationToken, youtubeUnavailable,
|
||||
HasNextPage: hasNextLocalPage || !string.IsNullOrEmpty(nextYoutubeContinuationToken));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.YouTube
|
||||
{
|
||||
public record SearchYouTubeAlbumsQuery(string Query, string ContinuationToken)
|
||||
: IQuery<ErrorOr<YouTubeAlbumSearchResult>>;
|
||||
|
||||
public class SearchYouTubeAlbumsQueryHandler(IYouTubeMusicService youTubeMusicService)
|
||||
: IQueryHandler<SearchYouTubeAlbumsQuery, ErrorOr<YouTubeAlbumSearchResult>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<YouTubeAlbumSearchResult>> Handle(SearchYouTubeAlbumsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.Query))
|
||||
return Error.Validation(description: "The search query must not be empty.");
|
||||
|
||||
return await youTubeMusicService.SearchAlbumsAsync(request.Query, request.ContinuationToken, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.DataTransferObjects.PlayLists;
|
||||
|
||||
/// <summary>Add a track already in the catalog by <see cref="TrackId"/>, or one from an external
|
||||
/// source by <see cref="Source"/> + <see cref="ExternalId"/> (provisioning it in the background if
|
||||
/// needed) — exactly one of the two must be given.</summary>
|
||||
public record AddPlayListTrackRequest(Guid? TrackId, TrackSource? Source, string? ExternalId);
|
||||
@@ -1,3 +0,0 @@
|
||||
namespace Musify.Api.DataTransferObjects.PlayLists;
|
||||
|
||||
public record AddYouTubeTrackRequest(string VideoId);
|
||||
@@ -7,6 +7,8 @@ using Musify.Application.Albums;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Application.YouTube;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.Endpoints;
|
||||
|
||||
@@ -19,8 +21,8 @@ public static class AlbumEndpoints
|
||||
|
||||
group.MapGet("/", GetAlbums)
|
||||
.WithName("GetAlbums")
|
||||
.WithSummary("Get Paginated Albums.")
|
||||
.Produces<PaginatedResponse<AlbumApplicationResponse>>();
|
||||
.WithSummary("Get Paginated Albums, Combined With Live YouTube Music Results When A Title Filter Is Given.")
|
||||
.Produces<AlbumsSearchResponse>();
|
||||
|
||||
group.MapGet("/{id}", GetAlbumById)
|
||||
.WithName("GetAlbumById")
|
||||
@@ -28,6 +30,12 @@ public static class AlbumEndpoints
|
||||
.Produces<AlbumApplicationResponse>()
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/external/{source}/{externalId}", GetExternalAlbum)
|
||||
.WithName("GetExternalAlbum")
|
||||
.WithSummary("Get An Album From An External Source (Currently Only YouTube Music) With Its Tracklist.")
|
||||
.Produces<YouTubeAlbumDetail>()
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/users/{userId}", GetAlbumsByUserId)
|
||||
.WithName("GetAlbumsByUserId")
|
||||
.WithSummary("Get Paginated Albums For A User.")
|
||||
@@ -100,9 +108,10 @@ public static class AlbumEndpoints
|
||||
CancellationToken cancellationToken,
|
||||
string? title,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
int pageSize = 10,
|
||||
string? youtubeContinuationToken = null)
|
||||
{
|
||||
var result = await mediator.Send(new GetAlbumsQuery(title, pageNumber, pageSize), cancellationToken);
|
||||
var result = await mediator.Send(new GetAlbumsQuery(title, pageNumber, pageSize, youtubeContinuationToken), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
@@ -115,6 +124,19 @@ public static class AlbumEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetExternalAlbum(
|
||||
IMediator mediator,
|
||||
string source,
|
||||
string externalId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Enum.TryParse<TrackSource>(source, ignoreCase: true, out var trackSource) || trackSource != TrackSource.YouTube)
|
||||
return Results.NotFound($"Unknown or unsupported source '{source}'.");
|
||||
|
||||
var result = await mediator.Send(new GetYouTubeAlbumQuery(externalId), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAlbumsByUserId(
|
||||
IMediator mediator,
|
||||
long userId,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using Mediator;
|
||||
using Musify.Application.PlayLists;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Musify.Application.Tracks;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Api.DataTransferObjects.PlayLists;
|
||||
using Musify.Api.Extensions;
|
||||
@@ -84,19 +86,10 @@ public static class PlayListEndpoints
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapPost("/{playlistId}/tracks/{trackId}", AddTrackToPlayList)
|
||||
.WithName("AddTrackToPlayList")
|
||||
.WithSummary("Add A Track To A PlayList.")
|
||||
.RequireAuthorization()
|
||||
.Produces(StatusCodes.Status204NoContent)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status409Conflict);
|
||||
|
||||
group.MapPost("/{playlistId}/youtube-tracks", AddYouTubeTrackToPlayList)
|
||||
.WithName("AddYouTubeTrackToPlayList")
|
||||
.WithSummary("Add A YouTube Track To A PlayList, Downloading It In The Background If Needed.")
|
||||
.AddEndpointFilter<ValidationFilter<AddYouTubeTrackRequest>>()
|
||||
group.MapPost("/{playlistId}/tracks", AddPlayListTrack)
|
||||
.WithName("AddPlayListTrack")
|
||||
.WithSummary("Add A Track To A PlayList, By Id Or By External Source, Provisioning It In The Background If Needed.")
|
||||
.AddEndpointFilter<ValidationFilter<AddPlayListTrackRequest>>()
|
||||
.RequireAuthorization()
|
||||
.Produces<TrackApplicationResponse>(StatusCodes.Status201Created)
|
||||
.ProducesValidationProblem()
|
||||
@@ -225,32 +218,29 @@ public static class PlayListEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> AddTrackToPlayList(
|
||||
private static async Task<IResult> AddPlayListTrack(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
Guid trackId,
|
||||
AddPlayListTrackRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new AddTrackToPlayListCommand(currentUser.RequiredId, playlistId, trackId),
|
||||
cancellationToken);
|
||||
if (request.TrackId is { } trackId)
|
||||
{
|
||||
var addResult = await mediator.Send(
|
||||
new AddTrackToPlayListCommand(currentUser.RequiredId, playlistId, trackId),
|
||||
cancellationToken);
|
||||
if (addResult.IsError)
|
||||
return addResult.ToHttpResult();
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
var trackResult = await mediator.Send(new GetTrackByIdQuery(trackId), cancellationToken);
|
||||
return trackResult.ToCreatedResult(track => $"/tracks/{track.Id}");
|
||||
}
|
||||
|
||||
private static async Task<IResult> AddYouTubeTrackToPlayList(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid playlistId,
|
||||
AddYouTubeTrackRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// The validator guarantees Source/ExternalId are set whenever TrackId isn't, and that Source
|
||||
// is one of the currently supported external sources (only YouTube for now).
|
||||
var result = await mediator.Send(
|
||||
new AddYouTubeTrackToPlayListCommand(
|
||||
currentUser.RequiredId,
|
||||
playlistId,
|
||||
request.VideoId),
|
||||
new AddYouTubeTrackToPlayListCommand(currentUser.RequiredId, playlistId, request.ExternalId!),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToCreatedResult(track => $"/tracks/{track.Id}");
|
||||
|
||||
@@ -3,6 +3,9 @@ using Musify.Application.Tracks;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.YouTube;
|
||||
using Musify.Application.YouTube.Responses;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Api.DataTransferObjects.Tracks;
|
||||
using Musify.Api.Extensions;
|
||||
@@ -41,6 +44,14 @@ public static class TrackEndpoints
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/external/{source}/{externalId}/stream", GetExternalTrackStream)
|
||||
.WithName("GetExternalTrackStream")
|
||||
.WithSummary("Resolve Playback For A Track From An External Source (Currently Only YouTube Music): Server Stream If Downloaded, Direct Stream From The Source Otherwise. Works Anonymously When The Playback Configuration Allows It.")
|
||||
.Produces<YouTubeStreamResponse>()
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status409Conflict);
|
||||
|
||||
group.MapGet("/users/{userId}", GetTracksByUserId)
|
||||
.WithName("GetTracksByUserId")
|
||||
.WithSummary("Get Paginated Tracks For A User.")
|
||||
@@ -129,6 +140,20 @@ public static class TrackEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetExternalTrackStream(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
string source,
|
||||
string externalId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Enum.TryParse<TrackSource>(source, ignoreCase: true, out var trackSource) || trackSource != TrackSource.YouTube)
|
||||
return Results.NotFound($"Unknown or unsupported source '{source}'.");
|
||||
|
||||
var result = await mediator.Send(new ResolveYouTubeTrackStreamCommand(externalId, currentUser.Id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTracksByUserId(
|
||||
IMediator mediator,
|
||||
long userId,
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
using Mediator;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Api.Extensions;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.YouTube;
|
||||
using Musify.Application.YouTube.Responses;
|
||||
|
||||
namespace Musify.Api.Endpoints;
|
||||
|
||||
public static class YouTubeEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapYouTubeEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/youtube")
|
||||
.WithTags("YouTube");
|
||||
|
||||
group.MapGet("/albums", SearchAlbums)
|
||||
.WithName("SearchYouTubeAlbums")
|
||||
.WithSummary("Search Albums On YouTube Music.")
|
||||
.RequireAuthorization()
|
||||
.Produces<YouTubeAlbumSearchResult>()
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.ProducesValidationProblem();
|
||||
|
||||
group.MapGet("/albums/{albumId}", GetAlbum)
|
||||
.WithName("GetYouTubeAlbum")
|
||||
.WithSummary("Get A YouTube Music Album With Its Tracklist.")
|
||||
.RequireAuthorization()
|
||||
.Produces<YouTubeAlbumDetail>()
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/tracks/{videoId}/stream", GetTrackStream)
|
||||
.WithName("GetYouTubeTrackStream")
|
||||
.WithSummary("Resolve Playback For A YouTube Track: Server Stream If Downloaded, Direct YouTube Stream Otherwise. Works Anonymously When The Playback Configuration Allows It.")
|
||||
.Produces<YouTubeStreamResponse>()
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.Produces(StatusCodes.Status409Conflict);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetTrackStream(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
string videoId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new ResolveYouTubeTrackStreamCommand(videoId, currentUser.Id),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> SearchAlbums(
|
||||
IMediator mediator,
|
||||
CancellationToken cancellationToken,
|
||||
string query,
|
||||
string? continuation = null)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new SearchYouTubeAlbumsQuery(query, continuation ?? string.Empty),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetAlbum(
|
||||
IMediator mediator,
|
||||
string albumId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetYouTubeAlbumQuery(albumId), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,7 @@ app
|
||||
.MapMixEndpoints()
|
||||
.MapPlayListEndpoints()
|
||||
.MapTrackEndpoints()
|
||||
.MapUserEndpoints()
|
||||
.MapYouTubeEndpoints();
|
||||
.MapUserEndpoints();
|
||||
|
||||
app.Run();
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using FluentValidation;
|
||||
using Musify.Api.DataTransferObjects.PlayLists;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.Validators.PlayLists;
|
||||
|
||||
public sealed class AddPlayListTrackRequestValidator : AbstractValidator<AddPlayListTrackRequest>
|
||||
{
|
||||
public AddPlayListTrackRequestValidator()
|
||||
{
|
||||
RuleFor(x => x)
|
||||
.Must(x => x.TrackId.HasValue ^ (x.Source.HasValue && !string.IsNullOrEmpty(x.ExternalId)))
|
||||
.WithMessage("Provide either trackId, or source and externalId, but not both.");
|
||||
|
||||
When(x => x.Source.HasValue, () =>
|
||||
{
|
||||
RuleFor(x => x.Source)
|
||||
.Must(source => source == TrackSource.YouTube)
|
||||
.WithMessage("Unsupported source.");
|
||||
|
||||
RuleFor(x => x.ExternalId)
|
||||
.NotEmpty()
|
||||
.Matches("^[A-Za-z0-9_-]{11}$")
|
||||
.WithMessage("externalId must be a valid YouTube video id.");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using FluentValidation;
|
||||
using Musify.Api.DataTransferObjects.PlayLists;
|
||||
|
||||
namespace Musify.Api.Validators.PlayLists;
|
||||
|
||||
public sealed class AddYouTubeTrackRequestValidator : AbstractValidator<AddYouTubeTrackRequest>
|
||||
{
|
||||
public AddYouTubeTrackRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.VideoId)
|
||||
.NotEmpty()
|
||||
.Matches("^[A-Za-z0-9_-]{11}$");
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,22 @@
|
||||
using ErrorOr;
|
||||
using Musify.Application.Albums;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tests.TestSupport;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Application.Tests.Albums
|
||||
{
|
||||
public sealed class GetAlbumsQueryHandlerTests : HandlerTestBase
|
||||
{
|
||||
private GetAlbumsQueryHandler CreateHandler() => new(Database);
|
||||
private readonly IYouTubeMusicService youTubeMusicService = Substitute.For<IYouTubeMusicService>();
|
||||
|
||||
private GetAlbumsQueryHandler CreateHandler() =>
|
||||
new(Database, youTubeMusicService, NoOpLogger<GetAlbumsQueryHandler>());
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NoTitleFilter_ReturnsAllAlbumsPaged()
|
||||
public async Task Handle_NoTitleFilter_ReturnsAllAlbumsPaged_AndDoesNotCallYouTube()
|
||||
{
|
||||
var owner = TestEntities.User();
|
||||
await SeedAsync(owner, TestEntities.UserAlbum(owner.Id, "Alpha"), TestEntities.UserAlbum(owner.Id, "Beta"));
|
||||
@@ -18,19 +25,68 @@ namespace Musify.Application.Tests.Albums
|
||||
|
||||
Assert.False(result.IsError);
|
||||
Assert.Equal(2, result.Value.TotalItemCount);
|
||||
Assert.All(result.Value.Items, item => Assert.NotNull(item.Album));
|
||||
await youTubeMusicService.DidNotReceiveWithAnyArgs()
|
||||
.SearchAlbumsAsync(default!, default!, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_TitleFilter_ReturnsOnlyMatchingAlbums()
|
||||
public async Task Handle_TitleFilter_ReturnsMatchingLocalAlbums_FollowedByYouTubeResults()
|
||||
{
|
||||
var owner = TestEntities.User();
|
||||
await SeedAsync(owner, TestEntities.UserAlbum(owner.Id, "Rock Classics"), TestEntities.UserAlbum(owner.Id, "Jazz Favorites"));
|
||||
|
||||
var album = new YouTubeAlbumResult("album-1", "Rock Classics Reissue", "Various Artists", "thumb.jpg", 2020, false, false, []);
|
||||
youTubeMusicService.SearchAlbumsAsync("rock", string.Empty, Arg.Any<CancellationToken>())
|
||||
.Returns(new YouTubeAlbumSearchResult([album], "next-token"));
|
||||
|
||||
var result = await CreateHandler().Handle(new GetAlbumsQuery(Title: "rock", PageNumber: 1, PageSize: 10), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsError);
|
||||
var album = Assert.Single(result.Value.Items);
|
||||
Assert.Equal("Rock Classics", album.Title);
|
||||
Assert.Equal(2, result.Value.Items.Count);
|
||||
Assert.NotNull(result.Value.Items[0].Album);
|
||||
Assert.Equal("Rock Classics", result.Value.Items[0].Album!.Title);
|
||||
Assert.Null(result.Value.Items[1].Album);
|
||||
Assert.NotNull(result.Value.Items[1].YouTubeAlbum);
|
||||
Assert.Equal("album-1", result.Value.Items[1].YouTubeAlbum!.AlbumId);
|
||||
Assert.Equal("next-token", result.Value.NextYoutubeContinuationToken);
|
||||
Assert.False(result.Value.YoutubeUnavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_TitleFilter_SkipsYouTubeResultAlreadyMaterializedLocally()
|
||||
{
|
||||
var externalAlbum = TestEntities.ExternalAlbum(externalId: "album-1", title: "Rock Classics", source: TrackSource.YouTube);
|
||||
await SeedAsync(externalAlbum);
|
||||
|
||||
var album = new YouTubeAlbumResult("album-1", "Rock Classics", "Various Artists", "thumb.jpg", 2020, false, false, []);
|
||||
youTubeMusicService.SearchAlbumsAsync("rock", string.Empty, Arg.Any<CancellationToken>())
|
||||
.Returns(new YouTubeAlbumSearchResult([album], string.Empty));
|
||||
|
||||
var result = await CreateHandler().Handle(new GetAlbumsQuery(Title: "rock", PageNumber: 1, PageSize: 10), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsError);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.NotNull(item.Album);
|
||||
Assert.Null(item.YouTubeAlbum);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_TitleFilter_YouTubeUnavailable_StillReturnsLocalResults()
|
||||
{
|
||||
var owner = TestEntities.User();
|
||||
await SeedAsync(owner, TestEntities.UserAlbum(owner.Id, "Rock Classics"));
|
||||
|
||||
youTubeMusicService.SearchAlbumsAsync("rock", string.Empty, Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Forbidden(description: "The YouTube Music source is disabled."));
|
||||
|
||||
var result = await CreateHandler().Handle(new GetAlbumsQuery(Title: "rock", PageNumber: 1, PageSize: 10), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsError);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.NotNull(item.Album);
|
||||
Assert.True(result.Value.YoutubeUnavailable);
|
||||
Assert.Null(result.Value.NextYoutubeContinuationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
using ErrorOr;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.YouTube;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Application.Tests.YouTube
|
||||
{
|
||||
public sealed class SearchYouTubeAlbumsQueryHandlerTests
|
||||
{
|
||||
private readonly IYouTubeMusicService youTubeMusicService = Substitute.For<IYouTubeMusicService>();
|
||||
|
||||
private SearchYouTubeAlbumsQueryHandler CreateHandler() => new(youTubeMusicService);
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_EmptyQuery_ReturnsValidationErrorWithoutCallingTheService()
|
||||
{
|
||||
var result = await CreateHandler().Handle(new SearchYouTubeAlbumsQuery(string.Empty, string.Empty), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(ErrorType.Validation, result.FirstError.Type);
|
||||
await youTubeMusicService.DidNotReceiveWithAnyArgs()
|
||||
.SearchAlbumsAsync(default!, default!, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_NonEmptyQuery_DelegatesToTheService()
|
||||
{
|
||||
var expected = new YouTubeAlbumSearchResult([], "next-token");
|
||||
youTubeMusicService.SearchAlbumsAsync("query", "token", Arg.Any<CancellationToken>()).Returns(expected);
|
||||
|
||||
var result = await CreateHandler().Handle(new SearchYouTubeAlbumsQuery("query", "token"), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.False(result.IsError);
|
||||
Assert.Same(expected, result.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user