Add likes, follows and playlist visibility; redesign web-player UI
Backend: - New Likes feature (toggle/get liked tracks) and endpoints - User follow/unfollow, listening stats, public user profile - Playlist visibility (public/private) support - Various auth and DTO/response adjustments to support the above Frontend (web-player): - New design system pass: theme tokens/mode (light/dark), glass menu, tabs bar, player dock/extras/queue components, mix tiles, artist link - New routes: Liked, public user profile (/u/[id]), likes API proxy - Search refactor: shared SearchBox component used by TopBar and MobileHeader (search now reachable on mobile), live results as you type instead of requiring Enter, dropped the "Buscando…" quick-result preview - Removed now-unused components (MobileNav, CoverBadge, MixBentoTile, PlayPauseOverlay, SuggestionsTable, userDirectory) - Design handoff reference docs added under web-player/design_handoff_musify_player and web-player/docs/design-system-refactor-plan.md
This commit is contained in:
@@ -18,6 +18,7 @@ public static class AuthenticationExtensions
|
||||
serviceProvider.GetRequiredService<IOptions<AuthenticationConfiguration>>().Value);
|
||||
|
||||
services.AddMemoryCache();
|
||||
services.AddHttpClient();
|
||||
services.AddScoped<JwtBearerEventsHandler>();
|
||||
services.ConfigureOptions<JwtBearerOptionsSetup>();
|
||||
|
||||
|
||||
@@ -2,17 +2,30 @@ using Mediator;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Musify.Application.Users;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public sealed class JwtBearerEventsHandler(
|
||||
IMediator mediator,
|
||||
IMemoryCache cache,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
AuthenticationConfiguration authenticationConfiguration,
|
||||
ILogger<JwtBearerEventsHandler> logger) : JwtBearerEvents
|
||||
{
|
||||
private static readonly TimeSpan UserSyncCacheTtl = TimeSpan.FromMinutes(15);
|
||||
|
||||
private sealed record UserInfoResponse(
|
||||
[property: JsonPropertyName("name")] string? Name,
|
||||
[property: JsonPropertyName("preferred_username")] string? PreferredUsername,
|
||||
[property: JsonPropertyName("email")] string? Email,
|
||||
[property: JsonPropertyName("given_name")] string? GivenName,
|
||||
[property: JsonPropertyName("family_name")] string? FamilyName,
|
||||
[property: JsonPropertyName("picture")] string? Picture);
|
||||
|
||||
public override async Task TokenValidated(TokenValidatedContext tokenValidatedContext)
|
||||
{
|
||||
var principal = tokenValidatedContext.Principal!;
|
||||
@@ -28,14 +41,30 @@ public sealed class JwtBearerEventsHandler(
|
||||
if (cache.TryGetValue(cacheKey, out _))
|
||||
return;
|
||||
|
||||
var username = principal.FindFirstValue(ClaimTypes.Name)
|
||||
// Access tokens from the IdP are minimal (just sub/scope/aud) — profile attributes live on
|
||||
// the userinfo endpoint, so ask for them there instead of relying on token claims alone.
|
||||
var userInfo = await FetchUserInfoAsync(tokenValidatedContext, tokenValidatedContext.HttpContext.RequestAborted);
|
||||
|
||||
// Zitadel also issues short-form JWT claim names ("name", "given_name", "family_name", "email"),
|
||||
// but the newer JsonWebTokenHandler (default since .NET 8) no longer auto-maps those to the
|
||||
// legacy ClaimTypes.* URIs the way JwtSecurityTokenHandler used to — so check both forms too.
|
||||
var username = userInfo?.Name
|
||||
?? userInfo?.PreferredUsername
|
||||
?? principal.FindFirstValue("name")
|
||||
?? principal.FindFirstValue(ClaimTypes.Name)
|
||||
?? principal.FindFirstValue("preferred_username")
|
||||
?? userInfo?.Email
|
||||
?? principal.FindFirstValue("email")
|
||||
?? principal.FindFirstValue(ClaimTypes.Email)
|
||||
?? rawId!;
|
||||
|
||||
var firstName = principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
var lastName = principal.FindFirstValue(ClaimTypes.Surname);
|
||||
var profilePictureUrl = principal.FindFirstValue("picture");
|
||||
var firstName = userInfo?.GivenName
|
||||
?? principal.FindFirstValue("given_name")
|
||||
?? principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
var lastName = userInfo?.FamilyName
|
||||
?? principal.FindFirstValue("family_name")
|
||||
?? principal.FindFirstValue(ClaimTypes.Surname);
|
||||
var profilePictureUrl = userInfo?.Picture ?? principal.FindFirstValue("picture");
|
||||
|
||||
try
|
||||
{
|
||||
@@ -51,6 +80,43 @@ public sealed class JwtBearerEventsHandler(
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<UserInfoResponse?> FetchUserInfoAsync(
|
||||
TokenValidatedContext tokenValidatedContext, CancellationToken cancellationToken)
|
||||
{
|
||||
var authorizationHeader = tokenValidatedContext.HttpContext.Request.Headers.Authorization.ToString();
|
||||
if (!authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
|
||||
var accessToken = authorizationHeader["Bearer ".Length..].Trim();
|
||||
if (accessToken.Length == 0)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
var client = httpClientFactory.CreateClient();
|
||||
var request = new HttpRequestMessage(
|
||||
HttpMethod.Get,
|
||||
$"{authenticationConfiguration.IssuerAddress.TrimEnd('/')}/oidc/v1/userinfo")
|
||||
{
|
||||
Headers = { Authorization = new AuthenticationHeaderValue("Bearer", accessToken) }
|
||||
};
|
||||
|
||||
var response = await client.SendAsync(request, cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger.LogDebug("Userinfo request returned {StatusCode}", response.StatusCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.Content.ReadFromJsonAsync<UserInfoResponse>(cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Failed to fetch userinfo from identity provider");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public override Task AuthenticationFailed(AuthenticationFailedContext context)
|
||||
{
|
||||
logger.LogWarning(context.Exception, "JWT authentication failed");
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.DataTransferObjects.Likes;
|
||||
|
||||
/// <summary>Toggle a like on 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 ToggleLikeRequest(Guid? TrackId, TrackSource? Source, string? ExternalId);
|
||||
@@ -1,6 +1,9 @@
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.DataTransferObjects.PlayLists;
|
||||
|
||||
public record CreatePlayListRequest(
|
||||
string Name,
|
||||
string? Description,
|
||||
Guid? PictureIntentId);
|
||||
Guid? PictureIntentId,
|
||||
PlaylistVisibility Visibility = PlaylistVisibility.Private);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.DataTransferObjects.PlayLists;
|
||||
|
||||
public record UpdatePlayListRequest(
|
||||
string? NewName,
|
||||
string? NewDescription,
|
||||
Guid? NewPictureIntentId);
|
||||
Guid? NewPictureIntentId,
|
||||
PlaylistVisibility? NewVisibility = null);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
using Mediator;
|
||||
using Musify.Application.Likes;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Api.DataTransferObjects.Likes;
|
||||
using Musify.Api.Extensions;
|
||||
using Musify.Api.Filters;
|
||||
|
||||
namespace Musify.Api.Endpoints;
|
||||
|
||||
public static class LikeEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapLikeEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/likes")
|
||||
.WithTags("Likes")
|
||||
.RequireAuthorization();
|
||||
|
||||
group.MapGet("/", GetLikedTracks)
|
||||
.WithName("GetLikedTracks")
|
||||
.WithSummary("Get The Current User'S Liked Tracks.")
|
||||
.Produces<PaginatedResponse<TrackApplicationResponse>>()
|
||||
.Produces(StatusCodes.Status401Unauthorized);
|
||||
|
||||
group.MapPost("/toggle", ToggleTrackLike)
|
||||
.WithName("ToggleTrackLike")
|
||||
.WithSummary("Like Or Unlike A Track, By Id Or By External Source, Provisioning It In The Background If Needed.")
|
||||
.AddEndpointFilter<ValidationFilter<ToggleLikeRequest>>()
|
||||
.Produces<bool>()
|
||||
.ProducesValidationProblem()
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetLikedTracks(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
CancellationToken cancellationToken,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
{
|
||||
var result = await mediator.Send(new GetLikedTracksQuery(currentUser.RequiredId, pageNumber, pageSize), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ToggleTrackLike(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
ToggleLikeRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new ToggleTrackLikeCommand(currentUser.RequiredId, request.TrackId, request.Source, request.ExternalId),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
}
|
||||
@@ -120,10 +120,11 @@ public static class PlayListEndpoints
|
||||
|
||||
private static async Task<IResult> GetPlayListById(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListByIdQuery(id), cancellationToken);
|
||||
var result = await mediator.Send(new GetPlayListByIdQuery(id, currentUser.Id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
@@ -133,9 +134,10 @@ public static class PlayListEndpoints
|
||||
CancellationToken cancellationToken,
|
||||
string? name,
|
||||
int pageNumber = 1,
|
||||
int pageSize = 10)
|
||||
int pageSize = 10,
|
||||
bool onlyPublic = false)
|
||||
{
|
||||
var result = await mediator.Send(new GetPlayListsByUserIdQuery(userId, name, pageNumber, pageSize), cancellationToken);
|
||||
var result = await mediator.Send(new GetPlayListsByUserIdQuery(userId, name, pageNumber, pageSize, onlyPublic), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
@@ -175,7 +177,7 @@ public static class PlayListEndpoints
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new CreatePlayListCommand(currentUser.RequiredId, request.Name, request.Description, request.PictureIntentId),
|
||||
new CreatePlayListCommand(currentUser.RequiredId, request.Name, request.Description, request.PictureIntentId, request.Visibility),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToCreatedResult(playList => $"/playlists/{playList.Id}");
|
||||
@@ -189,7 +191,7 @@ public static class PlayListEndpoints
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(
|
||||
new UpdatePlayListCommand(currentUser.RequiredId, playlistId, request.NewName, request.NewDescription, request.NewPictureIntentId),
|
||||
new UpdatePlayListCommand(currentUser.RequiredId, playlistId, request.NewName, request.NewDescription, request.NewPictureIntentId, request.NewVisibility),
|
||||
cancellationToken);
|
||||
|
||||
return result.ToHttpResult();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Mediator;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Api.DataTransferObjects.Users;
|
||||
using Musify.Api.Extensions;
|
||||
using Musify.Api.Filters;
|
||||
@@ -34,6 +35,40 @@ public static class UserEndpoints
|
||||
.Produces<IEnumerable<TrackApplicationResponse>>()
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/{id}/listening-stats", GetListeningStats)
|
||||
.WithName("GetListeningStats")
|
||||
.WithSummary("Get A User'S Listening Stats For The Current Week And Streak.")
|
||||
.Produces<ListeningStatsResponse>();
|
||||
|
||||
group.MapGet("/{id}/profile", GetUserProfile)
|
||||
.WithName("GetUserProfile")
|
||||
.WithSummary("Get A User'S Public Profile, Including Follower Counts.")
|
||||
.Produces<UserProfileResponse>()
|
||||
.Produces(StatusCodes.Status404NotFound);
|
||||
|
||||
group.MapGet("/{id}/is-following", IsFollowing)
|
||||
.WithName("IsFollowingUser")
|
||||
.WithSummary("Check Whether The Current User Follows Another User.")
|
||||
.RequireAuthorization()
|
||||
.Produces<bool>()
|
||||
.Produces(StatusCodes.Status401Unauthorized);
|
||||
|
||||
group.MapPost("/{id}/follow", FollowUser)
|
||||
.WithName("FollowUser")
|
||||
.WithSummary("Follow A User.")
|
||||
.RequireAuthorization()
|
||||
.Produces(StatusCodes.Status204NoContent)
|
||||
.Produces(StatusCodes.Status401Unauthorized)
|
||||
.Produces(StatusCodes.Status404NotFound)
|
||||
.ProducesValidationProblem();
|
||||
|
||||
group.MapDelete("/{id}/follow", UnfollowUser)
|
||||
.WithName("UnfollowUser")
|
||||
.WithSummary("Unfollow A User.")
|
||||
.RequireAuthorization()
|
||||
.Produces(StatusCodes.Status204NoContent)
|
||||
.Produces(StatusCodes.Status401Unauthorized);
|
||||
|
||||
group.MapPost("/", CreateUser)
|
||||
.WithName("CreateUser")
|
||||
.WithSummary("Create A New User.")
|
||||
@@ -73,6 +108,52 @@ public static class UserEndpoints
|
||||
return await mediator.Send(new GetListeningHistoryQuery(id), cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<ListeningStatsResponse> GetListeningStats(
|
||||
IMediator mediator,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return await mediator.Send(new GetListeningStatsQuery(id), cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetUserProfile(
|
||||
IMediator mediator,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetUserProfileQuery(id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<bool> IsFollowing(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return await mediator.Send(new IsFollowingUserQuery(currentUser.RequiredId, id), cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task<IResult> FollowUser(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new FollowUserCommand(currentUser.RequiredId, id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> UnfollowUser(
|
||||
IMediator mediator,
|
||||
CurrentUser currentUser,
|
||||
long id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new UnfollowUserCommand(currentUser.RequiredId, id), cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> CreateUser(
|
||||
IMediator mediator,
|
||||
CreateUserRequest request,
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.OpenApi;
|
||||
using Musify.Api.Authentication;
|
||||
using Musify.Application.Serialization;
|
||||
|
||||
namespace Musify.Api.OpenApi;
|
||||
|
||||
@@ -38,6 +39,24 @@ public sealed class OpenApiOptionsSetup(IOptions<AuthenticationConfiguration> op
|
||||
return Task.CompletedTask;
|
||||
} );
|
||||
|
||||
// Properties annotated with [JsonConverter(typeof(LongAsStringConverter))] (id-shaped
|
||||
// `long` fields — see that converter for why) serialize as a JSON string, but the
|
||||
// schema generator still reflects the declared CLR `long`/`long?` type as a bare
|
||||
// int64 number. Reconcile the declared schema so generated clients (openapi-typescript)
|
||||
// type exactly those properties as `string`, matching what actually goes over the wire —
|
||||
// scoped to the attribute, not the CLR type, so unrelated `long` fields (byte sizes, …)
|
||||
// are left alone.
|
||||
options.AddSchemaTransformer((schema, context, _) =>
|
||||
{
|
||||
if (context.JsonPropertyInfo?.CustomConverter is LongAsStringConverter or NullableLongAsStringConverter)
|
||||
{
|
||||
schema.Type = JsonSchemaType.String;
|
||||
schema.Format = null;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
} );
|
||||
|
||||
options.AddOperationTransformer((operation, context, _) =>
|
||||
{
|
||||
var requiresAuthorization = context.Description.ActionDescriptor.EndpointMetadata
|
||||
|
||||
@@ -40,6 +40,7 @@ app.UseAuthorization();
|
||||
app
|
||||
.MapAlbumEndpoints()
|
||||
.MapConfigEndpoints()
|
||||
.MapLikeEndpoints()
|
||||
.MapMixEndpoints()
|
||||
.MapPlayListEndpoints()
|
||||
.MapTrackEndpoints()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using FluentValidation;
|
||||
using Musify.Api.DataTransferObjects.Likes;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Api.Validators.Likes;
|
||||
|
||||
public sealed class ToggleLikeRequestValidator : AbstractValidator<ToggleLikeRequest>
|
||||
{
|
||||
public ToggleLikeRequestValidator()
|
||||
{
|
||||
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.");
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user