Design Prot Merge #1
@@ -1,23 +1,32 @@
|
|||||||
using ErrorOr;
|
using ErrorOr;
|
||||||
using Mediator;
|
using Mediator;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
using Musify.Application.Albums.Responses;
|
using Musify.Application.Albums.Responses;
|
||||||
using Musify.Application.Contracts;
|
using Musify.Application.Contracts;
|
||||||
using Musify.Application.Shared;
|
using Musify.Domain.Entities;
|
||||||
|
using Musify.Domain.ValueObjects;
|
||||||
using X.PagedList;
|
using X.PagedList;
|
||||||
using X.PagedList.EF;
|
using X.PagedList.EF;
|
||||||
|
|
||||||
namespace Musify.Application.Albums
|
namespace Musify.Application.Albums
|
||||||
{
|
{
|
||||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize)
|
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize, string? YoutubeContinuationToken = null)
|
||||||
: IQuery<ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>;
|
: IQuery<ErrorOr<AlbumsSearchResponse>>;
|
||||||
|
|
||||||
public class GetAlbumsQueryHandler(IDatabase database)
|
public class GetAlbumsQueryHandler(
|
||||||
: IQueryHandler<GetAlbumsQuery, ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>
|
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()
|
.AsNoTracking()
|
||||||
.AsQueryable();
|
.AsQueryable();
|
||||||
|
|
||||||
@@ -43,11 +52,62 @@ namespace Musify.Application.Albums
|
|||||||
})
|
})
|
||||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||||
|
|
||||||
var pagedAlbums = new StaticPagedList<AlbumApplicationResponse>(
|
var localItems = pagedEntities
|
||||||
pagedEntities.Select(entry => AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)),
|
.Select(entry => AlbumSearchItemResponse.FromAlbum(
|
||||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
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) =
|
(youtubeItems, nextContinuationToken, youtubeUnavailable) =
|
||||||
await SearchYouTubeAsync(request.Name, request.YoutubeContinuationToken, knownVideoIds, cancellationToken);
|
await SearchYouTubeAsync(request.Name, request.YoutubeContinuationToken, knownVideoIds, cancellationToken);
|
||||||
|
|
||||||
return new TracksSearchResponse(
|
return TracksSearchResponse.Create(
|
||||||
[.. localItems, .. youtubeItems],
|
[.. localItems, .. youtubeItems],
|
||||||
pagedEntities.PageNumber,
|
pagedEntities.PageNumber,
|
||||||
pagedEntities.PageSize,
|
pagedEntities.PageSize,
|
||||||
|
|||||||
@@ -15,8 +15,24 @@ namespace Musify.Application.Tracks.Responses
|
|||||||
bool HasPreviousPage,
|
bool HasPreviousPage,
|
||||||
bool HasNextLocalPage,
|
bool HasNextLocalPage,
|
||||||
string? NextYoutubeContinuationToken,
|
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.Albums.Responses;
|
||||||
using Musify.Application.Shared;
|
using Musify.Application.Shared;
|
||||||
using Musify.Application.Tracks.Responses;
|
using Musify.Application.Tracks.Responses;
|
||||||
|
using Musify.Application.YouTube;
|
||||||
|
using Musify.Domain.ValueObjects;
|
||||||
|
|
||||||
namespace Musify.Api.Endpoints;
|
namespace Musify.Api.Endpoints;
|
||||||
|
|
||||||
@@ -19,8 +21,8 @@ public static class AlbumEndpoints
|
|||||||
|
|
||||||
group.MapGet("/", GetAlbums)
|
group.MapGet("/", GetAlbums)
|
||||||
.WithName("GetAlbums")
|
.WithName("GetAlbums")
|
||||||
.WithSummary("Get Paginated Albums.")
|
.WithSummary("Get Paginated Albums, Combined With Live YouTube Music Results When A Title Filter Is Given.")
|
||||||
.Produces<PaginatedResponse<AlbumApplicationResponse>>();
|
.Produces<AlbumsSearchResponse>();
|
||||||
|
|
||||||
group.MapGet("/{id}", GetAlbumById)
|
group.MapGet("/{id}", GetAlbumById)
|
||||||
.WithName("GetAlbumById")
|
.WithName("GetAlbumById")
|
||||||
@@ -28,6 +30,12 @@ public static class AlbumEndpoints
|
|||||||
.Produces<AlbumApplicationResponse>()
|
.Produces<AlbumApplicationResponse>()
|
||||||
.Produces(StatusCodes.Status404NotFound);
|
.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)
|
group.MapGet("/users/{userId}", GetAlbumsByUserId)
|
||||||
.WithName("GetAlbumsByUserId")
|
.WithName("GetAlbumsByUserId")
|
||||||
.WithSummary("Get Paginated Albums For A User.")
|
.WithSummary("Get Paginated Albums For A User.")
|
||||||
@@ -100,9 +108,10 @@ public static class AlbumEndpoints
|
|||||||
CancellationToken cancellationToken,
|
CancellationToken cancellationToken,
|
||||||
string? title,
|
string? title,
|
||||||
int pageNumber = 1,
|
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();
|
return result.ToHttpResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,6 +124,19 @@ public static class AlbumEndpoints
|
|||||||
return result.ToHttpResult();
|
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(
|
private static async Task<IResult> GetAlbumsByUserId(
|
||||||
IMediator mediator,
|
IMediator mediator,
|
||||||
long userId,
|
long userId,
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
using Musify.Application.PlayLists;
|
using Musify.Application.PlayLists;
|
||||||
using Musify.Application.PlayLists.Responses;
|
using Musify.Application.PlayLists.Responses;
|
||||||
|
using Musify.Application.Tracks;
|
||||||
using Musify.Application.Tracks.Responses;
|
using Musify.Application.Tracks.Responses;
|
||||||
using Musify.Application.Shared;
|
using Musify.Application.Shared;
|
||||||
using Musify.Application.Contracts;
|
using Musify.Application.Contracts;
|
||||||
|
using Musify.Domain.ValueObjects;
|
||||||
using Musify.Api.Authentication;
|
using Musify.Api.Authentication;
|
||||||
using Musify.Api.DataTransferObjects.PlayLists;
|
using Musify.Api.DataTransferObjects.PlayLists;
|
||||||
using Musify.Api.Extensions;
|
using Musify.Api.Extensions;
|
||||||
@@ -84,19 +86,10 @@ public static class PlayListEndpoints
|
|||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.Produces(StatusCodes.Status404NotFound);
|
.Produces(StatusCodes.Status404NotFound);
|
||||||
|
|
||||||
group.MapPost("/{playlistId}/tracks/{trackId}", AddTrackToPlayList)
|
group.MapPost("/{playlistId}/tracks", AddPlayListTrack)
|
||||||
.WithName("AddTrackToPlayList")
|
.WithName("AddPlayListTrack")
|
||||||
.WithSummary("Add A Track To A PlayList.")
|
.WithSummary("Add A Track To A PlayList, By Id Or By External Source, Provisioning It In The Background If Needed.")
|
||||||
.RequireAuthorization()
|
.AddEndpointFilter<ValidationFilter<AddPlayListTrackRequest>>()
|
||||||
.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>>()
|
|
||||||
.RequireAuthorization()
|
.RequireAuthorization()
|
||||||
.Produces<TrackApplicationResponse>(StatusCodes.Status201Created)
|
.Produces<TrackApplicationResponse>(StatusCodes.Status201Created)
|
||||||
.ProducesValidationProblem()
|
.ProducesValidationProblem()
|
||||||
@@ -225,32 +218,29 @@ public static class PlayListEndpoints
|
|||||||
return result.ToHttpResult();
|
return result.ToHttpResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static async Task<IResult> AddTrackToPlayList(
|
private static async Task<IResult> AddPlayListTrack(
|
||||||
IMediator mediator,
|
IMediator mediator,
|
||||||
CurrentUser currentUser,
|
CurrentUser currentUser,
|
||||||
Guid playlistId,
|
Guid playlistId,
|
||||||
Guid trackId,
|
AddPlayListTrackRequest request,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var result = await mediator.Send(
|
if (request.TrackId is { } trackId)
|
||||||
new AddTrackToPlayListCommand(currentUser.RequiredId, playlistId, trackId),
|
{
|
||||||
cancellationToken);
|
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(
|
// The validator guarantees Source/ExternalId are set whenever TrackId isn't, and that Source
|
||||||
IMediator mediator,
|
// is one of the currently supported external sources (only YouTube for now).
|
||||||
CurrentUser currentUser,
|
|
||||||
Guid playlistId,
|
|
||||||
AddYouTubeTrackRequest request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var result = await mediator.Send(
|
var result = await mediator.Send(
|
||||||
new AddYouTubeTrackToPlayListCommand(
|
new AddYouTubeTrackToPlayListCommand(currentUser.RequiredId, playlistId, request.ExternalId!),
|
||||||
currentUser.RequiredId,
|
|
||||||
playlistId,
|
|
||||||
request.VideoId),
|
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
return result.ToCreatedResult(track => $"/tracks/{track.Id}");
|
return result.ToCreatedResult(track => $"/tracks/{track.Id}");
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ using Musify.Application.Tracks;
|
|||||||
using Musify.Application.Tracks.Responses;
|
using Musify.Application.Tracks.Responses;
|
||||||
using Musify.Application.Shared;
|
using Musify.Application.Shared;
|
||||||
using Musify.Application.Contracts;
|
using Musify.Application.Contracts;
|
||||||
|
using Musify.Application.YouTube;
|
||||||
|
using Musify.Application.YouTube.Responses;
|
||||||
|
using Musify.Domain.ValueObjects;
|
||||||
using Musify.Api.Authentication;
|
using Musify.Api.Authentication;
|
||||||
using Musify.Api.DataTransferObjects.Tracks;
|
using Musify.Api.DataTransferObjects.Tracks;
|
||||||
using Musify.Api.Extensions;
|
using Musify.Api.Extensions;
|
||||||
@@ -41,6 +44,14 @@ public static class TrackEndpoints
|
|||||||
.Produces(StatusCodes.Status401Unauthorized)
|
.Produces(StatusCodes.Status401Unauthorized)
|
||||||
.Produces(StatusCodes.Status404NotFound);
|
.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)
|
group.MapGet("/users/{userId}", GetTracksByUserId)
|
||||||
.WithName("GetTracksByUserId")
|
.WithName("GetTracksByUserId")
|
||||||
.WithSummary("Get Paginated Tracks For A User.")
|
.WithSummary("Get Paginated Tracks For A User.")
|
||||||
@@ -129,6 +140,20 @@ public static class TrackEndpoints
|
|||||||
return result.ToHttpResult();
|
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(
|
private static async Task<IResult> GetTracksByUserId(
|
||||||
IMediator mediator,
|
IMediator mediator,
|
||||||
long userId,
|
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()
|
.MapMixEndpoints()
|
||||||
.MapPlayListEndpoints()
|
.MapPlayListEndpoints()
|
||||||
.MapTrackEndpoints()
|
.MapTrackEndpoints()
|
||||||
.MapUserEndpoints()
|
.MapUserEndpoints();
|
||||||
.MapYouTubeEndpoints();
|
|
||||||
|
|
||||||
app.Run();
|
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.Albums;
|
||||||
|
using Musify.Application.Contracts;
|
||||||
using Musify.Application.Tests.TestSupport;
|
using Musify.Application.Tests.TestSupport;
|
||||||
|
using Musify.Domain.ValueObjects;
|
||||||
|
using NSubstitute;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace Musify.Application.Tests.Albums
|
namespace Musify.Application.Tests.Albums
|
||||||
{
|
{
|
||||||
public sealed class GetAlbumsQueryHandlerTests : HandlerTestBase
|
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]
|
[Fact]
|
||||||
public async Task Handle_NoTitleFilter_ReturnsAllAlbumsPaged()
|
public async Task Handle_NoTitleFilter_ReturnsAllAlbumsPaged_AndDoesNotCallYouTube()
|
||||||
{
|
{
|
||||||
var owner = TestEntities.User();
|
var owner = TestEntities.User();
|
||||||
await SeedAsync(owner, TestEntities.UserAlbum(owner.Id, "Alpha"), TestEntities.UserAlbum(owner.Id, "Beta"));
|
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.False(result.IsError);
|
||||||
Assert.Equal(2, result.Value.TotalItemCount);
|
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]
|
[Fact]
|
||||||
public async Task Handle_TitleFilter_ReturnsOnlyMatchingAlbums()
|
public async Task Handle_TitleFilter_ReturnsMatchingLocalAlbums_FollowedByYouTubeResults()
|
||||||
{
|
{
|
||||||
var owner = TestEntities.User();
|
var owner = TestEntities.User();
|
||||||
await SeedAsync(owner, TestEntities.UserAlbum(owner.Id, "Rock Classics"), TestEntities.UserAlbum(owner.Id, "Jazz Favorites"));
|
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);
|
var result = await CreateHandler().Handle(new GetAlbumsQuery(Title: "rock", PageNumber: 1, PageSize: 10), TestContext.Current.CancellationToken);
|
||||||
|
|
||||||
Assert.False(result.IsError);
|
Assert.False(result.IsError);
|
||||||
var album = Assert.Single(result.Value.Items);
|
Assert.Equal(2, result.Value.Items.Count);
|
||||||
Assert.Equal("Rock Classics", album.Title);
|
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]
|
[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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,7 +16,7 @@ export async function fetchAlbumQueueItems(
|
|||||||
return toQueueItems(data.items ?? []);
|
return toQueueItems(data.items ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch(`/api/albums/youtube/${albumId}/tracks`);
|
const res = await fetch(`/api/albums/external/${kind}/${albumId}/tracks`);
|
||||||
if (!res.ok) return [];
|
if (!res.ok) return [];
|
||||||
const detail = (await res.json()) as YouTubeAlbumTracksResponse;
|
const detail = (await res.json()) as YouTubeAlbumTracksResponse;
|
||||||
return detail.tracks.map((track) => ({
|
return detail.tracks.map((track) => ({
|
||||||
|
|||||||
@@ -305,7 +305,7 @@ class PlayerState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async #resolveYouTubeSrc(videoId: string): Promise<string> {
|
async #resolveYouTubeSrc(videoId: string): Promise<string> {
|
||||||
const res = await fetch(`/api/youtube/tracks/${videoId}/stream`);
|
const res = await fetch(`/api/tracks/external/youtube/${videoId}/stream`);
|
||||||
if (!res.ok) throw new Error(await readErrorMessage(res));
|
if (!res.ok) throw new Error(await readErrorMessage(res));
|
||||||
const { mode, streamUrl, ticket } = (await res.json()) as {
|
const { mode, streamUrl, ticket } = (await res.json()) as {
|
||||||
mode: string;
|
mode: string;
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ export async function addTrackAction({ request, params, locals, fetch }: Request
|
|||||||
}
|
}
|
||||||
|
|
||||||
const api = createApiClient({ fetch, accessToken });
|
const api = createApiClient({ fetch, accessToken });
|
||||||
const { error: err, response } = await api.POST('/playlists/{playlistId}/tracks/{trackId}', {
|
const { error: err, response } = await api.POST('/playlists/{playlistId}/tracks', {
|
||||||
params: { path: { playlistId, trackId } }
|
params: { path: { playlistId } },
|
||||||
|
body: { trackId, source: null, externalId: null }
|
||||||
});
|
});
|
||||||
|
|
||||||
if (err) {
|
if (err) {
|
||||||
@@ -36,19 +37,15 @@ export async function addYouTubeToPlaylistAction({ request, params, locals, fetc
|
|||||||
const form = await request.formData();
|
const form = await request.formData();
|
||||||
const playlistId = String(form.get('playlistId') ?? '') || String(params.id ?? '');
|
const playlistId = String(form.get('playlistId') ?? '') || String(params.id ?? '');
|
||||||
const videoId = String(form.get('videoId') ?? '');
|
const videoId = String(form.get('videoId') ?? '');
|
||||||
const title = String(form.get('title') ?? '');
|
|
||||||
const artist = String(form.get('artist') ?? '');
|
|
||||||
const durationSeconds = Number(form.get('durationSeconds') ?? 0);
|
|
||||||
const thumbnailUrl = String(form.get('thumbnailUrl') ?? '');
|
|
||||||
|
|
||||||
if (!playlistId || !videoId || !title) {
|
if (!playlistId || !videoId) {
|
||||||
return fail(400, { message: 'Faltan datos de la canción.' });
|
return fail(400, { message: 'Faltan datos de la canción.' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const api = createApiClient({ fetch, accessToken });
|
const api = createApiClient({ fetch, accessToken });
|
||||||
const { error: err, response } = await api.POST('/playlists/{playlistId}/youtube-tracks', {
|
const { error: err, response } = await api.POST('/playlists/{playlistId}/tracks', {
|
||||||
params: { path: { playlistId } },
|
params: { path: { playlistId } },
|
||||||
body: { videoId, title, artist, durationSeconds, thumbnailUrl }
|
body: { trackId: null, source: 'YouTube', externalId: videoId }
|
||||||
});
|
});
|
||||||
|
|
||||||
if (err) {
|
if (err) {
|
||||||
@@ -84,8 +81,9 @@ export async function addAlbumToPlaylistAction({ request, params, locals, fetch
|
|||||||
|
|
||||||
let added = 0;
|
let added = 0;
|
||||||
for (const track of tracks.items) {
|
for (const track of tracks.items) {
|
||||||
const { error: err } = await api.POST('/playlists/{playlistId}/tracks/{trackId}', {
|
const { error: err } = await api.POST('/playlists/{playlistId}/tracks', {
|
||||||
params: { path: { playlistId, trackId: String(track.id) } }
|
params: { path: { playlistId } },
|
||||||
|
body: { trackId: String(track.id), source: null, externalId: null }
|
||||||
});
|
});
|
||||||
if (!err) added++;
|
if (!err) added++;
|
||||||
}
|
}
|
||||||
@@ -111,8 +109,8 @@ export async function addYoutubeAlbumToPlaylistAction({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const api = createApiClient({ fetch, accessToken });
|
const api = createApiClient({ fetch, accessToken });
|
||||||
const { data: detail, error: detailErr } = await api.GET('/youtube/albums/{albumId}', {
|
const { data: detail, error: detailErr } = await api.GET('/albums/external/{source}/{externalId}', {
|
||||||
params: { path: { albumId } }
|
params: { path: { source: 'YouTube', externalId: albumId } }
|
||||||
});
|
});
|
||||||
|
|
||||||
if (detailErr || !detail) {
|
if (detailErr || !detail) {
|
||||||
@@ -121,15 +119,9 @@ export async function addYoutubeAlbumToPlaylistAction({
|
|||||||
|
|
||||||
let added = 0;
|
let added = 0;
|
||||||
for (const track of detail.tracks) {
|
for (const track of detail.tracks) {
|
||||||
const { error: err } = await api.POST('/playlists/{playlistId}/youtube-tracks', {
|
const { error: err } = await api.POST('/playlists/{playlistId}/tracks', {
|
||||||
params: { path: { playlistId } },
|
params: { path: { playlistId } },
|
||||||
body: {
|
body: { trackId: null, source: 'YouTube', externalId: track.videoId }
|
||||||
videoId: track.videoId,
|
|
||||||
title: track.title,
|
|
||||||
artist: detail.album.artist,
|
|
||||||
durationSeconds: Number(track.durationSeconds),
|
|
||||||
thumbnailUrl: detail.album.thumbnailUrl
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
if (!err) added++;
|
if (!err) added++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export const THUMBNAIL_SIZES = {
|
|||||||
|
|
||||||
export type ThumbnailSize = keyof typeof THUMBNAIL_SIZES;
|
export type ThumbnailSize = keyof typeof THUMBNAIL_SIZES;
|
||||||
|
|
||||||
const PROXY_PATH = '/api/youtube/thumbnail';
|
const PROXY_PATH = '/api/thumbnail';
|
||||||
|
|
||||||
export function thumbnailSrc(
|
export function thumbnailSrc(
|
||||||
url: string | undefined,
|
url: string | undefined,
|
||||||
|
|||||||
+4
-2
@@ -10,13 +10,15 @@ export const load: PageServerLoad = async ({ params, locals, url, fetch }) => {
|
|||||||
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
|
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
|
||||||
|
|
||||||
const [albumRes, playlistsRes] = await Promise.all([
|
const [albumRes, playlistsRes] = await Promise.all([
|
||||||
api.GET('/youtube/albums/{albumId}', { params: { path: { albumId: params.albumId } } }),
|
api.GET('/albums/external/{source}/{externalId}', {
|
||||||
|
params: { path: { source: params.source, externalId: params.externalId } }
|
||||||
|
}),
|
||||||
api.GET('/playlists/users/{userId}', {
|
api.GET('/playlists/users/{userId}', {
|
||||||
params: { path: { userId: user.sub }, query: { pageNumber: 1, pageSize: 50 } }
|
params: { path: { userId: user.sub }, query: { pageNumber: 1, pageSize: 50 } }
|
||||||
})
|
})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const album = unwrapOrError(albumRes, 'No se pudo cargar el álbum de YouTube Music.', 404);
|
const album = unwrapOrError(albumRes, 'No se pudo cargar el álbum.', 404);
|
||||||
|
|
||||||
return { album, playlists: playlistsRes.data?.items ?? [], section: null };
|
return { album, playlists: playlistsRes.data?.items ?? [], section: null };
|
||||||
};
|
};
|
||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
EXPLORE_ALBUMS_PAGE_SIZE,
|
EXPLORE_ALBUMS_PAGE_SIZE,
|
||||||
EXPLORE_PAGE_SIZE as PAGE_SIZE,
|
EXPLORE_PAGE_SIZE as PAGE_SIZE,
|
||||||
SEARCH_MIN_LENGTH,
|
|
||||||
YOUTUBE_FILLER_LIMIT
|
YOUTUBE_FILLER_LIMIT
|
||||||
} from '$lib/config';
|
} from '$lib/config';
|
||||||
import { searchUsers } from '$lib/server/userDirectory';
|
import { searchUsers } from '$lib/server/userDirectory';
|
||||||
@@ -36,25 +35,21 @@ export const load: PageServerLoad = async ({ url, locals, fetch }) => {
|
|||||||
})
|
})
|
||||||
: Promise.resolve(null);
|
: Promise.resolve(null);
|
||||||
|
|
||||||
const youtubeAlbumsPromise =
|
const [tracksRes, playlistsRes, albumsRes] = await Promise.all([
|
||||||
query.length >= SEARCH_MIN_LENGTH
|
|
||||||
? api.GET('/youtube/albums', { params: { query: { query } } })
|
|
||||||
: Promise.resolve(null);
|
|
||||||
|
|
||||||
const [tracksRes, playlistsRes, albumsRes, youtubeAlbumsRes] = await Promise.all([
|
|
||||||
tracksPromise,
|
tracksPromise,
|
||||||
playlistsPromise,
|
playlistsPromise,
|
||||||
albumsPromise,
|
albumsPromise
|
||||||
youtubeAlbumsPromise
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const tracks = unwrapOrError(tracksRes, 'No se pudieron cargar las canciones.');
|
const tracks = unwrapOrError(tracksRes, 'No se pudieron cargar las canciones.');
|
||||||
|
|
||||||
|
const albumItems = albumsRes?.data?.items ?? [];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
query,
|
query,
|
||||||
tracks,
|
tracks,
|
||||||
albums: albumsRes?.data?.items ?? [],
|
albums: albumItems.flatMap((item) => (item.album ? [item.album] : [])),
|
||||||
youtubeAlbums: youtubeAlbumsRes?.data?.items ?? [],
|
youtubeAlbums: albumItems.flatMap((item) => (item.youTubeAlbum ? [item.youTubeAlbum] : [])),
|
||||||
users: searchUsers(query),
|
users: searchUsers(query),
|
||||||
youtubeFiller: query
|
youtubeFiller: query
|
||||||
? Promise.resolve(null)
|
? Promise.resolve(null)
|
||||||
|
|||||||
@@ -282,7 +282,7 @@
|
|||||||
</a>
|
</a>
|
||||||
{:else}
|
{:else}
|
||||||
<a
|
<a
|
||||||
href="/albums/youtube/{entry.album.albumId}"
|
href="/albums/external/youtube/{entry.album.albumId}"
|
||||||
class="group/card animate-enter block min-w-0 rounded-art focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-bg focus-visible:outline-none"
|
class="group/card animate-enter block min-w-0 rounded-art focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-bg focus-visible:outline-none"
|
||||||
style="animation-delay:{Math.min(i, 10) * 45}ms"
|
style="animation-delay:{Math.min(i, 10) * 45}ms"
|
||||||
oncontextmenu={(e) => openAlbumMenu(e, 'youtube', entry.album.albumId)}
|
oncontextmenu={(e) => openAlbumMenu(e, 'youtube', entry.album.albumId)}
|
||||||
|
|||||||
@@ -215,7 +215,7 @@
|
|||||||
{#each albums as album, i (album.id)}
|
{#each albums as album, i (album.id)}
|
||||||
<a
|
<a
|
||||||
href={album.youTubeAlbumId
|
href={album.youTubeAlbumId
|
||||||
? `/albums/youtube/${album.youTubeAlbumId}`
|
? `/albums/external/youtube/${album.youTubeAlbumId}`
|
||||||
: `/albums/${album.id}`}
|
: `/albums/${album.id}`}
|
||||||
class="group/card animate-enter block w-42 shrink-0 rounded-art focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-bg focus-visible:outline-none"
|
class="group/card animate-enter block w-42 shrink-0 rounded-art focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-bg focus-visible:outline-none"
|
||||||
style="animation-delay:{Math.min(i, 10) * 45}ms"
|
style="animation-delay:{Math.min(i, 10) * 45}ms"
|
||||||
|
|||||||
+3
-3
@@ -4,9 +4,9 @@ import { createApiClient, unwrapOrError } from '$lib/server/api';
|
|||||||
|
|
||||||
export const GET: RequestHandler = async ({ params, locals, fetch }) => {
|
export const GET: RequestHandler = async ({ params, locals, fetch }) => {
|
||||||
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
|
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
|
||||||
const result = await api.GET('/youtube/albums/{albumId}', {
|
const result = await api.GET('/albums/external/{source}/{externalId}', {
|
||||||
params: { path: { albumId: params.albumId } }
|
params: { path: { source: params.source, externalId: params.externalId } }
|
||||||
});
|
});
|
||||||
|
|
||||||
return json(unwrapOrError(result, 'No se pudo cargar el álbum de YouTube.'));
|
return json(unwrapOrError(result, 'No se pudo cargar el álbum.'));
|
||||||
};
|
};
|
||||||
+3
-3
@@ -6,9 +6,9 @@ export const GET: RequestHandler = async ({ params, locals, fetch }) => {
|
|||||||
const accessToken = requireAccessToken(locals, 'Inicia sesión para reproducir.');
|
const accessToken = requireAccessToken(locals, 'Inicia sesión para reproducir.');
|
||||||
|
|
||||||
const api = createApiClient({ fetch, accessToken });
|
const api = createApiClient({ fetch, accessToken });
|
||||||
const result = await api.GET('/youtube/tracks/{videoId}/stream', {
|
const result = await api.GET('/tracks/external/{source}/{externalId}/stream', {
|
||||||
params: { path: { videoId: params.videoId } }
|
params: { path: { source: params.source, externalId: params.externalId } }
|
||||||
});
|
});
|
||||||
|
|
||||||
return json(unwrapOrError(result, 'No se pudo obtener el stream de YouTube.'));
|
return json(unwrapOrError(result, 'No se pudo obtener el stream.'));
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user