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:
2026-09-14 23:42:45 +02:00
parent 389b3b9244
commit dc1ba89a6d
166 changed files with 14271 additions and 1982 deletions
@@ -1,5 +1,6 @@
using System.Text.Json.Serialization;
using Musify.Domain.Entities;
using Musify.Application.Serialization;
namespace Musify.Application.Albums.Responses
{
@@ -17,7 +18,7 @@ namespace Musify.Application.Albums.Responses
string Title,
string? Description,
int? ReleaseYear,
long OwnerUserId,
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId,
int TrackCount,
string? SmallImageKeyName,
string? MediumImageKeyName,
@@ -41,6 +41,10 @@ namespace Musify.Application.Contracts
DbSet<ListeningHistory> ListeningHistories { get; }
DbSet<TrackLike> TrackLikes { get; }
DbSet<UserFollow> UserFollows { get; }
Task<IDatabaseTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken);
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
@@ -0,0 +1,45 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Shared;
using Musify.Application.Tracks.Responses;
using Musify.Domain.Entities;
using X.PagedList;
using X.PagedList.EF;
namespace Musify.Application.Likes
{
public record GetLikedTracksQuery(
long UserId,
int PageNumber,
int PageSize)
: IQuery<ErrorOr<PaginatedResponse<TrackApplicationResponse>>>;
public class GetLikedTracksQueryHandler(IDatabase database)
: IQueryHandler<GetLikedTracksQuery, ErrorOr<PaginatedResponse<TrackApplicationResponse>>>
{
public async ValueTask<ErrorOr<PaginatedResponse<TrackApplicationResponse>>> Handle(GetLikedTracksQuery request, CancellationToken cancellationToken)
{
var likesQuery = database.TrackLikes
.AsNoTracking()
.Include(like => ((ExternalTrack)like.Track).TrackArtists)
.ThenInclude(trackArtist => trackArtist.Artist)
.Include(like => ((LocalTrack)like.Track).Owner)
.Where(like => like.UserId == request.UserId);
var totalCount = await likesQuery.CountAsync(cancellationToken);
var pagedEntities = await likesQuery
.OrderByDescending(like => like.CreatedAt)
.Select(like => new { like.Track, ListensCount = like.Track.ListeningHistories.Count })
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
pagedEntities.Select(x => TrackApplicationResponse.FromEntity(x.Track, x.ListensCount)),
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
return PaginatedResponse<TrackApplicationResponse>.FromPagedList(pagedTracks);
}
}
}
@@ -0,0 +1,83 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Application.Services;
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Likes
{
public record ToggleTrackLikeCommand(
long UserId,
Guid? TrackId,
TrackSource? Source,
string? ExternalId)
: ICommand<ErrorOr<bool>>;
public class ToggleTrackLikeCommandHandler(
IDatabase database,
YouTubeTrackProvisioner provisioner,
ILogger<ToggleTrackLikeCommandHandler> logger)
: ICommandHandler<ToggleTrackLikeCommand, ErrorOr<bool>>
{
public async ValueTask<ErrorOr<bool>> Handle(ToggleTrackLikeCommand request, CancellationToken cancellationToken)
{
var trackIdResult = await ResolveTrackIdAsync(request, cancellationToken);
if (trackIdResult.IsError)
return trackIdResult.Errors;
var trackId = trackIdResult.Value;
var existingLike = await database.TrackLikes
.SingleOrDefaultAsync(like => like.UserId == request.UserId && like.TrackId == trackId, cancellationToken);
bool nowLiked;
if (existingLike is not null)
{
database.TrackLikes.Remove(existingLike);
nowLiked = false;
}
else
{
await database.TrackLikes.AddAsync(new TrackLike
{
UserId = request.UserId,
TrackId = trackId
}, cancellationToken);
nowLiked = true;
}
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("User {UserId} {Action} track {TrackId}",
request.UserId, nowLiked ? "liked" : "unliked", trackId);
return nowLiked;
}
private async ValueTask<ErrorOr<Guid>> ResolveTrackIdAsync(ToggleTrackLikeCommand request, CancellationToken cancellationToken)
{
if (request.TrackId.HasValue)
{
var trackExists = await database.Tracks
.AsNoTracking()
.AnyAsync(t => t.Id == request.TrackId.Value, cancellationToken);
if (!trackExists)
{
logger.LogInformation("Track {TrackId} not found", request.TrackId);
return Error.NotFound(description: $"Track {request.TrackId} not found");
}
return request.TrackId.Value;
}
var provisionResult = await provisioner.GetOrCreateAsync(request.ExternalId!, cancellationToken);
if (provisionResult.IsError)
return provisionResult.Errors;
return provisionResult.Value.Track.Id;
}
}
}
@@ -17,7 +17,8 @@ namespace Musify.Application.PlayLists
long UserId,
string Name,
string? Description,
Guid? PictureIntentId)
Guid? PictureIntentId,
PlaylistVisibility Visibility = PlaylistVisibility.Private)
: ICommand<ErrorOr<PlayListApplicationResponse>>;
public class CreatePlayListCommandHandler(
@@ -55,7 +56,8 @@ namespace Musify.Application.PlayLists
Name = request.Name,
NormalizedName = request.Name.Trim().ToUpperInvariant(),
Description = string.IsNullOrWhiteSpace(request.Description)? null: request.Description.Trim(),
Pictures = resolvedPictures.Pictures
Pictures = resolvedPictures.Pictures,
Visibility = request.Visibility
};
await database.PlayLists.AddAsync(playList, cancellationToken);
@@ -3,10 +3,11 @@ using Microsoft.EntityFrameworkCore;
using Musify.Application.PlayLists.Responses;
using Mediator;
using Musify.Application.Contracts;
using Musify.Domain.ValueObjects;
namespace Musify.Application.PlayLists
{
public record GetPlayListByIdQuery(Guid Id)
public record GetPlayListByIdQuery(Guid Id, long? RequestingUserId = null)
: IQuery<ErrorOr<PlayListApplicationResponse>>;
public class GetPlayListByIdQueryHandler(IDatabase database)
@@ -31,6 +32,10 @@ namespace Musify.Application.PlayLists
if (entry is null)
return Error.NotFound();
if (entry.PlayList.Visibility == PlaylistVisibility.Private
&& entry.PlayList.UserId != request.RequestingUserId)
return Error.NotFound();
return PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds);
}
}
@@ -14,7 +14,8 @@ namespace Musify.Application.PlayLists
long UserId,
string? Name,
int PageNumber,
int PageSize)
int PageSize,
bool OnlyPublic = false)
: IQuery<ErrorOr<PaginatedResponse<PlayListApplicationResponse>> >;
public class GetPlayListsByUserIdQueryHandler(IDatabase database)
@@ -26,6 +27,11 @@ namespace Musify.Application.PlayLists
.AsNoTracking()
.Where(p => p.UserId == request.UserId);
if (request.OnlyPublic)
{
playListsQuery = playListsQuery.Where(p => p.Visibility == PlaylistVisibility.Public);
}
if (!string.IsNullOrEmpty(request.Name))
{
var normalizedName = request.Name.Trim().ToUpperInvariant();
@@ -1,4 +1,5 @@
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
namespace Musify.Application.PlayLists.Responses
{
@@ -9,6 +10,7 @@ namespace Musify.Application.PlayLists.Responses
string? SmallImageKeyName,
string? MediumImageKeyName,
string? LargeImageKeyName,
PlaylistVisibility Visibility,
DateTime CreatedAt,
DateTime UpdatedAt,
IReadOnlyList<Guid> CoverTrackIds)
@@ -26,6 +28,7 @@ namespace Musify.Application.PlayLists.Responses
playList.Pictures?.SmallName,
playList.Pictures?.MediumName,
playList.Pictures?.LargeName,
playList.Visibility,
playList.CreatedAt,
playList.UpdatedAt,
coverTrackIds ?? []);
@@ -18,7 +18,8 @@ namespace Musify.Application.PlayLists
Guid PlayListId,
string? NewName,
string? NewDescription,
Guid? NewPictureIntentId)
Guid? NewPictureIntentId,
PlaylistVisibility? NewVisibility = null)
: ICommand<ErrorOr<PlayListApplicationResponse>>;
public class UpdatePlayListCommandHandler(
@@ -57,6 +58,11 @@ namespace Musify.Application.PlayLists
playListEntity.Description = request.NewDescription;
}
if (request.NewVisibility.HasValue)
{
playListEntity.Visibility = request.NewVisibility.Value;
}
UploadIntent? pictureIntent = null;
string? finalPictureKey = null;
@@ -0,0 +1,44 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Musify.Application.Serialization;
// Zitadel-issued user ids routinely exceed Number.MAX_SAFE_INTEGER (2^53-1).
// Serialized as a raw JSON number, the frontend's JSON.parse silently rounds
// them to the nearest representable double, corrupting the id (it becomes a
// different, sometimes valid, user id). Applied via [property: JsonConverter(...)]
// on the specific id-shaped `long`/`long?` response properties (not globally —
// unrelated `long` fields like byte sizes must stay numbers), this serializes
// them as a JSON string instead, which round-trips exactly.
public sealed class LongAsStringConverter : JsonConverter<long>
{
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType == JsonTokenType.String
? long.Parse(reader.GetString()!, CultureInfo.InvariantCulture)
: reader.GetInt64();
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
}
public sealed class NullableLongAsStringConverter : JsonConverter<long?>
{
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;
return reader.TokenType == JsonTokenType.String
? string.IsNullOrEmpty(reader.GetString()) ? null : long.Parse(reader.GetString()!, CultureInfo.InvariantCulture)
: reader.GetInt64();
}
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
{
if (value.HasValue)
writer.WriteStringValue(value.Value.ToString(CultureInfo.InvariantCulture));
else
writer.WriteNullValue();
}
}
@@ -1,3 +1,5 @@
using System.Text.Json.Serialization;
using Musify.Application.Serialization;
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
@@ -12,7 +14,7 @@ namespace Musify.Application.Tracks.Responses
int ListensCount,
DateTime CreatedAt,
DateTime UpdatedAt,
long OwnerUserId)
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId)
: TrackApplicationResponse(Id, Title, Artist, AudioStatus, Duration, ListensCount, CreatedAt, UpdatedAt)
{
public static LocalTrackApplicationResponse FromEntity(LocalTrack track, int listensCount) =>
@@ -0,0 +1,50 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Domain.Entities;
namespace Musify.Application.Users
{
public record FollowUserCommand(long FollowerId, long FollowedId) : ICommand<ErrorOr<Success>>;
public class FollowUserCommandHandler(
IDatabase database,
ILogger<FollowUserCommandHandler> logger)
: ICommandHandler<FollowUserCommand, ErrorOr<Success>>
{
public async ValueTask<ErrorOr<Success>> Handle(FollowUserCommand request, CancellationToken cancellationToken)
{
if (request.FollowerId == request.FollowedId)
return Error.Validation(description: "A user cannot follow themselves.");
var followedExists = await database.Users
.AsNoTracking()
.AnyAsync(u => u.Id == request.FollowedId, cancellationToken);
if (!followedExists)
{
logger.LogInformation("User {FollowedId} not found", request.FollowedId);
return Error.NotFound(description: $"User {request.FollowedId} not found");
}
var alreadyFollowing = await database.UserFollows
.AsNoTracking()
.AnyAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken);
if (alreadyFollowing)
return new Success();
await database.UserFollows.AddAsync(new UserFollow
{
FollowerId = request.FollowerId,
FollowedId = request.FollowedId
}, cancellationToken);
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("User {FollowerId} followed user {FollowedId}", request.FollowerId, request.FollowedId);
return new Success();
}
}
}
@@ -0,0 +1,48 @@
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
namespace Musify.Application.Users
{
public record GetListeningStatsQuery(long UserId) : IQuery<ListeningStatsResponse>;
public record ListeningStatsResponse(int TracksThisWeek, int SecondsThisWeek, int StreakDays);
public class GetListeningStatsQueryHandler(IDatabase database)
: IQueryHandler<GetListeningStatsQuery, ListeningStatsResponse>
{
public async ValueTask<ListeningStatsResponse> Handle(GetListeningStatsQuery request, CancellationToken cancellationToken)
{
var weekAgo = DateTime.UtcNow.AddDays(-7);
var thisWeekHistory = database.ListeningHistories
.Where(l => l.UserId == request.UserId && l.ListenedAt >= weekAgo);
var tracksThisWeek = await thisWeekHistory
.Select(l => l.TrackId)
.Distinct()
.CountAsync(cancellationToken);
var secondsThisWeek = await thisWeekHistory
.Join(database.Tracks, l => l.TrackId, t => t.Id, (l, t) => t.DurationSeconds)
.SumAsync(cancellationToken);
var listenedDates = await database.ListeningHistories
.Where(l => l.UserId == request.UserId)
.Select(l => l.ListenedAt.Date)
.Distinct()
.ToListAsync(cancellationToken);
var listenedDateSet = listenedDates.ToHashSet();
var streakDays = 0;
var day = DateTime.UtcNow.Date;
while (listenedDateSet.Contains(day))
{
streakDays++;
day = day.AddDays(-1);
}
return new ListeningStatsResponse(tracksThisWeek, (int)Math.Round(secondsThisWeek), streakDays);
}
}
}
@@ -0,0 +1,63 @@
using System.Text.Json.Serialization;
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Serialization;
namespace Musify.Application.Users
{
public record GetUserProfileQuery(long UserId) : IQuery<ErrorOr<UserProfileResponse>>;
public record UserProfileResponse(
[property: JsonConverter(typeof(LongAsStringConverter))] long Id,
string Name,
string? FirstName,
string? SecondName,
string? ProfilePictureUrl,
DateTime CreatedAt,
int FollowersCount,
int FollowingCount);
public class GetUserProfileQueryHandler(IDatabase database)
: IQueryHandler<GetUserProfileQuery, ErrorOr<UserProfileResponse>>
{
public async ValueTask<ErrorOr<UserProfileResponse>> Handle(GetUserProfileQuery request, CancellationToken cancellationToken)
{
var user = await database.Users
.AsNoTracking()
.Where(u => u.Id == request.UserId)
.Select(u => new
{
u.Id,
u.Name,
u.FirstName,
u.SecondName,
u.ProfilePictureUrl,
u.CreatedAt
})
.SingleOrDefaultAsync(cancellationToken);
if (user is null)
return Error.NotFound();
var followersCount = await database.UserFollows
.AsNoTracking()
.CountAsync(f => f.FollowedId == request.UserId, cancellationToken);
var followingCount = await database.UserFollows
.AsNoTracking()
.CountAsync(f => f.FollowerId == request.UserId, cancellationToken);
return new UserProfileResponse(
user.Id,
user.Name,
user.FirstName,
user.SecondName,
user.ProfilePictureUrl,
user.CreatedAt,
followersCount,
followingCount);
}
}
}
@@ -0,0 +1,17 @@
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
namespace Musify.Application.Users
{
public record IsFollowingUserQuery(long FollowerId, long FollowedId) : IQuery<bool>;
public class IsFollowingUserQueryHandler(IDatabase database)
: IQueryHandler<IsFollowingUserQuery, bool>
{
public ValueTask<bool> Handle(IsFollowingUserQuery request, CancellationToken cancellationToken) =>
new(database.UserFollows
.AsNoTracking()
.AnyAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken));
}
}
@@ -1,9 +1,11 @@
using Musify.Domain.Entities;
using System.Text.Json.Serialization;
using Musify.Application.Serialization;
using Musify.Domain.Entities;
namespace Musify.Application.Users.Responses
{
public record UserApplicationResponse(
long Id,
[property: JsonConverter(typeof(LongAsStringConverter))] long Id,
string Name,
string? FirstName,
string? SecondName,
@@ -0,0 +1,32 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
namespace Musify.Application.Users
{
public record UnfollowUserCommand(long FollowerId, long FollowedId) : ICommand<ErrorOr<Success>>;
public class UnfollowUserCommandHandler(
IDatabase database,
ILogger<UnfollowUserCommandHandler> logger)
: ICommandHandler<UnfollowUserCommand, ErrorOr<Success>>
{
public async ValueTask<ErrorOr<Success>> Handle(UnfollowUserCommand request, CancellationToken cancellationToken)
{
var follow = await database.UserFollows
.SingleOrDefaultAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken);
if (follow is null)
return new Success();
database.UserFollows.Remove(follow);
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("User {FollowerId} unfollowed user {FollowedId}", request.FollowerId, request.FollowedId);
return new Success();
}
}
}
@@ -33,6 +33,9 @@ namespace Musify.Domain.Entities
[Required]
public LifeCycleStatus LifeCycleStatus { get; set; } = LifeCycleStatus.Active;
[Required]
public PlaylistVisibility Visibility { get; set; } = PlaylistVisibility.Private;
[Required]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
@@ -0,0 +1,28 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Musify.Domain.Entities
{
#pragma warning disable CS8618
[Table("TrackLikes")]
public class TrackLike
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
public required long UserId { get; set; }
[Required]
public required Guid TrackId { get; set; }
[Required]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
[ForeignKey(nameof(UserId))]
public User User { get; set; }
[ForeignKey(nameof(TrackId))]
public Track Track { get; set; }
}
}
@@ -0,0 +1,28 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Musify.Domain.Entities
{
#pragma warning disable CS8618
[Table("UserFollows")]
public class UserFollow
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
public required long FollowerId { get; set; }
[Required]
public required long FollowedId { get; set; }
[Required]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
[ForeignKey(nameof(FollowerId))]
public User Follower { get; set; }
[ForeignKey(nameof(FollowedId))]
public User Followed { get; set; }
}
}
@@ -0,0 +1,8 @@
namespace Musify.Domain.ValueObjects
{
public enum PlaylistVisibility
{
Private = 0,
Public = 1
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 68 KiB

@@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using MassTransit;
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.MassTransit.Sagas;
using AppIDatabase = Musify.Application.Contracts.IDatabase;
@@ -88,6 +89,10 @@ namespace Musify.Infrastructure.Persistence
.HasIndex(artist => artist.ExternalId)
.IsUnique();
modelBuilder.Entity<PlayList>()
.Property(playList => playList.Visibility)
.HasDefaultValue(PlaylistVisibility.Private);
modelBuilder.Entity<PlayList>()
.OwnsOne(playList => playList.Pictures, pictures =>
{
@@ -159,6 +164,26 @@ namespace Musify.Infrastructure.Persistence
modelBuilder.Entity<MixItem>()
.HasIndex(item => new { item.MixId, item.Position });
modelBuilder.Entity<TrackLike>()
.HasIndex(like => new { like.UserId, like.TrackId })
.IsUnique();
modelBuilder.Entity<UserFollow>()
.HasOne(follow => follow.Follower)
.WithMany()
.HasForeignKey(follow => follow.FollowerId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserFollow>()
.HasOne(follow => follow.Followed)
.WithMany()
.HasForeignKey(follow => follow.FollowedId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserFollow>()
.HasIndex(follow => new { follow.FollowerId, follow.FollowedId })
.IsUnique();
var playListProcessing = modelBuilder.Entity<PlayListProcessingState>();
playListProcessing.HasKey(state => state.CorrelationId);
playListProcessing.Property(state => state.CorrelationId).ValueGeneratedNever();
@@ -206,6 +231,10 @@ namespace Musify.Infrastructure.Persistence
public DbSet<ListeningHistory> ListeningHistories => Set<ListeningHistory>();
public DbSet<TrackLike> TrackLikes => Set<TrackLike>();
public DbSet<UserFollow> UserFollows => Set<UserFollow>();
public async Task<IDatabaseTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken)
{
var transaction = await Database.BeginTransactionAsync(isolationLevel, cancellationToken);
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddPlayListVisibility : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Visibility",
table: "PlayLists",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Visibility",
table: "PlayLists");
}
}
}
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddTrackLikes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TrackLikes",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<long>(type: "bigint", nullable: false),
TrackId = table.Column<Guid>(type: "uuid", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrackLikes", x => x.Id);
table.ForeignKey(
name: "FK_TrackLikes_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TrackLikes_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_TrackLikes_TrackId",
table: "TrackLikes",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_TrackLikes_UserId_TrackId",
table: "TrackLikes",
columns: new[] { "UserId", "TrackId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TrackLikes");
}
}
}
@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddUserFollows : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UserFollows",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
FollowerId = table.Column<long>(type: "bigint", nullable: false),
FollowedId = table.Column<long>(type: "bigint", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserFollows", x => x.Id);
table.ForeignKey(
name: "FK_UserFollows_User_FollowedId",
column: x => x.FollowedId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_UserFollows_User_FollowerId",
column: x => x.FollowerId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_UserFollows_FollowedId",
table: "UserFollows",
column: "FollowedId");
migrationBuilder.CreateIndex(
name: "IX_UserFollows_FollowerId_FollowedId",
table: "UserFollows",
columns: new[] { "FollowerId", "FollowedId" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserFollows");
}
}
}
@@ -431,6 +431,11 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Property<long>("UserId")
.HasColumnType("bigint");
b.Property<int>("Visibility")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(0);
b.HasKey("Id");
b.HasIndex("UserId");
@@ -518,6 +523,31 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.ToTable("TrackArtist");
});
modelBuilder.Entity("Musify.Domain.Entities.TrackLike", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("TrackId")
.HasColumnType("uuid");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("TrackId");
b.HasIndex("UserId", "TrackId")
.IsUnique();
b.ToTable("TrackLikes");
});
modelBuilder.Entity("Musify.Domain.Entities.Upload", b =>
{
b.Property<Guid>("Id")
@@ -636,6 +666,31 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.ToTable("User");
});
modelBuilder.Entity("Musify.Domain.Entities.UserFollow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("FollowedId")
.HasColumnType("bigint");
b.Property<long>("FollowerId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("FollowedId");
b.HasIndex("FollowerId", "FollowedId")
.IsUnique();
b.ToTable("UserFollows");
});
modelBuilder.Entity("Musify.Domain.Entities.UserHasTrack", b =>
{
b.Property<Guid>("Id")
@@ -1105,6 +1160,25 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Navigation("Track");
});
modelBuilder.Entity("Musify.Domain.Entities.TrackLike", b =>
{
b.HasOne("Musify.Domain.Entities.Track", "Track")
.WithMany()
.HasForeignKey("TrackId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Musify.Domain.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Track");
b.Navigation("User");
});
modelBuilder.Entity("Musify.Domain.Entities.UploadIntent", b =>
{
b.HasOne("Musify.Domain.Entities.User", "User")
@@ -1116,6 +1190,25 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Navigation("User");
});
modelBuilder.Entity("Musify.Domain.Entities.UserFollow", b =>
{
b.HasOne("Musify.Domain.Entities.User", "Followed")
.WithMany()
.HasForeignKey("FollowedId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("Musify.Domain.Entities.User", "Follower")
.WithMany()
.HasForeignKey("FollowerId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Followed");
b.Navigation("Follower");
});
modelBuilder.Entity("Musify.Domain.Entities.UserHasTrack", b =>
{
b.HasOne("Musify.Domain.Entities.Track", "Track")
@@ -13,8 +13,8 @@ namespace Musify.Infrastructure.Services
{
public class YouTubeMusicService(YouTubeConfiguration configuration, IMemoryCache cache, ILogger<YouTubeMusicService> logger) : IYouTubeMusicService
{
private readonly YouTubeMusicClient client = new(geographicalLocation: configuration.GeographicalLocation);
private readonly SingleFlightCache singleFlight = new(cache);
private readonly YouTubeMusicClient client = new YouTubeMusicClient(geographicalLocation: configuration.GeographicalLocation);
private readonly SingleFlightCache singleFlight = new SingleFlightCache(cache);
private sealed record CachedStreamInfo(string Url, DateTime ExpiresAtUtc);
@@ -89,7 +89,7 @@ namespace Musify.Infrastructure.Services
song.IsExplicit,
song.Artists
.Select(artist => new YouTubeArtistRef(
string.IsNullOrEmpty(artist.Id) ? null : artist.Id,
string.IsNullOrEmpty(artist.Id)? null: artist.Id,
artist.Name))
.ToList()))
.ToList();
@@ -147,7 +147,7 @@ namespace Musify.Infrastructure.Services
info.IsEp,
info.Artists
.Select(artist => new YouTubeArtistRef(
string.IsNullOrEmpty(artist.Id) ? null : artist.Id,
string.IsNullOrEmpty(artist.Id)? null: artist.Id,
artist.Name))
.ToList());
@@ -203,7 +203,7 @@ namespace Musify.Infrastructure.Services
{
var now = DateTime.UtcNow;
if (cache.TryGetValue(StreamCacheKey(videoId), out CachedStreamInfo? cached)
&& cached is not null
&& cached != null
&& cached.ExpiresAtUtc > now)
{
return new YouTubeStreamInfo(cached.Url, (int)(cached.ExpiresAtUtc - now).TotalSeconds);
@@ -267,7 +267,7 @@ namespace Musify.Infrastructure.Services
info.IsExplicit,
info.Artists
.Select(artist => new YouTubeArtistRef(
string.IsNullOrEmpty(artist.Id) ? null : artist.Id,
string.IsNullOrEmpty(artist.Id)? null: artist.Id,
artist.Name))
.ToList());
}
@@ -291,8 +291,7 @@ namespace Musify.Infrastructure.Services
var chosen = candidates.FirstOrDefault(thumbnail => thumbnail.Width >= configuration.ThumbnailSize)
?? candidates.LastOrDefault();
return chosen is null
? string.Empty
return chosen ==null? string.Empty
: YouTubeThumbNailHelper.WithSize(chosen.Url, configuration.ThumbnailSize);
}
@@ -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
+1
View File
@@ -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.");
});
}
}
@@ -0,0 +1,55 @@
using Musify.Application.Likes;
using Musify.Application.Tests.TestSupport;
using Musify.Domain.Entities;
using Xunit;
namespace Musify.Application.Tests.Likes
{
public sealed class GetLikedTracksQueryHandlerTests : HandlerTestBase
{
private GetLikedTracksQueryHandler CreateHandler() => new(Database);
[Fact]
public async Task Handle_MultipleLikes_ReturnsMostRecentFirst()
{
var owner = TestEntities.User();
var older = TestEntities.LocalTrack(owner, "Older like");
var newer = TestEntities.LocalTrack(owner, "Newer like");
await SeedAsync(
owner, older, newer,
new TrackLike { UserId = owner.Id, TrackId = older.Id, CreatedAt = DateTime.UtcNow.AddMinutes(-10) },
new TrackLike { UserId = owner.Id, TrackId = newer.Id, CreatedAt = DateTime.UtcNow });
var result = await CreateHandler().Handle(new GetLikedTracksQuery(owner.Id, 1, 10), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(["Newer like", "Older like"], result.Value.Items.Select(track => track.Title));
}
[Fact]
public async Task Handle_NoLikes_ReturnsEmpty()
{
var owner = TestEntities.User();
await SeedAsync(owner);
var result = await CreateHandler().Handle(new GetLikedTracksQuery(owner.Id, 1, 10), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Empty(result.Value.Items);
}
[Fact]
public async Task Handle_OtherUsersLikes_AreExcluded()
{
var owner = TestEntities.User(1, "owner");
var stranger = TestEntities.User(2, "stranger");
var track = TestEntities.LocalTrack(owner);
await SeedAsync(owner, stranger, track, new TrackLike { UserId = stranger.Id, TrackId = track.Id });
var result = await CreateHandler().Handle(new GetLikedTracksQuery(owner.Id, 1, 10), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Empty(result.Value.Items);
}
}
}
@@ -0,0 +1,103 @@
using ErrorOr;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Likes;
using Musify.Application.Services;
using Musify.Application.Tests.TestSupport;
using Musify.Domain.ValueObjects;
using NSubstitute;
using Xunit;
namespace Musify.Application.Tests.Likes
{
public sealed class ToggleTrackLikeCommandHandlerTests : HandlerTestBase
{
private readonly IYouTubeMusicService youTubeMusicService = Substitute.For<IYouTubeMusicService>();
private ToggleTrackLikeCommandHandler CreateHandler()
{
var provisioner = new YouTubeTrackProvisioner(
Database, youTubeMusicService, TestConfigurations.Track(), NoOpLogger<YouTubeTrackProvisioner>());
return new ToggleTrackLikeCommandHandler(Database, provisioner, NoOpLogger<ToggleTrackLikeCommandHandler>());
}
private static YouTubeSongResult BuildSong(string videoId) => new(
videoId, "Song Title", "Song Artist", "Song Album", 200, "https://img.example/thumb.jpg", false,
[new YouTubeArtistRef("artist-id", "Song Artist")]);
[Fact]
public async Task Handle_LocalTrackNotLiked_LikesIt()
{
var owner = TestEntities.User();
var track = TestEntities.LocalTrack(owner);
await SeedAsync(owner, track);
var result = await CreateHandler().Handle(
new ToggleTrackLikeCommand(owner.Id, track.Id, null, null), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.True(result.Value);
Assert.Single(await Database.TrackLikes.ToListAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_LocalTrackAlreadyLiked_UnlikesIt()
{
var owner = TestEntities.User();
var track = TestEntities.LocalTrack(owner);
await SeedAsync(owner, track, new Musify.Domain.Entities.TrackLike { UserId = owner.Id, TrackId = track.Id });
var result = await CreateHandler().Handle(
new ToggleTrackLikeCommand(owner.Id, track.Id, null, null), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.False(result.Value);
Assert.Empty(await Database.TrackLikes.ToListAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_TrackMissing_ReturnsNotFound()
{
var owner = TestEntities.User();
await SeedAsync(owner);
var result = await CreateHandler().Handle(
new ToggleTrackLikeCommand(owner.Id, Guid.NewGuid(), null, null), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
[Fact]
public async Task Handle_UnknownExternalTrack_ProvisionsAndLikesIt()
{
youTubeMusicService.GetSongAsync("new-video", Arg.Any<CancellationToken>()).Returns(BuildSong("new-video"));
var owner = TestEntities.User();
await SeedAsync(owner);
var result = await CreateHandler().Handle(
new ToggleTrackLikeCommand(owner.Id, null, TrackSource.YouTube, "new-video"), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.True(result.Value);
var track = await Database.ExternalTracks.SingleAsync(t => t.ExternalId == "new-video", TestContext.Current.CancellationToken);
Assert.True(await Database.TrackLikes.AnyAsync(like => like.TrackId == track.Id, TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_ExistingExternalTrack_LikesItWithoutReprovisioning()
{
var owner = TestEntities.User();
var track = TestEntities.ExternalTrack(externalId: "abc123");
await SeedAsync(owner, track);
var result = await CreateHandler().Handle(
new ToggleTrackLikeCommand(owner.Id, null, TrackSource.YouTube, "abc123"), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.True(result.Value);
await youTubeMusicService.DidNotReceive().GetSongAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}
}
@@ -60,6 +60,34 @@ namespace Musify.Application.Tests.PlayLists
await eventBus.Received(1).PublishAsync(Arg.Any<Musify.Application.Events.CreatePlayListResourcesEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_NoVisibilitySpecified_DefaultsToPrivate()
{
var user = TestEntities.User();
await SeedAsync(user);
var command = new CreatePlayListCommand(user.Id, "My Playlist", null, PictureIntentId: null);
var result = await CreateHandler().Handle(command, TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(Musify.Domain.ValueObjects.PlaylistVisibility.Private, result.Value.Visibility);
}
[Fact]
public async Task Handle_PublicVisibility_PersistsIt()
{
var user = TestEntities.User();
await SeedAsync(user);
var command = new CreatePlayListCommand(user.Id, "My Playlist", null, PictureIntentId: null, Visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Public);
var result = await CreateHandler().Handle(command, TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(Musify.Domain.ValueObjects.PlaylistVisibility.Public, result.Value.Visibility);
}
[Fact]
public async Task Handle_UserMissing_ReturnsNotFound()
{
@@ -14,7 +14,7 @@ namespace Musify.Application.Tests.PlayLists
public async Task Handle_ExistingPlayList_ReturnsItWithCoverTrackIds()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id);
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Public);
var track = TestEntities.LocalTrack(owner);
await SeedAsync(owner, playList, track, new PlayListHasTrack { PlayListId = playList.Id, TrackId = track.Id, Position = 0 });
@@ -32,5 +32,54 @@ namespace Musify.Application.Tests.PlayLists
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
[Fact]
public async Task Handle_PrivatePlayList_RequestedByOwner_ReturnsIt()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Private);
await SeedAsync(owner, playList);
var result = await CreateHandler().Handle(new GetPlayListByIdQuery(playList.Id, owner.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
}
[Fact]
public async Task Handle_PrivatePlayList_RequestedByStranger_ReturnsNotFound()
{
var owner = TestEntities.User(1, "owner");
var stranger = TestEntities.User(2, "stranger");
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Private);
await SeedAsync(owner, stranger, playList);
var result = await CreateHandler().Handle(new GetPlayListByIdQuery(playList.Id, stranger.Id), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
[Fact]
public async Task Handle_PrivatePlayList_RequestedAnonymously_ReturnsNotFound()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Private);
await SeedAsync(owner, playList);
var result = await CreateHandler().Handle(new GetPlayListByIdQuery(playList.Id, RequestingUserId: null), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
[Fact]
public async Task Handle_PublicPlayList_RequestedAnonymously_ReturnsIt()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Public);
await SeedAsync(owner, playList);
var result = await CreateHandler().Handle(new GetPlayListByIdQuery(playList.Id, RequestingUserId: null), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
}
}
}
@@ -27,6 +27,22 @@ namespace Musify.Application.Tests.PlayLists
Assert.Equal("Mine", playList.Name);
}
[Fact]
public async Task Handle_OnlyPublic_ReturnsOnlyPublicPlayLists()
{
var owner = TestEntities.User();
await SeedAsync(
owner,
TestEntities.PlayList(owner.Id, "Public one", visibility: PlaylistVisibility.Public),
TestEntities.PlayList(owner.Id, "Private one", visibility: PlaylistVisibility.Private));
var result = await CreateHandler().Handle(new GetPlayListsByUserIdQuery(owner.Id, Name: null, PageNumber: 1, PageSize: 10, OnlyPublic: true), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
var playList = Assert.Single(result.Value.Items);
Assert.Equal("Public one", playList.Name);
}
[Fact]
public async Task Handle_NameFilter_ReturnsOnlyMatchingPlayLists()
{
@@ -62,6 +62,36 @@ namespace Musify.Application.Tests.PlayLists
Assert.Equal(ErrorType.Unauthorized, result.FirstError.Type);
}
[Fact]
public async Task Handle_NewVisibility_UpdatesIt()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id);
await SeedAsync(owner, playList);
var command = new UpdatePlayListCommand(owner.Id, playList.Id, null, null, null, Musify.Domain.ValueObjects.PlaylistVisibility.Public);
var result = await CreateHandler().Handle(command, TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(Musify.Domain.ValueObjects.PlaylistVisibility.Public, result.Value.Visibility);
}
[Fact]
public async Task Handle_NoVisibilitySpecified_LeavesItUnchanged()
{
var owner = TestEntities.User();
var playList = TestEntities.PlayList(owner.Id, visibility: Musify.Domain.ValueObjects.PlaylistVisibility.Public);
await SeedAsync(owner, playList);
var command = new UpdatePlayListCommand(owner.Id, playList.Id, "New Name", null, null);
var result = await CreateHandler().Handle(command, TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(Musify.Domain.ValueObjects.PlaylistVisibility.Public, result.Value.Visibility);
}
[Fact]
public async Task Handle_BlankNameAndDescription_LeavesThemUnchanged()
{
@@ -126,6 +126,26 @@ namespace Musify.Application.Tests.TestSupport
modelBuilder.Entity<MixItem>()
.HasIndex(item => new { item.MixId, item.Position });
modelBuilder.Entity<TrackLike>()
.HasIndex(like => new { like.UserId, like.TrackId })
.IsUnique();
modelBuilder.Entity<UserFollow>()
.HasOne(follow => follow.Follower)
.WithMany()
.HasForeignKey(follow => follow.FollowerId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserFollow>()
.HasOne(follow => follow.Followed)
.WithMany()
.HasForeignKey(follow => follow.FollowedId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<UserFollow>()
.HasIndex(follow => new { follow.FollowerId, follow.FollowedId })
.IsUnique();
}
public DbSet<User> Users => Set<User>();
@@ -164,6 +184,10 @@ namespace Musify.Application.Tests.TestSupport
public DbSet<ListeningHistory> ListeningHistories => Set<ListeningHistory>();
public DbSet<TrackLike> TrackLikes => Set<TrackLike>();
public DbSet<UserFollow> UserFollows => Set<UserFollow>();
public async Task<IDatabaseTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken)
{
var transaction = await Database.BeginTransactionAsync(isolationLevel, cancellationToken);
@@ -111,7 +111,8 @@ namespace Musify.Application.Tests.TestSupport
string name = "Test Playlist",
string? description = null,
PlayListPictures? pictures = null,
LifeCycleStatus lifeCycleStatus = LifeCycleStatus.Active) =>
LifeCycleStatus lifeCycleStatus = LifeCycleStatus.Active,
PlaylistVisibility visibility = PlaylistVisibility.Private) =>
new()
{
UserId = userId,
@@ -119,7 +120,8 @@ namespace Musify.Application.Tests.TestSupport
NormalizedName = name.ToUpperInvariant(),
Description = description,
Pictures = pictures ?? PlayListPictures(),
LifeCycleStatus = lifeCycleStatus
LifeCycleStatus = lifeCycleStatus,
Visibility = visibility
};
public static AlbumPictures AlbumPictures() => new()
@@ -0,0 +1,61 @@
using ErrorOr;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Tests.TestSupport;
using Musify.Application.Users;
using Xunit;
namespace Musify.Application.Tests.Users
{
public sealed class FollowUserCommandHandlerTests : HandlerTestBase
{
private FollowUserCommandHandler CreateHandler() => new(Database, NoOpLogger<FollowUserCommandHandler>());
[Fact]
public async Task Handle_ValidTarget_CreatesFollow()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed);
var result = await CreateHandler().Handle(new FollowUserCommand(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Single(await Database.UserFollows.ToListAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_AlreadyFollowing_IsIdempotent()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed, new Musify.Domain.Entities.UserFollow { FollowerId = follower.Id, FollowedId = followed.Id });
var result = await CreateHandler().Handle(new FollowUserCommand(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Single(await Database.UserFollows.ToListAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_SelfFollow_ReturnsValidationError()
{
var user = TestEntities.User();
await SeedAsync(user);
var result = await CreateHandler().Handle(new FollowUserCommand(user.Id, user.Id), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.Validation, result.FirstError.Type);
}
[Fact]
public async Task Handle_TargetMissing_ReturnsNotFound()
{
var follower = TestEntities.User();
await SeedAsync(follower);
var result = await CreateHandler().Handle(new FollowUserCommand(follower.Id, 404), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
}
}
@@ -0,0 +1,87 @@
using Musify.Application.Tests.TestSupport;
using Musify.Application.Users;
using Xunit;
namespace Musify.Application.Tests.Users
{
public sealed class GetListeningStatsQueryHandlerTests : HandlerTestBase
{
private GetListeningStatsQueryHandler CreateHandler() => new(Database);
[Fact]
public async Task Handle_NoHistory_ReturnsZeroes()
{
var user = TestEntities.User();
await SeedAsync(user);
var result = await CreateHandler().Handle(new GetListeningStatsQuery(user.Id), TestContext.Current.CancellationToken);
Assert.Equal(0, result.TracksThisWeek);
Assert.Equal(0, result.SecondsThisWeek);
Assert.Equal(0, result.StreakDays);
}
[Fact]
public async Task Handle_ListensThisWeek_CountsDistinctTracksAndTotalSeconds()
{
var user = TestEntities.User();
var trackA = TestEntities.LocalTrack(user, "Track A", durationSeconds: 200);
var trackB = TestEntities.LocalTrack(user, "Track B", durationSeconds: 100);
await SeedAsync(
user, trackA, trackB,
TestEntities.ListeningHistory(user.Id, trackA.Id, DateTime.UtcNow.AddDays(-1)),
TestEntities.ListeningHistory(user.Id, trackA.Id, DateTime.UtcNow.AddHours(-1)),
TestEntities.ListeningHistory(user.Id, trackB.Id, DateTime.UtcNow),
TestEntities.ListeningHistory(user.Id, trackB.Id, DateTime.UtcNow.AddDays(-10)));
var result = await CreateHandler().Handle(new GetListeningStatsQuery(user.Id), TestContext.Current.CancellationToken);
Assert.Equal(2, result.TracksThisWeek);
Assert.Equal(500, result.SecondsThisWeek);
}
[Fact]
public async Task Handle_ListenedTodayAndYesterday_StreakIsTwo()
{
var user = TestEntities.User();
var track = TestEntities.LocalTrack(user);
await SeedAsync(
user, track,
TestEntities.ListeningHistory(user.Id, track.Id, DateTime.UtcNow),
TestEntities.ListeningHistory(user.Id, track.Id, DateTime.UtcNow.AddDays(-1)));
var result = await CreateHandler().Handle(new GetListeningStatsQuery(user.Id), TestContext.Current.CancellationToken);
Assert.Equal(2, result.StreakDays);
}
[Fact]
public async Task Handle_GapBeforeToday_StopsStreakAtGap()
{
var user = TestEntities.User();
var track = TestEntities.LocalTrack(user);
await SeedAsync(
user, track,
TestEntities.ListeningHistory(user.Id, track.Id, DateTime.UtcNow),
TestEntities.ListeningHistory(user.Id, track.Id, DateTime.UtcNow.AddDays(-2)));
var result = await CreateHandler().Handle(new GetListeningStatsQuery(user.Id), TestContext.Current.CancellationToken);
Assert.Equal(1, result.StreakDays);
}
[Fact]
public async Task Handle_NoListenToday_StreakIsZero()
{
var user = TestEntities.User();
var track = TestEntities.LocalTrack(user);
await SeedAsync(
user, track,
TestEntities.ListeningHistory(user.Id, track.Id, DateTime.UtcNow.AddDays(-1)));
var result = await CreateHandler().Handle(new GetListeningStatsQuery(user.Id), TestContext.Current.CancellationToken);
Assert.Equal(0, result.StreakDays);
}
}
}
@@ -0,0 +1,41 @@
using ErrorOr;
using Musify.Application.Tests.TestSupport;
using Musify.Application.Users;
using Musify.Domain.Entities;
using Xunit;
namespace Musify.Application.Tests.Users
{
public sealed class GetUserProfileQueryHandlerTests : HandlerTestBase
{
private GetUserProfileQueryHandler CreateHandler() => new(Database);
[Fact]
public async Task Handle_ExistingUser_ReturnsFollowerAndFollowingCounts()
{
var user = TestEntities.User(1, "user");
var followerA = TestEntities.User(2, "followerA");
var followerB = TestEntities.User(3, "followerB");
var followed = TestEntities.User(4, "followed");
await SeedAsync(
user, followerA, followerB, followed,
new UserFollow { FollowerId = followerA.Id, FollowedId = user.Id },
new UserFollow { FollowerId = followerB.Id, FollowedId = user.Id },
new UserFollow { FollowerId = user.Id, FollowedId = followed.Id });
var result = await CreateHandler().Handle(new GetUserProfileQuery(user.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Equal(2, result.Value.FollowersCount);
Assert.Equal(1, result.Value.FollowingCount);
}
[Fact]
public async Task Handle_UserMissing_ReturnsNotFound()
{
var result = await CreateHandler().Handle(new GetUserProfileQuery(404), TestContext.Current.CancellationToken);
Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
}
}
}
@@ -0,0 +1,36 @@
using Musify.Application.Tests.TestSupport;
using Musify.Application.Users;
using Musify.Domain.Entities;
using Xunit;
namespace Musify.Application.Tests.Users
{
public sealed class IsFollowingUserQueryHandlerTests : HandlerTestBase
{
private IsFollowingUserQueryHandler CreateHandler() => new(Database);
[Fact]
public async Task Handle_Following_ReturnsTrue()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed, new UserFollow { FollowerId = follower.Id, FollowedId = followed.Id });
var result = await CreateHandler().Handle(new IsFollowingUserQuery(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.True(result);
}
[Fact]
public async Task Handle_NotFollowing_ReturnsFalse()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed);
var result = await CreateHandler().Handle(new IsFollowingUserQuery(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.False(result);
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore;
using Musify.Application.Tests.TestSupport;
using Musify.Application.Users;
using Musify.Domain.Entities;
using Xunit;
namespace Musify.Application.Tests.Users
{
public sealed class UnfollowUserCommandHandlerTests : HandlerTestBase
{
private UnfollowUserCommandHandler CreateHandler() => new(Database, NoOpLogger<UnfollowUserCommandHandler>());
[Fact]
public async Task Handle_ExistingFollow_RemovesIt()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed, new UserFollow { FollowerId = follower.Id, FollowedId = followed.Id });
var result = await CreateHandler().Handle(new UnfollowUserCommand(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
Assert.Empty(await Database.UserFollows.ToListAsync(TestContext.Current.CancellationToken));
}
[Fact]
public async Task Handle_NotFollowing_IsIdempotent()
{
var follower = TestEntities.User(1, "follower");
var followed = TestEntities.User(2, "followed");
await SeedAsync(follower, followed);
var result = await CreateHandler().Handle(new UnfollowUserCommand(follower.Id, followed.Id), TestContext.Current.CancellationToken);
Assert.False(result.IsError);
}
}
}