Design Prot Merge #1
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "musify-web",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["--prefix", "web-player", "run", "dev"],
|
||||
"port": 3000,
|
||||
"autoPort": true
|
||||
},
|
||||
{
|
||||
"name": "musify-api",
|
||||
"runtimeExecutable": "dotnet",
|
||||
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.Api"],
|
||||
"port": 5111
|
||||
},
|
||||
{
|
||||
"name": "musify-streaming-gateway",
|
||||
"runtimeExecutable": "dotnet",
|
||||
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.StreamingGateway"],
|
||||
"port": 8081
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -4,6 +4,13 @@
|
||||
# Force LF for shell scripts
|
||||
*.sh text eol=lf
|
||||
|
||||
# Env templates get `cp`-ed straight into deploy/.env / deploy/.env.prod,
|
||||
# which containers (e.g. zitadel-init in deploy/compose.yml) parse with
|
||||
# plain shell text tools — keep them LF so a Windows checkout can't
|
||||
# reintroduce CRLF into a value that then looks non-empty but isn't.
|
||||
.env.example text eol=lf
|
||||
.env.prod.example text eol=lf
|
||||
|
||||
# Treat common binaries as binary
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Copilot Instructions
|
||||
|
||||
## Project Guidelines
|
||||
- No crear pruebas/tests si el usuario no lo solicita explícitamente; evitar cambios no pedidos.
|
||||
+11
-1
@@ -15,5 +15,15 @@ artifacts/
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
|
||||
# Secrets / local
|
||||
# Environment files (deploy/.env, deploy/.env.prod, web-player/.env, ...)
|
||||
.env
|
||||
.env.*
|
||||
*.env
|
||||
!.env.example
|
||||
!.env.prod.example
|
||||
|
||||
# Deploy secrets and runtime state
|
||||
deploy/keys/
|
||||
deploy/secrets/
|
||||
deploy/nginx/certs/
|
||||
deploy/zitadel/.output/
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Musify
|
||||
|
||||
Music streaming platform: upload your own tracks, process them asynchronously
|
||||
(audio transcoded to `.m4a`, thumbnails generated) and stream them without the
|
||||
bytes ever going through the API.
|
||||
|
||||
```
|
||||
backend/ .NET 10 — Domain / Application / Infrastructure / Api / Worker / StreamingGateway / Tests
|
||||
web-player/ SvelteKit 2 + Svelte 5 + Tailwind 4 web client
|
||||
deploy/ Docker Compose stacks — self-contained, no wrapper scripts
|
||||
docs/ What each piece does and why (in Spanish)
|
||||
```
|
||||
|
||||
```sh
|
||||
dotnet test backend/Musify.slnx # backend/Tests/ — Docker running (Testcontainers: Postgres, SeaweedFS)
|
||||
```
|
||||
|
||||
## Run it
|
||||
|
||||
Development (Docker Desktop):
|
||||
|
||||
```sh
|
||||
docker compose -f deploy/compose.yml -f deploy/compose.dev.yml up -d
|
||||
```
|
||||
|
||||
Infrastructure plus stream-ticket keys, database migrations and Zitadel OIDC
|
||||
provisioning — all as one-shot jobs baked into the compose file. Apps run from
|
||||
the IDE by default; add `--profile apps up -d --build` as a second command to
|
||||
run them in Docker instead.
|
||||
|
||||
Production, on a server with a domain:
|
||||
|
||||
```sh
|
||||
cp deploy/.env.prod.example deploy/.env.prod # fill in the domain and secrets
|
||||
docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml up -d
|
||||
docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml --profile apps up -d --build
|
||||
```
|
||||
|
||||
Idempotent — run the same commands again to deploy an update. See
|
||||
[deploy/README.md](deploy/README.md) for the details, the port map and the
|
||||
production prerequisites.
|
||||
|
||||
## Components
|
||||
|
||||
| Service | Port (dev) | Role |
|
||||
|---|---|---|
|
||||
| `Musify.Api` | 5111 | REST API, issues presigned upload URLs and stream tickets |
|
||||
| `Musify.StreamingGateway` | 8081 | YARP proxy that validates the stream ticket and serves the audio |
|
||||
| `Musify.Worker` | — | MassTransit consumers: transcoding, thumbnails |
|
||||
| `web-player` | 5173 / 3000 | Web client (SvelteKit, server-side OIDC session) |
|
||||
| Zitadel | 8080 | Identity (OIDC/OAuth2) |
|
||||
| PostgreSQL / RabbitMQ / SeaweedFS / Jaeger | 59000 / 5672 / 8333 / 16686 | Metadata, messaging, object storage, traces |
|
||||
|
||||
More in [docs/](docs/README.md): [architecture](docs/architecture.md),
|
||||
[authentication](docs/authentication.md), [storage](docs/storage.md),
|
||||
[streaming](docs/streaming.md), [media processing](docs/media-processing.md),
|
||||
[development](docs/development.md).
|
||||
@@ -8,3 +8,5 @@
|
||||
.claude/
|
||||
**/DesignSettings.json
|
||||
*.user
|
||||
# Test projects: never shipped, no app Dockerfile needs them in its build context.
|
||||
Tests/
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record AddTrackToAlbumCommand(long UserId, Guid AlbumId, Guid TrackId)
|
||||
: ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class AddTrackToAlbumCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<AddTrackToAlbumCommandHandler> logger)
|
||||
: ICommandHandler<AddTrackToAlbumCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(AddTrackToAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (album.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} is not the owner of album {AlbumId}", request.UserId, request.AlbumId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var track = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (track == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound(description: $"Track {request.TrackId} not found");
|
||||
}
|
||||
|
||||
if (track.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} does not own track {TrackId}", request.UserId, request.TrackId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var alreadyAdded = await database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.AnyAsync(albumTrack => albumTrack.AlbumId == request.AlbumId && albumTrack.TrackId == request.TrackId, cancellationToken);
|
||||
if (alreadyAdded)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} already in album {AlbumId}", request.TrackId, request.AlbumId);
|
||||
return Error.Conflict(description: "Track is already in the album.");
|
||||
}
|
||||
|
||||
var albumTracksQuery = database.AlbumHasTracks
|
||||
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId);
|
||||
|
||||
var hasTracks = await albumTracksQuery.AnyAsync(cancellationToken);
|
||||
var nextTrackNumber = hasTracks
|
||||
? await albumTracksQuery.MaxAsync(albumTrack => albumTrack.TrackNumber, cancellationToken) + 1
|
||||
: 1;
|
||||
|
||||
await database.AlbumHasTracks.AddAsync(new AlbumHasTrack
|
||||
{
|
||||
AlbumId = request.AlbumId,
|
||||
TrackId = request.TrackId,
|
||||
TrackNumber = nextTrackNumber
|
||||
}, cancellationToken);
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Added track {TrackId} to album {AlbumId} as number {TrackNumber}",
|
||||
request.TrackId, request.AlbumId, nextTrackNumber);
|
||||
|
||||
return new Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Events;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record CreateAlbumCommand(
|
||||
long UserId,
|
||||
string Title,
|
||||
string? Description,
|
||||
int? ReleaseYear,
|
||||
Guid PictureIntentId)
|
||||
: ICommand<ErrorOr<AlbumApplicationResponse>>;
|
||||
|
||||
public class CreateAlbumCommandHandler(
|
||||
IEventBus eventBus,
|
||||
IDatabase database,
|
||||
UploadIntentValidator uploadIntentValidator,
|
||||
ILogger<CreateAlbumCommandHandler> logger,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
AlbumConfiguration albumConfiguration,
|
||||
UploadIntentConfiguration uploadIntentConfiguration)
|
||||
: ICommandHandler<CreateAlbumCommand, ErrorOr<AlbumApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(CreateAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userExists = await database.Users
|
||||
.AsNoTracking()
|
||||
.AnyAsync(user => user.Id == request.UserId, cancellationToken);
|
||||
if (!userExists)
|
||||
{
|
||||
logger.LogWarning("User {UserId} not found", request.UserId);
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
}
|
||||
|
||||
var pictureIntent = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration, request.PictureIntentId, request.UserId, cancellationToken);
|
||||
if (pictureIntent.IsError)
|
||||
return pictureIntent.Errors;
|
||||
|
||||
var intent = pictureIntent.Value;
|
||||
var title = request.Title.Trim();
|
||||
|
||||
var album = new Album
|
||||
{
|
||||
OwnerUserId = request.UserId,
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
Description = request.Description,
|
||||
ReleaseYear = request.ReleaseYear,
|
||||
Pictures = new AlbumPictures
|
||||
{
|
||||
OriginalName = intent.ObjectName,
|
||||
SmallName = intent.ObjectName,
|
||||
MediumName = intent.ObjectName,
|
||||
LargeName = intent.ObjectName
|
||||
}
|
||||
};
|
||||
|
||||
await database.Albums.AddAsync(album, cancellationToken);
|
||||
|
||||
var finalPictureKey = albumConfiguration.Routes.BuildOriginalPicturePath(request.UserId, intent.ObjectName);
|
||||
var publishResult = await PublishCreateAlbumEventAsync(album.Id, intent, finalPictureKey, cancellationToken);
|
||||
if (publishResult.IsError)
|
||||
return publishResult.Errors;
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to save album for user {UserId}", request.UserId);
|
||||
return Error.Failure(description: $"Failed to create album for user {request.UserId}");
|
||||
}
|
||||
|
||||
logger.LogInformation("Created album {AlbumId} for user {UserId}", album.Id, request.UserId);
|
||||
|
||||
return AlbumApplicationResponse.FromEntity(album, trackCount: 0);
|
||||
}
|
||||
|
||||
private async Task<ErrorOr<Success>> PublishCreateAlbumEventAsync(
|
||||
Guid albumId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await eventBus.PublishAsync(
|
||||
new CreateAlbumResourcesEvent(
|
||||
albumId,
|
||||
pictureIntent.Id,
|
||||
storageConfiguration.Bucket,
|
||||
pictureIntent.Key,
|
||||
finalPictureKey,
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.SmallPicturesPath,
|
||||
albumConfiguration.PicturesSizes.SmallPictureWidth,
|
||||
albumConfiguration.PicturesSizes.SmallPictureHeight),
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.MediumPicturesPath,
|
||||
albumConfiguration.PicturesSizes.MediumPictureWidth,
|
||||
albumConfiguration.PicturesSizes.MediumPictureHeight),
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.LargePicturesPath,
|
||||
albumConfiguration.PicturesSizes.LargePictureWidth,
|
||||
albumConfiguration.PicturesSizes.LargePictureHeight)),
|
||||
cancellationToken);
|
||||
return new Success();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to publish create album event for album {AlbumId}", albumId);
|
||||
return Error.Failure(description: $"Failed to publish create album event for album {albumId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record DeleteAlbumCommand(long UserId, Guid AlbumId)
|
||||
: ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class DeleteAlbumCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<DeleteAlbumCommandHandler> logger)
|
||||
: ICommandHandler<DeleteAlbumCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeleteAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.Albums
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogDebug("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (album.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("Album {AlbumId} does not belong to user {UserId}", request.AlbumId, request.UserId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
database.Albums.Remove(album);
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to delete album {AlbumId}", request.AlbumId);
|
||||
return Error.Failure(description: $"Failed to delete album {request.AlbumId}");
|
||||
}
|
||||
|
||||
logger.LogInformation("Deleted album {AlbumId} for user {UserId}", request.AlbumId, request.UserId);
|
||||
|
||||
return new Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumByIdQuery(Guid Id)
|
||||
: IQuery<ErrorOr<AlbumApplicationResponse>>;
|
||||
|
||||
public class GetAlbumByIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumByIdQuery, ErrorOr<AlbumApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(GetAlbumByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.Where(a => a.Id == request.Id)
|
||||
.Select(a => new
|
||||
{
|
||||
Album = a,
|
||||
TrackCount = a.AlbumTracks.Count,
|
||||
CoverTrackIds = a.AlbumTracks
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Take(AlbumApplicationResponse.CoverTrackCount)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (album == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return AlbumApplicationResponse.FromEntity(album.Album, album.TrackCount, album.CoverTrackIds);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MimeMapping;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumCoverQuery(Guid AlbumId, string Size)
|
||||
: IQuery<ErrorOr<AlbumCoverLocation>>;
|
||||
|
||||
public record AlbumCoverLocation(string Bucket, string Key, string ContentType);
|
||||
|
||||
public class GetAlbumCoverQueryHandler(
|
||||
IDatabase database,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
AlbumConfiguration albumConfiguration)
|
||||
: IQueryHandler<GetAlbumCoverQuery, ErrorOr<AlbumCoverLocation>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumCoverLocation>> Handle(GetAlbumCoverQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var pictures = await database.Albums.AsNoTracking()
|
||||
.Where(a => a.Id == request.AlbumId)
|
||||
.Select(a => a.Pictures)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (pictures == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var routes = albumConfiguration.Routes;
|
||||
var (name, key) = request.Size.ToLowerInvariant() switch
|
||||
{
|
||||
"small" => (pictures.SmallName, BuildKey(routes.BuildSmallPicturePath, pictures.SmallName)),
|
||||
"large" => (pictures.LargeName, BuildKey(routes.BuildLargePicturePath, pictures.LargeName)),
|
||||
_ => (pictures.MediumName, BuildKey(routes.BuildMediumPicturePath, pictures.MediumName))
|
||||
};
|
||||
|
||||
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(key))
|
||||
return Error.NotFound();
|
||||
|
||||
var contentType = MimeUtility.GetMimeMapping(name);
|
||||
return new AlbumCoverLocation(storageConfiguration.Bucket, key, contentType);
|
||||
}
|
||||
|
||||
private static string? BuildKey(Func<string, string> builder, string? name)
|
||||
=> string.IsNullOrEmpty(name) ? null : builder(name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumTracksQuery(
|
||||
Guid AlbumId,
|
||||
int PageNumber,
|
||||
int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<TrackApplicationResponse>>>;
|
||||
|
||||
public class GetAlbumTracksQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumTracksQuery, ErrorOr<PaginatedResponse<TrackApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<TrackApplicationResponse>>> Handle(GetAlbumTracksQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var albumExists = await database.Albums
|
||||
.AsNoTracking()
|
||||
.AnyAsync(album => album.Id == request.AlbumId, cancellationToken);
|
||||
if (!albumExists)
|
||||
return Error.NotFound();
|
||||
|
||||
var tracksQuery = database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(albumTrack => albumTrack.Track.Owner)
|
||||
.Include(albumTrack => albumTrack.Track.Tags)
|
||||
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId);
|
||||
|
||||
var totalCount = await tracksQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Select(albumTrack => new { albumTrack.Track, ListensCount = albumTrack.Track.ListeningHistories.Count })
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
|
||||
pagedEntities.Select(entry => TrackApplicationResponse.FromEntity(entry.Track, entry.ListensCount)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<TrackApplicationResponse>.FromPagedList(pagedTracks);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<AlbumsSearchResponse>>;
|
||||
|
||||
public class GetAlbumsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumsQuery, ErrorOr<AlbumsSearchResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumsSearchResponse>> Handle(GetAlbumsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var albumsQuery = database.Albums
|
||||
.AsNoTracking()
|
||||
.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrEmpty(request.Title))
|
||||
{
|
||||
var normalizedTitle = request.Title.Trim().ToUpperInvariant();
|
||||
albumsQuery = albumsQuery.Where(album => album.NormalizedTitle.Contains(normalizedTitle));
|
||||
}
|
||||
|
||||
var totalCount = await albumsQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await albumsQuery
|
||||
.OrderByDescending(album => album.CreatedAt)
|
||||
.Select(album => new
|
||||
{
|
||||
Album = album,
|
||||
TrackCount = album.AlbumTracks.Count,
|
||||
CoverTrackIds = album.AlbumTracks
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Take(AlbumApplicationResponse.CoverTrackCount)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var items = pagedEntities
|
||||
.Select(entry => AlbumSearchItemResponse.FromAlbum(
|
||||
AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)))
|
||||
.ToList();
|
||||
|
||||
return new AlbumsSearchResponse(
|
||||
items,
|
||||
pagedEntities.PageNumber,
|
||||
pagedEntities.PageSize,
|
||||
pagedEntities.PageCount,
|
||||
pagedEntities.TotalItemCount,
|
||||
pagedEntities.HasPreviousPage,
|
||||
pagedEntities.HasNextPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumsByUserIdQuery(long UserId, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>;
|
||||
|
||||
public class GetAlbumsByUserIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumsByUserIdQuery, ErrorOr<PaginatedResponse<AlbumApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<AlbumApplicationResponse>>> Handle(GetAlbumsByUserIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userExists = await database.Users
|
||||
.AsNoTracking()
|
||||
.AnyAsync(user => user.Id == request.UserId, cancellationToken);
|
||||
if (!userExists)
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
|
||||
var albumsQuery = database.Albums
|
||||
.AsNoTracking()
|
||||
.Where(album => album.OwnerUserId == request.UserId);
|
||||
|
||||
var totalCount = await albumsQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await albumsQuery
|
||||
.OrderByDescending(album => album.CreatedAt)
|
||||
.Select(album => new
|
||||
{
|
||||
Album = album,
|
||||
TrackCount = album.AlbumTracks.Count,
|
||||
CoverTrackIds = album.AlbumTracks
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Take(AlbumApplicationResponse.CoverTrackCount)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedAlbums = new StaticPagedList<AlbumApplicationResponse>(
|
||||
pagedEntities.Select(entry => AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<AlbumApplicationResponse>.FromPagedList(pagedAlbums);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetRecentlyListenedAlbumsQuery(long UserId, int Limit)
|
||||
: IQuery<ErrorOr<IReadOnlyList<AlbumApplicationResponse>>>;
|
||||
|
||||
public class GetRecentlyListenedAlbumsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetRecentlyListenedAlbumsQuery, ErrorOr<IReadOnlyList<AlbumApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<IReadOnlyList<AlbumApplicationResponse>>> Handle(GetRecentlyListenedAlbumsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var listenedTrackIds = database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(history => history.UserId == request.UserId);
|
||||
|
||||
var ranked = await database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.Join(
|
||||
listenedTrackIds,
|
||||
albumTrack => albumTrack.TrackId,
|
||||
history => history.TrackId,
|
||||
(albumTrack, history) => new { albumTrack.AlbumId, history.ListenedAt })
|
||||
.GroupBy(entry => entry.AlbumId)
|
||||
.Select(group => new { AlbumId = group.Key, LastListenedAt = group.Max(entry => entry.ListenedAt) })
|
||||
.OrderByDescending(entry => entry.LastListenedAt)
|
||||
.Take(request.Limit)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (ranked.Count == 0)
|
||||
return new List<AlbumApplicationResponse>();
|
||||
|
||||
var albumIds = ranked.Select(entry => entry.AlbumId).ToList();
|
||||
|
||||
var albums = await database.Albums
|
||||
.AsNoTracking()
|
||||
.Where(album => albumIds.Contains(album.Id))
|
||||
.Select(album => new
|
||||
{
|
||||
Album = album,
|
||||
TrackCount = album.AlbumTracks.Count,
|
||||
CoverTrackIds = album.AlbumTracks
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Take(AlbumApplicationResponse.CoverTrackCount)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.ToDictionaryAsync(entry => entry.Album.Id, cancellationToken);
|
||||
|
||||
return ranked
|
||||
.Where(entry => albums.ContainsKey(entry.AlbumId))
|
||||
.Select(entry => albums[entry.AlbumId])
|
||||
.Select(entry => AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record RemoveTrackFromAlbumCommand(long UserId, Guid AlbumId, Guid TrackId)
|
||||
: ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class RemoveTrackFromAlbumCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<RemoveTrackFromAlbumCommandHandler> logger)
|
||||
: ICommandHandler<RemoveTrackFromAlbumCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(RemoveTrackFromAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (album.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} is not the owner of album {AlbumId}", request.UserId, request.AlbumId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var albumTracks = await database.AlbumHasTracks
|
||||
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId)
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var link = albumTracks.SingleOrDefault(albumTrack => albumTrack.TrackId == request.TrackId);
|
||||
if (link == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not in album {AlbumId}", request.TrackId, request.AlbumId);
|
||||
return Error.NotFound(description: "Track is not in the album.");
|
||||
}
|
||||
|
||||
database.AlbumHasTracks.Remove(link);
|
||||
|
||||
var trackNumber = 1;
|
||||
foreach (var remaining in albumTracks.Where(albumTrack => albumTrack.Id != link.Id))
|
||||
remaining.TrackNumber = trackNumber++;
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Removed track {TrackId} from album {AlbumId}", request.TrackId, request.AlbumId);
|
||||
|
||||
return new Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record RequestAlbumPictureUploadCommand(
|
||||
long UserId,
|
||||
string FileType,
|
||||
string ContentType,
|
||||
long? ExpectedSizeBytes = null)
|
||||
: ICommand<ErrorOr<AlbumPictureUploadResponse>>;
|
||||
|
||||
public class RequestAlbumPictureUploadCommandHandler(
|
||||
IDatabase database,
|
||||
UploadIntentValidator uploadIntentValidator,
|
||||
IStorageService storageService,
|
||||
ILogger<RequestAlbumPictureUploadCommandHandler> logger,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
AlbumConfiguration albumConfiguration,
|
||||
UploadIntentConfiguration uploadIntentConfiguration)
|
||||
: ICommandHandler<RequestAlbumPictureUploadCommand, ErrorOr<AlbumPictureUploadResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumPictureUploadResponse>> Handle(RequestAlbumPictureUploadCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userExists = await database.Users
|
||||
.AsNoTracking()
|
||||
.AnyAsync(u => u.Id == request.UserId, cancellationToken);
|
||||
if (!userExists)
|
||||
{
|
||||
logger.LogWarning("User {UserId} not found", request.UserId);
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
}
|
||||
|
||||
var effectiveSizeBytes = request.ExpectedSizeBytes
|
||||
?? uploadIntentConfiguration.DefaultExpectedPictureSizeBytes;
|
||||
|
||||
var objectName = $"{Guid.NewGuid()}.{request.FileType.TrimStart('.').ToLowerInvariant()}";
|
||||
|
||||
var tempKey = albumConfiguration.Routes.BuildTempPicturePath(
|
||||
uploadIntentConfiguration.TemporalRootPrefix, request.UserId, objectName);
|
||||
|
||||
try
|
||||
{
|
||||
var uploadUrl = await storageService.GetUploadUrlAsync(
|
||||
storageConfiguration.Bucket,
|
||||
tempKey,
|
||||
request.ContentType,
|
||||
TimeSpan.FromSeconds(uploadIntentConfiguration.UploadUrlExpiresInSeconds),
|
||||
cancellationToken);
|
||||
|
||||
await using var transaction = await database.BeginTransactionAsync(
|
||||
System.Data.IsolationLevel.Serializable, cancellationToken);
|
||||
|
||||
var quotaCheck = await uploadIntentValidator.CheckQuotaAsync(
|
||||
uploadIntentConfiguration,
|
||||
request.UserId, effectiveSizeBytes, 1, cancellationToken);
|
||||
if (quotaCheck.IsError)
|
||||
{
|
||||
logger.LogWarning("User {UserId} failed upload intent quota check", request.UserId);
|
||||
return quotaCheck.Errors;
|
||||
}
|
||||
|
||||
var intent = new UploadIntent
|
||||
{
|
||||
UserId = request.UserId,
|
||||
Bucket = storageConfiguration.Bucket,
|
||||
Key = tempKey,
|
||||
ObjectName = objectName,
|
||||
ContentType = request.ContentType,
|
||||
ExpectedSizeBytes = effectiveSizeBytes,
|
||||
Purpose = UploadIntentPurpose.AlbumPicture,
|
||||
ExpiresAt = DateTime.UtcNow.AddSeconds(uploadIntentConfiguration.UploadUrlExpiresInSeconds),
|
||||
};
|
||||
|
||||
await database.UploadIntents.AddAsync(intent, cancellationToken);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Issued upload intent {IntentId} for user {UserId} (AlbumPicture, temp key: {Key})", intent.Id, request.UserId, tempKey);
|
||||
|
||||
return new AlbumPictureUploadResponse(
|
||||
intent.Id,
|
||||
storageConfiguration.Bucket,
|
||||
tempKey,
|
||||
objectName,
|
||||
request.ContentType,
|
||||
uploadIntentConfiguration.UploadUrlExpiresInSeconds,
|
||||
uploadUrl);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to generate album picture upload URL for user {UserId}", request.UserId);
|
||||
return Error.Failure(description: "Failed to generate upload URL");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Application.Serialization;
|
||||
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
public record AlbumApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Description,
|
||||
int? ReleaseYear,
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId,
|
||||
int TrackCount,
|
||||
string? SmallImageKeyName,
|
||||
string? MediumImageKeyName,
|
||||
string? LargeImageKeyName,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
IReadOnlyList<Guid> CoverTrackIds)
|
||||
{
|
||||
public const int CoverTrackCount = 4;
|
||||
|
||||
public static AlbumApplicationResponse FromEntity(
|
||||
Album album,
|
||||
int trackCount,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
return new AlbumApplicationResponse(
|
||||
album.Id,
|
||||
album.Title,
|
||||
album.Description,
|
||||
album.ReleaseYear,
|
||||
album.OwnerUserId,
|
||||
trackCount,
|
||||
album.Pictures?.SmallName,
|
||||
album.Pictures?.MediumName,
|
||||
album.Pictures?.LargeName,
|
||||
album.CreatedAt,
|
||||
album.UpdatedAt,
|
||||
coverTrackIds ?? []);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
public record AlbumPictureUploadResponse(
|
||||
Guid IntentId,
|
||||
string Bucket,
|
||||
string Key,
|
||||
string PictureName,
|
||||
string ContentType,
|
||||
int ExpiresInSeconds,
|
||||
string UploadUrl);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
public record AlbumSearchItemResponse(AlbumApplicationResponse Album)
|
||||
{
|
||||
public static AlbumSearchItemResponse FromAlbum(AlbumApplicationResponse album) => new(album);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
|
||||
public record AlbumsSearchResponse(
|
||||
IReadOnlyList<AlbumSearchItemResponse> Items,
|
||||
int PageNumber,
|
||||
int PageSize,
|
||||
int PageCount,
|
||||
int TotalItemCount,
|
||||
bool HasPreviousPage,
|
||||
bool HasNextPage);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Events;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record UpdateAlbumCommand(
|
||||
long UserId,
|
||||
Guid AlbumId,
|
||||
string Title,
|
||||
string? Description,
|
||||
int? ReleaseYear,
|
||||
Guid? NewPictureIntentId)
|
||||
: ICommand<ErrorOr<AlbumApplicationResponse>>;
|
||||
|
||||
public class UpdateAlbumCommandHandler(
|
||||
IEventBus eventBus,
|
||||
IDatabase database,
|
||||
UploadIntentValidator uploadIntentValidator,
|
||||
ILogger<UpdateAlbumCommandHandler> logger,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
AlbumConfiguration albumConfiguration,
|
||||
UploadIntentConfiguration uploadIntentConfiguration)
|
||||
: ICommandHandler<UpdateAlbumCommand, ErrorOr<AlbumApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(UpdateAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.Albums
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (album.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("Album {AlbumId} does not belong to user {UserId}", request.AlbumId, request.UserId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var title = request.Title.Trim();
|
||||
|
||||
album.Title = title;
|
||||
album.NormalizedTitle = title.ToUpperInvariant();
|
||||
album.Description = request.Description;
|
||||
album.ReleaseYear = request.ReleaseYear;
|
||||
|
||||
UploadIntent? pictureIntent = null;
|
||||
string? finalPictureKey = null;
|
||||
|
||||
if (request.NewPictureIntentId.HasValue)
|
||||
{
|
||||
var validation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration,
|
||||
request.NewPictureIntentId.Value, request.UserId, cancellationToken);
|
||||
if (validation.IsError)
|
||||
return validation.Errors;
|
||||
|
||||
pictureIntent = validation.Value;
|
||||
album.Pictures = new AlbumPictures
|
||||
{
|
||||
OriginalName = pictureIntent.ObjectName,
|
||||
SmallName = pictureIntent.ObjectName,
|
||||
MediumName = pictureIntent.ObjectName,
|
||||
LargeName = pictureIntent.ObjectName
|
||||
};
|
||||
finalPictureKey = albumConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
|
||||
}
|
||||
|
||||
if (pictureIntent != null && finalPictureKey != null)
|
||||
{
|
||||
var publishResult = await PublishUpdateAlbumPictureSourceEventAsync(
|
||||
album.Id, pictureIntent, finalPictureKey, cancellationToken);
|
||||
if (publishResult.IsError)
|
||||
return publishResult.Errors;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to update album {AlbumId}", request.AlbumId);
|
||||
return Error.Failure(description: $"Failed to update album {request.AlbumId}");
|
||||
}
|
||||
|
||||
var albumTracks = database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(albumTrack => albumTrack.AlbumId == album.Id);
|
||||
|
||||
var trackCount = await albumTracks.CountAsync(cancellationToken);
|
||||
var coverTrackIds = await albumTracks
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Take(AlbumApplicationResponse.CoverTrackCount)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Updated album {AlbumId}", album.Id);
|
||||
return AlbumApplicationResponse.FromEntity(album, trackCount, coverTrackIds);
|
||||
}
|
||||
|
||||
private async Task<ErrorOr<Success>> PublishUpdateAlbumPictureSourceEventAsync(
|
||||
Guid albumId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await eventBus.PublishAsync(
|
||||
new UpdateAlbumPictureSourceEvent(
|
||||
albumId,
|
||||
pictureIntent.Id,
|
||||
storageConfiguration.Bucket,
|
||||
pictureIntent.Key,
|
||||
finalPictureKey,
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.SmallPicturesPath,
|
||||
albumConfiguration.PicturesSizes.SmallPictureWidth,
|
||||
albumConfiguration.PicturesSizes.SmallPictureHeight),
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.MediumPicturesPath,
|
||||
albumConfiguration.PicturesSizes.MediumPictureWidth,
|
||||
albumConfiguration.PicturesSizes.MediumPictureHeight),
|
||||
new ImageSize(
|
||||
albumConfiguration.Routes.LargePicturesPath,
|
||||
albumConfiguration.PicturesSizes.LargePictureWidth,
|
||||
albumConfiguration.PicturesSizes.LargePictureHeight)),
|
||||
cancellationToken);
|
||||
return new Success();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to publish update album picture source event for album {AlbumId}", albumId);
|
||||
return Error.Failure(description: $"Failed to publish update album picture source event for album {albumId}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -1,5 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>Musify.Application</AssemblyName>
|
||||
<RootNamespace>Musify.Application</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ErrorOr" />
|
||||
<PackageReference Include="MassTransit" />
|
||||
@@ -13,12 +18,13 @@
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" />
|
||||
<PackageReference Include="MimeMapping" />
|
||||
<PackageReference Include="X.PagedList" />
|
||||
<PackageReference Include="X.PagedList.EF" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Musify.Domain\Musify.Domain.csproj" />
|
||||
<ProjectReference Include="..\Musify.Domain\Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+4
-1
@@ -1,4 +1,3 @@
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Musify.Application.Configuration;
|
||||
@@ -12,12 +11,16 @@ public static class ApplicationDependencyInjection
|
||||
{
|
||||
services.AddMediator();
|
||||
services.AddScoped<UploadIntentValidator>();
|
||||
services.AddScoped<TrackStreamIssuer>();
|
||||
|
||||
services.AddValidatedOptions<ApplicationStorageConfiguration>(configuration, ApplicationStorageConfiguration.SectionName);
|
||||
services.AddValidatedOptions<PlayListConfiguration>(configuration, PlayListConfiguration.SectionName);
|
||||
services.AddValidatedOptions<AlbumConfiguration>(configuration, AlbumConfiguration.SectionName);
|
||||
services.AddValidatedOptions<TrackConfiguration>(configuration, TrackConfiguration.SectionName);
|
||||
services.AddValidatedOptions<MixConfiguration>(configuration, MixConfiguration.SectionName);
|
||||
services.AddValidatedOptions<StreamGatewayConfiguration>(configuration, StreamGatewayConfiguration.SectionName);
|
||||
services.AddValidatedOptions<UploadIntentConfiguration>(configuration, UploadIntentConfiguration.SectionName);
|
||||
services.AddValidatedOptions<PlaybackConfiguration>(configuration, PlaybackConfiguration.SectionName);
|
||||
|
||||
return services;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Musify.Application.Shared;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
public class AlbumConfiguration
|
||||
{
|
||||
public const string SectionName = "Album";
|
||||
|
||||
[Required]
|
||||
public AlbumRoutes Routes { get; set; } = new AlbumRoutes();
|
||||
|
||||
[Required]
|
||||
public AlbumPicturesSizes PicturesSizes { get; set; } = new AlbumPicturesSizes();
|
||||
}
|
||||
|
||||
public class AlbumRoutes
|
||||
{
|
||||
[Required]
|
||||
public string UploadsFolder { get; set; } = "uploads";
|
||||
|
||||
[Required]
|
||||
public string ParentFolders { get; set; } = "Albums";
|
||||
|
||||
[Required]
|
||||
public string OriginalPicturesFolder { get; set; } = "OriginalPictures";
|
||||
|
||||
[Required]
|
||||
public string SmallPicturesFolder { get; set; } = "SmallPictures";
|
||||
|
||||
[Required]
|
||||
public string MediumPicturesFolder { get; set; } = "MediumPictures";
|
||||
|
||||
[Required]
|
||||
public string LargePicturesFolder { get; set; } = "LargePictures";
|
||||
|
||||
public string SmallPicturesPath => StorageKey.Combine(ParentFolders, SmallPicturesFolder);
|
||||
|
||||
public string MediumPicturesPath => StorageKey.Combine(ParentFolders, MediumPicturesFolder);
|
||||
|
||||
public string LargePicturesPath => StorageKey.Combine(ParentFolders, LargePicturesFolder);
|
||||
|
||||
public string OriginalPicturesPath => StorageKey.Combine(ParentFolders, OriginalPicturesFolder);
|
||||
|
||||
public string BuildOriginalPicturePath(string pictureName) => StorageKey.Combine(ParentFolders, OriginalPicturesFolder, pictureName);
|
||||
|
||||
public string BuildOriginalPicturePath(long userId, string pictureName) => StorageKey.Combine(UploadsFolder, userId.ToString(), ParentFolders, OriginalPicturesFolder, pictureName);
|
||||
|
||||
public string BuildSmallPicturePath(string pictureName) => StorageKey.Combine(ParentFolders, SmallPicturesFolder, pictureName);
|
||||
|
||||
public string BuildMediumPicturePath(string pictureName) => StorageKey.Combine(ParentFolders, MediumPicturesFolder, pictureName);
|
||||
|
||||
public string BuildLargePicturePath(string pictureName) => StorageKey.Combine(ParentFolders, LargePicturesFolder, pictureName);
|
||||
|
||||
public string BuildTempPicturePath(string tempRootPrefix, long userId, string objectName) =>
|
||||
StorageKey.Combine(tempRootPrefix, userId.ToString(), ParentFolders, objectName);
|
||||
}
|
||||
|
||||
public class AlbumPicturesSizes
|
||||
{
|
||||
[Range(1, 1024)]
|
||||
public int SmallPictureWidth { get; set; } = 128;
|
||||
|
||||
[Range(1, 1024)]
|
||||
public int SmallPictureHeight { get; set; } = 128;
|
||||
|
||||
[Range(1, 1024)]
|
||||
public int MediumPictureWidth { get; set; } = 256;
|
||||
|
||||
[Range(1, 1024)]
|
||||
public int MediumPictureHeight { get; set; } = 256;
|
||||
|
||||
[Range(1, 1024)]
|
||||
public int LargePictureWidth { get; set; } = 512;
|
||||
|
||||
[Range(1, 1024)]
|
||||
public int LargePictureHeight { get; set; } = 512;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Mediator;
|
||||
using Musify.Application.Configuration.Responses;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
|
||||
public record GetPlaybackPublicConfigQuery : IQuery<PlaybackPublicConfigResponse>;
|
||||
|
||||
public class GetPlaybackPublicConfigQueryHandler(PlaybackConfiguration playbackConfiguration)
|
||||
: IQueryHandler<GetPlaybackPublicConfigQuery, PlaybackPublicConfigResponse>
|
||||
{
|
||||
public ValueTask<PlaybackPublicConfigResponse> Handle(GetPlaybackPublicConfigQuery query, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult(new PlaybackPublicConfigResponse(
|
||||
playbackConfiguration.AllowAnonymousListening,
|
||||
playbackConfiguration.AnonymousFragmentSeconds));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
public class MixConfiguration
|
||||
{
|
||||
public const string SectionName = "Mix";
|
||||
|
||||
[Range(4, 100)]
|
||||
public int ItemsPerMix { get; set; } = 12;
|
||||
}
|
||||
}
|
||||
-18
@@ -34,30 +34,12 @@ namespace Musify.Application.Configuration
|
||||
[Required]
|
||||
public string LargePicturesFolder { get; set; } = "LargePictures";
|
||||
|
||||
[Required]
|
||||
public string PresetOriginalPicture { get; set; } = "PresetOriginalPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetSmallPicture { get; set; } = "PresetSmallPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetMediumPicture { get; set; } = "PresetMediumPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetLargePicture { get; set; } = "PresetLargePicture.webp";
|
||||
|
||||
public string SmallPicturesPath => StorageKey.Combine(ParentFolders, SmallPicturesFolder);
|
||||
|
||||
public string MediumPicturesPath => StorageKey.Combine(ParentFolders, MediumPicturesFolder);
|
||||
|
||||
public string LargePicturesPath => StorageKey.Combine(ParentFolders, LargePicturesFolder);
|
||||
|
||||
public string PresetSmallPicturePath => StorageKey.Combine(ParentFolders, PresetSmallPicture);
|
||||
|
||||
public string PresetMediumPicturePath => StorageKey.Combine(ParentFolders, PresetMediumPicture);
|
||||
|
||||
public string PresetLargePicturePath => StorageKey.Combine(ParentFolders, PresetLargePicture);
|
||||
|
||||
public string OriginalPicturesPath => StorageKey.Combine(ParentFolders, OriginalPicturesFolder);
|
||||
|
||||
public string BuildOriginalPicturePath(string pictureName) => StorageKey.Combine(ParentFolders, OriginalPicturesFolder, pictureName);
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
|
||||
public sealed class PlaybackConfiguration
|
||||
{
|
||||
public const string SectionName = "Playback";
|
||||
|
||||
public bool AllowAnonymousListening { get; set; }
|
||||
|
||||
[Range(0, 3600)]
|
||||
public int AnonymousFragmentSeconds { get; set; }
|
||||
|
||||
[Range(1, int.MaxValue)]
|
||||
public int EstimatedAudioBytesPerSecond { get; set; } = 16_000;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
namespace Musify.Application.Configuration.Responses
|
||||
{
|
||||
|
||||
public record PlaybackPublicConfigResponse(bool AllowAnonymousListening, int AnonymousFragmentSeconds);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Musify.Application.Contracts
|
||||
{
|
||||
public record AudioTranscodeResult(int StatusCode, TimeSpan Duration);
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@ namespace Musify.Application.Contracts
|
||||
{
|
||||
public interface IAudioTranscoderService
|
||||
{
|
||||
Task<int> TranscodeToAudioFileAsync(Stream audioStream, string destinationPath, CancellationToken cancellationToken);
|
||||
Task<AudioTranscodeResult> TranscodeToAudioFileAsync(Stream audioStream, string destinationPath, CancellationToken cancellationToken);
|
||||
|
||||
Task<bool> IsValidAudioFileAsync(string filePath, CancellationToken cancellationToken);
|
||||
}
|
||||
+16
@@ -9,16 +9,32 @@ namespace Musify.Application.Contracts
|
||||
|
||||
DbSet<PlayList> PlayLists { get; }
|
||||
|
||||
DbSet<Album> Albums { get; }
|
||||
|
||||
DbSet<AlbumHasTrack> AlbumHasTracks { get; }
|
||||
|
||||
DbSet<Track> Tracks { get; }
|
||||
|
||||
DbSet<UserHasTrack> UserHasTracks { get; }
|
||||
|
||||
DbSet<PlayListHasTrack> PlayListHasTracks { get; }
|
||||
|
||||
DbSet<Mix> Mixes { get; }
|
||||
|
||||
DbSet<MixItem> MixItems { get; }
|
||||
|
||||
DbSet<Upload> Uploads { get; }
|
||||
|
||||
DbSet<UploadIntent> UploadIntents { get; }
|
||||
|
||||
DbSet<ListeningHistory> ListeningHistories { get; }
|
||||
|
||||
DbSet<TrackLike> TrackLikes { get; }
|
||||
|
||||
DbSet<TrackTag> TrackTags { get; }
|
||||
|
||||
DbSet<UserFollow> UserFollows { get; }
|
||||
|
||||
Task<IDatabaseTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken);
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
+2
-1
@@ -2,7 +2,8 @@ namespace Musify.Application.Contracts
|
||||
{
|
||||
public interface IStreamTicketService
|
||||
{
|
||||
StreamTicket IssueTicket(long userId, string keyPrefix);
|
||||
|
||||
StreamTicket IssueTicket(long? userId, string keyPrefix, long? maxBytes = null);
|
||||
}
|
||||
|
||||
public record StreamTicket(string Token, int ExpiresInSeconds);
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record AlbumPictureProcessed(Guid AlbumId);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record AlbumPictureProcessingFailed(Guid AlbumId);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record AlbumProcessingFailed(
|
||||
Guid AlbumId,
|
||||
string? Bucket,
|
||||
string? PictureKey);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Musify.Application.Shared;
|
||||
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record CreateAlbumResourcesEvent(
|
||||
Guid AlbumId,
|
||||
Guid PictureIntentId,
|
||||
string Bucket,
|
||||
string PictureSourceKey,
|
||||
string PictureDestinationKey,
|
||||
ImageSize Small,
|
||||
ImageSize Medium,
|
||||
ImageSize Large);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using Musify.Application.Shared;
|
||||
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record UpdateAlbumPictureEvent(
|
||||
Guid AlbumId,
|
||||
string Bucket,
|
||||
string SourceKey,
|
||||
ImageSize Small,
|
||||
ImageSize Medium,
|
||||
ImageSize Large);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Musify.Application.Shared;
|
||||
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record UpdateAlbumPictureSourceEvent(
|
||||
Guid AlbumId,
|
||||
Guid PictureIntentId,
|
||||
string Bucket,
|
||||
string PictureSourceKey,
|
||||
string PictureDestinationKey,
|
||||
ImageSize Small,
|
||||
ImageSize Medium,
|
||||
ImageSize Large);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
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 => like.Track.Owner)
|
||||
.Include(like => like.Track.Tags)
|
||||
.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,56 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Likes
|
||||
{
|
||||
public record ToggleTrackLikeCommand(long UserId, Guid TrackId)
|
||||
: ICommand<ErrorOr<bool>>;
|
||||
|
||||
public class ToggleTrackLikeCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<ToggleTrackLikeCommandHandler> logger)
|
||||
: ICommandHandler<ToggleTrackLikeCommand, ErrorOr<bool>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<bool>> Handle(ToggleTrackLikeCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackExists = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.AnyAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (!trackExists)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound(description: $"Track {request.TrackId} not found");
|
||||
}
|
||||
|
||||
var existingLike = await database.TrackLikes
|
||||
.SingleOrDefaultAsync(like => like.UserId == request.UserId && like.TrackId == request.TrackId, cancellationToken);
|
||||
|
||||
bool nowLiked;
|
||||
if (existingLike != null)
|
||||
{
|
||||
database.TrackLikes.Remove(existingLike);
|
||||
nowLiked = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
await database.TrackLikes.AddAsync(new TrackLike
|
||||
{
|
||||
UserId = request.UserId,
|
||||
TrackId = request.TrackId
|
||||
}, cancellationToken);
|
||||
nowLiked = true;
|
||||
}
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("User {UserId} {Action} track {TrackId}",
|
||||
request.UserId, nowLiked ? "liked" : "unliked", request.TrackId);
|
||||
|
||||
return nowLiked;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Mixes
|
||||
{
|
||||
public record GenerateMixesForUserCommand(long UserId)
|
||||
: ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class GenerateMixesForUserCommandHandler(
|
||||
IDatabase database,
|
||||
MixConfiguration mixConfiguration,
|
||||
ILogger<GenerateMixesForUserCommandHandler> logger)
|
||||
: ICommandHandler<GenerateMixesForUserCommand, ErrorOr<Success>>
|
||||
{
|
||||
private sealed record MixDraft(string Title, string? Subtitle, IReadOnlyList<Guid> TrackIds);
|
||||
|
||||
public async ValueTask<ErrorOr<Success>> Handle(GenerateMixesForUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = request.UserId;
|
||||
|
||||
var libraryTrackIds = await database.UserHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(userTrack => userTrack.UserId == userId && userTrack.Track.LifeCycleStatus == LifeCycleStatus.Active)
|
||||
.Select(userTrack => userTrack.TrackId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (libraryTrackIds.Count == 0)
|
||||
{
|
||||
logger.LogInformation("User {UserId} has no tracks yet, skipping mix generation", userId);
|
||||
return new Success();
|
||||
}
|
||||
|
||||
var historyTrackIds = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(history => history.UserId == userId)
|
||||
.Select(history => history.TrackId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var historySet = new HashSet<Guid>(historyTrackIds);
|
||||
var unheardTrackIds = libraryTrackIds.Where(id => !historySet.Contains(id)).ToList();
|
||||
|
||||
var drafts = new List<MixDraft>();
|
||||
|
||||
var discovery = Take(Shuffle(unheardTrackIds));
|
||||
if (discovery.Count > 0)
|
||||
{
|
||||
drafts.Add(new MixDraft(
|
||||
"Descubrimiento",
|
||||
"Canciones de tu biblioteca que todavía no has escuchado.",
|
||||
discovery));
|
||||
}
|
||||
|
||||
var daily = Take(Interleave(Shuffle(historyTrackIds), Shuffle(unheardTrackIds)));
|
||||
if (daily.Count > 0)
|
||||
{
|
||||
drafts.Add(new MixDraft(
|
||||
"Tu mezcla diaria",
|
||||
"Lo que más escuchas, con alguna sorpresa de tu biblioteca.",
|
||||
daily));
|
||||
}
|
||||
|
||||
if (drafts.Count == 0)
|
||||
{
|
||||
logger.LogInformation("No candidate songs found for user {UserId}, skipping mix generation", userId);
|
||||
return new Success();
|
||||
}
|
||||
|
||||
await ReplaceMixesAsync(userId, drafts, cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to generate mixes for user {UserId}", userId);
|
||||
return Error.Failure(description: $"Failed to generate mixes for user {userId}");
|
||||
}
|
||||
|
||||
logger.LogInformation("Generated {Count} mixes for user {UserId}", drafts.Count, userId);
|
||||
return new Success();
|
||||
}
|
||||
|
||||
private List<Guid> Take(IEnumerable<Guid> trackIds) =>
|
||||
[.. trackIds.Take(mixConfiguration.ItemsPerMix)];
|
||||
|
||||
private static List<Guid> Shuffle(IEnumerable<Guid> trackIds) =>
|
||||
[.. trackIds.OrderBy(_ => Guid.NewGuid())];
|
||||
|
||||
private static List<Guid> Interleave(IReadOnlyList<Guid> first, IReadOnlyList<Guid> second)
|
||||
{
|
||||
var merged = new List<Guid>(first.Count + second.Count);
|
||||
for (var index = 0; index < Math.Max(first.Count, second.Count); index++)
|
||||
{
|
||||
if (index < first.Count)
|
||||
merged.Add(first[index]);
|
||||
if (index < second.Count)
|
||||
merged.Add(second[index]);
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
private async Task ReplaceMixesAsync(long userId, IReadOnlyList<MixDraft> drafts, CancellationToken cancellationToken)
|
||||
{
|
||||
var previousMixes = await database.Mixes
|
||||
.Where(mix => mix.UserId == userId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (previousMixes.Count > 0)
|
||||
{
|
||||
var previousIds = previousMixes.Select(mix => mix.Id).ToList();
|
||||
var previousItems = await database.MixItems
|
||||
.Where(item => previousIds.Contains(item.MixId))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
database.MixItems.RemoveRange(previousItems);
|
||||
database.Mixes.RemoveRange(previousMixes);
|
||||
}
|
||||
|
||||
for (var position = 0; position < drafts.Count; position++)
|
||||
{
|
||||
var draft = drafts[position];
|
||||
var mix = new Mix
|
||||
{
|
||||
UserId = userId,
|
||||
Title = draft.Title,
|
||||
Subtitle = draft.Subtitle,
|
||||
Position = position
|
||||
};
|
||||
|
||||
await database.Mixes.AddAsync(mix, cancellationToken);
|
||||
|
||||
for (var itemPosition = 0; itemPosition < draft.TrackIds.Count; itemPosition++)
|
||||
{
|
||||
await database.MixItems.AddAsync(new MixItem
|
||||
{
|
||||
MixId = mix.Id,
|
||||
Position = itemPosition,
|
||||
TrackId = draft.TrackIds[itemPosition]
|
||||
}, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Mixes.Responses;
|
||||
|
||||
namespace Musify.Application.Mixes
|
||||
{
|
||||
public record GetMixByIdQuery(long UserId, Guid MixId)
|
||||
: IQuery<ErrorOr<MixApplicationResponse>>;
|
||||
|
||||
public class GetMixByIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetMixByIdQuery, ErrorOr<MixApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<MixApplicationResponse>> Handle(GetMixByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var mix = await database.Mixes
|
||||
.AsNoTracking()
|
||||
.Include(mix => mix.Items)
|
||||
.SingleOrDefaultAsync(mix => mix.Id == request.MixId && mix.UserId == request.UserId, cancellationToken);
|
||||
|
||||
if (mix == null)
|
||||
return Error.NotFound(description: $"Mix {request.MixId} was not found");
|
||||
|
||||
var orderedItems = mix.Items.OrderBy(item => item.Position).ToList();
|
||||
var items = await MixItemMapper.ToResponsesAsync(database, orderedItems, cancellationToken);
|
||||
|
||||
return new MixApplicationResponse(mix.Id, mix.Title, mix.Subtitle, items.Count, items);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Mixes.Responses;
|
||||
|
||||
namespace Musify.Application.Mixes
|
||||
{
|
||||
public record GetMixesByUserIdQuery(long UserId)
|
||||
: IQuery<ErrorOr<IReadOnlyList<MixApplicationResponse>>>;
|
||||
|
||||
public class GetMixesByUserIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetMixesByUserIdQuery, ErrorOr<IReadOnlyList<MixApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<IReadOnlyList<MixApplicationResponse>>> Handle(GetMixesByUserIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var mixes = await database.Mixes
|
||||
.AsNoTracking()
|
||||
.Where(mix => mix.UserId == request.UserId)
|
||||
.Include(mix => mix.Items)
|
||||
.OrderBy(mix => mix.Position)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var responses = new List<MixApplicationResponse>(mixes.Count);
|
||||
foreach (var mix in mixes)
|
||||
{
|
||||
var orderedItems = mix.Items.OrderBy(item => item.Position).ToList();
|
||||
var coverItems = await MixItemMapper.ToResponsesAsync(
|
||||
database, orderedItems.Take(MixApplicationResponse.CoverItemCount).ToList(), cancellationToken);
|
||||
|
||||
responses.Add(new MixApplicationResponse(mix.Id, mix.Title, mix.Subtitle, orderedItems.Count, coverItems));
|
||||
}
|
||||
|
||||
return responses;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Mixes.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Mixes
|
||||
{
|
||||
|
||||
internal static class MixItemMapper
|
||||
{
|
||||
public static async Task<List<MixItemApplicationResponse>> ToResponsesAsync(
|
||||
IDatabase database,
|
||||
IReadOnlyList<MixItem> orderedItems,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var trackIds = orderedItems.Select(item => item.TrackId).Distinct().ToList();
|
||||
|
||||
var tracksById = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(track => track.Owner)
|
||||
.Where(track => trackIds.Contains(track.Id))
|
||||
.Select(track => new { Track = track, ListensCount = track.ListeningHistories.Count })
|
||||
.ToDictionaryAsync(x => x.Track.Id, cancellationToken);
|
||||
|
||||
return orderedItems
|
||||
.Where(item => tracksById.ContainsKey(item.TrackId))
|
||||
.Select(item =>
|
||||
{
|
||||
var entry = tracksById[item.TrackId];
|
||||
return new MixItemApplicationResponse(
|
||||
item.TrackId,
|
||||
entry.Track.Title,
|
||||
entry.Track.Owner.Name,
|
||||
entry.Track.DurationSeconds,
|
||||
entry.ListensCount);
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Musify.Application.Mixes.Responses
|
||||
{
|
||||
public record MixApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Subtitle,
|
||||
int ItemCount,
|
||||
IReadOnlyList<MixItemApplicationResponse> Items)
|
||||
{
|
||||
public const int CoverItemCount = 4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Musify.Application.Mixes.Responses
|
||||
{
|
||||
public record MixItemApplicationResponse(
|
||||
Guid TrackId,
|
||||
string Title,
|
||||
string? Artist,
|
||||
double DurationSeconds,
|
||||
int ListensCount);
|
||||
}
|
||||
+8
-5
@@ -19,7 +19,7 @@ namespace Musify.Application.PlayLists
|
||||
{
|
||||
var playList = await database.PlayLists
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -49,10 +49,13 @@ namespace Musify.Application.PlayLists
|
||||
return Error.Conflict(description: "Track is already in the playlist.");
|
||||
}
|
||||
|
||||
var nextPosition = await database.PlayListHasTracks
|
||||
.Where(plt => plt.PlayListId == request.PlayListId)
|
||||
.Select(plt => (int?)plt.Position)
|
||||
.MaxAsync(cancellationToken) + 1 ?? 0;
|
||||
var playListTracksQuery = database.PlayListHasTracks
|
||||
.Where(plt => plt.PlayListId == request.PlayListId);
|
||||
|
||||
var hasTracks = await playListTracksQuery.AnyAsync(cancellationToken);
|
||||
var nextPosition = hasTracks
|
||||
? await playListTracksQuery.MaxAsync(plt => plt.Position, cancellationToken) + 1
|
||||
: 0;
|
||||
|
||||
await database.PlayListHasTracks.AddAsync(new PlayListHasTrack
|
||||
{
|
||||
+40
-30
@@ -8,6 +8,7 @@ using Musify.Application.Events;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
@@ -15,8 +16,9 @@ namespace Musify.Application.PlayLists
|
||||
public record CreatePlayListCommand(
|
||||
long UserId,
|
||||
string Name,
|
||||
string Description,
|
||||
Guid? PictureIntentId)
|
||||
string? Description,
|
||||
Guid? PictureIntentId,
|
||||
PlaylistVisibility Visibility = PlaylistVisibility.Private)
|
||||
: ICommand<ErrorOr<PlayListApplicationResponse>>;
|
||||
|
||||
public class CreatePlayListCommandHandler(
|
||||
@@ -29,6 +31,8 @@ namespace Musify.Application.PlayLists
|
||||
UploadIntentConfiguration uploadIntentConfiguration)
|
||||
: ICommandHandler<CreatePlayListCommand, ErrorOr<PlayListApplicationResponse>>
|
||||
{
|
||||
private sealed record ResolvedPlayListPictures(PlayListPictures? Pictures, UploadIntent? Intent);
|
||||
|
||||
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(CreatePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userExists = await database.Users
|
||||
@@ -40,44 +44,27 @@ namespace Musify.Application.PlayLists
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
}
|
||||
|
||||
UploadIntent? pictureIntent = null;
|
||||
string originalPictureName;
|
||||
var picturesResult = await ResolvePicturesAsync(request, cancellationToken);
|
||||
if (picturesResult.IsError)
|
||||
return picturesResult.Errors;
|
||||
|
||||
if (request.PictureIntentId.HasValue)
|
||||
{
|
||||
var validation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration,
|
||||
request.PictureIntentId.Value, request.UserId, cancellationToken);
|
||||
if (validation.IsError)
|
||||
return validation.Errors;
|
||||
|
||||
pictureIntent = validation.Value;
|
||||
originalPictureName = pictureIntent.ObjectName;
|
||||
}
|
||||
else
|
||||
{
|
||||
originalPictureName = playListConfiguration.Routes.PresetOriginalPicture;
|
||||
}
|
||||
var resolvedPictures = picturesResult.Value;
|
||||
|
||||
var playList = new PlayList
|
||||
{
|
||||
UserId = request.UserId,
|
||||
Name = request.Name,
|
||||
NormalizedName = request.Name.Trim().ToUpperInvariant(),
|
||||
Description = request.Description,
|
||||
OriginalPictureName = originalPictureName,
|
||||
SmallPictureName = playListConfiguration.Routes.PresetSmallPicture,
|
||||
MediumPictureName = playListConfiguration.Routes.PresetMediumPicture,
|
||||
LargePictureName = playListConfiguration.Routes.PresetLargePicture
|
||||
Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(),
|
||||
Pictures = resolvedPictures.Pictures,
|
||||
Visibility = request.Visibility
|
||||
};
|
||||
|
||||
await database.PlayLists.AddAsync(playList, cancellationToken);
|
||||
|
||||
if (pictureIntent is not null)
|
||||
if (resolvedPictures.Intent != null)
|
||||
{
|
||||
var finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, originalPictureName);
|
||||
var publishResult = await PublishCreatePlayListEventAsync(
|
||||
playList.Id, pictureIntent, finalPictureKey, cancellationToken);
|
||||
var finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, resolvedPictures.Pictures!.OriginalName);
|
||||
var publishResult = await PublishCreatePlayListEventAsync(playList.Id, resolvedPictures.Intent, finalPictureKey, cancellationToken);
|
||||
if (publishResult.IsError)
|
||||
return publishResult.Errors;
|
||||
}
|
||||
@@ -96,7 +83,30 @@ namespace Musify.Application.PlayLists
|
||||
return PlayListApplicationResponse.FromEntity(playList);
|
||||
}
|
||||
|
||||
async Task<ErrorOr<Success>> PublishCreatePlayListEventAsync(
|
||||
private async ValueTask<ErrorOr<ResolvedPlayListPictures>> ResolvePicturesAsync(
|
||||
CreatePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!request.PictureIntentId.HasValue)
|
||||
{
|
||||
return new ResolvedPlayListPictures(null, null);
|
||||
}
|
||||
|
||||
var validation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration, request.PictureIntentId.Value, request.UserId, cancellationToken);
|
||||
|
||||
if (validation.IsError)
|
||||
return validation.Errors;
|
||||
|
||||
return new ResolvedPlayListPictures(new PlayListPictures
|
||||
{
|
||||
OriginalName = validation.Value.ObjectName,
|
||||
SmallName = validation.Value.ObjectName,
|
||||
MediumName = validation.Value.ObjectName,
|
||||
LargeName = validation.Value.ObjectName
|
||||
}, validation.Value);
|
||||
}
|
||||
|
||||
private async Task<ErrorOr<Success>> PublishCreatePlayListEventAsync(
|
||||
Guid playListId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
+1
-1
@@ -20,7 +20,7 @@ namespace Musify.Application.PlayLists
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeletePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playList = await database.PlayLists.SingleOrDefaultAsync(p => p.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogDebug("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -0,0 +1,42 @@
|
||||
using ErrorOr;
|
||||
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, long? RequestingUserId = null)
|
||||
: IQuery<ErrorOr<PlayListApplicationResponse>>;
|
||||
|
||||
public class GetPlayListByIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetPlayListByIdQuery, ErrorOr<PlayListApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(GetPlayListByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entry = await database.PlayLists
|
||||
.AsNoTracking()
|
||||
.Where(p => p.Id == request.Id)
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
.Select(plt => plt.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (entry == 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MimeMapping;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record GetPlayListCoverQuery(Guid PlayListId, string Size)
|
||||
: IQuery<ErrorOr<PlayListCoverLocation>>;
|
||||
|
||||
public record PlayListCoverLocation(string Bucket, string Key, string ContentType);
|
||||
|
||||
public class GetPlayListCoverQueryHandler(
|
||||
IDatabase database,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
PlayListConfiguration playListConfiguration)
|
||||
: IQueryHandler<GetPlayListCoverQuery, ErrorOr<PlayListCoverLocation>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PlayListCoverLocation>> Handle(GetPlayListCoverQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var pictures = await database.PlayLists.AsNoTracking()
|
||||
.Where(p => p.Id == request.PlayListId)
|
||||
.Select(p => p.Pictures)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (pictures == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var routes = playListConfiguration.Routes;
|
||||
var (name, key) = request.Size.ToLowerInvariant() switch
|
||||
{
|
||||
"small" => (pictures.SmallName, BuildKey(routes.BuildSmallPicturePath, pictures.SmallName)),
|
||||
"large" => (pictures.LargeName, BuildKey(routes.BuildLargePicturePath, pictures.LargeName)),
|
||||
_ => (pictures.MediumName, BuildKey(routes.BuildMediumPicturePath, pictures.MediumName))
|
||||
};
|
||||
|
||||
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(key))
|
||||
return Error.NotFound();
|
||||
|
||||
var contentType = MimeUtility.GetMimeMapping(name);
|
||||
return new PlayListCoverLocation(storageConfiguration.Bucket, key, contentType);
|
||||
}
|
||||
|
||||
private static string? BuildKey(Func<string, string> builder, string? name)
|
||||
=> string.IsNullOrEmpty(name) ? null : builder(name);
|
||||
}
|
||||
}
|
||||
+11
-5
@@ -4,14 +4,15 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record GetPlayListTracksQuery(
|
||||
Guid PlayListId,
|
||||
int PageNumber = 1,
|
||||
int PageSize = 10)
|
||||
int PageNumber,
|
||||
int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<TrackApplicationResponse>>>;
|
||||
|
||||
public class GetPlayListTracksQueryHandler(IDatabase database)
|
||||
@@ -27,16 +28,21 @@ namespace Musify.Application.PlayLists
|
||||
|
||||
var tracksQuery = database.PlayListHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(plt => plt.Track)
|
||||
.Include(plt => plt.Track.Owner)
|
||||
.Include(plt => plt.Track.Tags)
|
||||
.Where(plt => plt.PlayListId == request.PlayListId);
|
||||
|
||||
var totalCount = await tracksQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedTracks = await tracksQuery
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Select(plt => TrackApplicationResponse.FromEntity(plt.Track))
|
||||
.Select(plt => new { plt.Track, ListensCount = plt.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,43 @@
|
||||
using ErrorOr;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
using Mediator;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record GetPlayListsQuery(int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<PlayListApplicationResponse>>>;
|
||||
|
||||
public class GetPlayListsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetPlayListsQuery, ErrorOr<PaginatedResponse<PlayListApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<PlayListApplicationResponse>>> Handle(GetPlayListsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var totalCount = await database.PlayLists.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await database.PlayLists
|
||||
.AsNoTracking()
|
||||
.OrderBy(p => p.Id)
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
.Select(plt => plt.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedPlayLists = new StaticPagedList<PlayListApplicationResponse>(
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<PlayListApplicationResponse>.FromPagedList(pagedPlayLists);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record GetPlayListsByUserIdQuery(
|
||||
long UserId,
|
||||
string? Name,
|
||||
int PageNumber,
|
||||
int PageSize,
|
||||
bool OnlyPublic = false)
|
||||
: IQuery<ErrorOr<PaginatedResponse<PlayListApplicationResponse>>>;
|
||||
|
||||
public class GetPlayListsByUserIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetPlayListsByUserIdQuery, ErrorOr<PaginatedResponse<PlayListApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<PlayListApplicationResponse>>> Handle(GetPlayListsByUserIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playListsQuery = database.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();
|
||||
playListsQuery = playListsQuery.Where(p => p.NormalizedName.Contains(normalizedName));
|
||||
}
|
||||
|
||||
var totalCount = await playListsQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await playListsQuery
|
||||
.OrderBy(p => p.CreatedAt)
|
||||
.Where(p => p.LifeCycleStatus == LifeCycleStatus.Active)
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
.Select(plt => plt.TrackId)
|
||||
.ToList()
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedPlayLists = new StaticPagedList<PlayListApplicationResponse>(
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<PlayListApplicationResponse>.FromPagedList(pagedPlayLists);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -18,7 +18,7 @@ namespace Musify.Application.PlayLists
|
||||
{
|
||||
var playList = await database.PlayLists
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -32,7 +32,7 @@ namespace Musify.Application.PlayLists
|
||||
|
||||
var link = await database.PlayListHasTracks
|
||||
.SingleOrDefaultAsync(plt => plt.PlayListId == request.PlayListId && plt.TrackId == request.TrackId, cancellationToken);
|
||||
if (link is null)
|
||||
if (link == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not in playlist {PlayListId}", request.TrackId, request.PlayListId);
|
||||
return Error.NotFound(description: "Track is not in the playlist.");
|
||||
@@ -0,0 +1,37 @@
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.PlayLists.Responses
|
||||
{
|
||||
public record PlayListApplicationResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
string? SmallImageKeyName,
|
||||
string? MediumImageKeyName,
|
||||
string? LargeImageKeyName,
|
||||
PlaylistVisibility Visibility,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
IReadOnlyList<Guid> CoverTrackIds)
|
||||
{
|
||||
public const int CoverTrackCount = 4;
|
||||
|
||||
public static PlayListApplicationResponse FromEntity(
|
||||
PlayList playList,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
return new PlayListApplicationResponse(
|
||||
playList.Id,
|
||||
playList.Name,
|
||||
playList.Description,
|
||||
playList.Pictures?.SmallName,
|
||||
playList.Pictures?.MediumName,
|
||||
playList.Pictures?.LargeName,
|
||||
playList.Visibility,
|
||||
playList.CreatedAt,
|
||||
playList.UpdatedAt,
|
||||
coverTrackIds ?? []);
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
-10
@@ -8,6 +8,7 @@ using Musify.Application.Events;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
@@ -17,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(
|
||||
@@ -33,7 +35,7 @@ namespace Musify.Application.PlayLists
|
||||
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(UpdatePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playListEntity = await database.PlayLists.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playListEntity is null)
|
||||
if (playListEntity == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -45,17 +47,22 @@ namespace Musify.Application.PlayLists
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
if (request.NewName is not null)
|
||||
if (!string.IsNullOrWhiteSpace(request.NewName))
|
||||
{
|
||||
playListEntity.Name = request.NewName;
|
||||
playListEntity.NormalizedName = request.NewName.Trim().ToUpperInvariant();
|
||||
}
|
||||
|
||||
if (request.NewDescription is not null)
|
||||
if (!string.IsNullOrWhiteSpace(request.NewDescription))
|
||||
{
|
||||
playListEntity.Description = request.NewDescription;
|
||||
}
|
||||
|
||||
if (request.NewVisibility.HasValue)
|
||||
{
|
||||
playListEntity.Visibility = request.NewVisibility.Value;
|
||||
}
|
||||
|
||||
UploadIntent? pictureIntent = null;
|
||||
string? finalPictureKey = null;
|
||||
|
||||
@@ -68,13 +75,17 @@ namespace Musify.Application.PlayLists
|
||||
return validation.Errors;
|
||||
|
||||
pictureIntent = validation.Value;
|
||||
playListEntity.OriginalPictureName = pictureIntent.ObjectName;
|
||||
playListEntity.Pictures = new PlayListPictures
|
||||
{
|
||||
OriginalName = pictureIntent.ObjectName,
|
||||
SmallName = pictureIntent.ObjectName,
|
||||
MediumName = pictureIntent.ObjectName,
|
||||
LargeName = pictureIntent.ObjectName
|
||||
};
|
||||
finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
|
||||
}
|
||||
|
||||
database.PlayLists.Update(playListEntity);
|
||||
|
||||
if (pictureIntent is not null && finalPictureKey is not null)
|
||||
if (pictureIntent != null && finalPictureKey != null)
|
||||
{
|
||||
var publishResult = await PublishUpdatePlayListPictureSourceEventAsync(
|
||||
playListEntity.Id, pictureIntent, finalPictureKey, cancellationToken);
|
||||
@@ -92,11 +103,19 @@ namespace Musify.Application.PlayLists
|
||||
return Error.Failure(description: $"Failed to update playlist {playListEntity.Id}");
|
||||
}
|
||||
|
||||
var coverTrackIds = await database.PlayListHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(plt => plt.PlayListId == playListEntity.Id)
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
.Select(plt => plt.TrackId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Updated playlist {PlayListId}", playListEntity.Id);
|
||||
return PlayListApplicationResponse.FromEntity(playListEntity);
|
||||
return PlayListApplicationResponse.FromEntity(playListEntity, coverTrackIds);
|
||||
}
|
||||
|
||||
async Task<ErrorOr<Success>> PublishUpdatePlayListPictureSourceEventAsync(
|
||||
private async Task<ErrorOr<Success>> PublishUpdatePlayListPictureSourceEventAsync(
|
||||
Guid playListId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Musify.Application.Serialization;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Services;
|
||||
|
||||
public sealed class TrackStreamIssuer(
|
||||
IDatabase database,
|
||||
IStreamTicketService ticketService,
|
||||
TrackConfiguration trackConfiguration,
|
||||
StreamGatewayConfiguration streamGatewayConfiguration,
|
||||
PlaybackConfiguration playbackConfiguration)
|
||||
{
|
||||
public async Task<TrackStreamResponse> IssueAsync(
|
||||
Guid trackId,
|
||||
string audioFolderName,
|
||||
long? userId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var folderPath = trackConfiguration.Routes.BuildProcessedAudioPath(audioFolderName);
|
||||
var keyPrefix = $"{folderPath}/";
|
||||
|
||||
var maxBytes = AnonymousFragmentBytes(userId);
|
||||
var ticket = ticketService.IssueTicket(userId, keyPrefix, maxBytes);
|
||||
|
||||
var manifestUrl = string.Join('/',
|
||||
streamGatewayConfiguration.PublicBaseUrl.TrimEnd('/'),
|
||||
"media",
|
||||
folderPath,
|
||||
streamGatewayConfiguration.AudioFileName);
|
||||
|
||||
if (userId != null)
|
||||
{
|
||||
var newListeningHistory = new ListeningHistory
|
||||
{
|
||||
UserId = userId.Value,
|
||||
TrackId = trackId,
|
||||
};
|
||||
await database.ListeningHistories.AddAsync(newListeningHistory, cancellationToken);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return new TrackStreamResponse(manifestUrl, ticket.Token, ticket.ExpiresInSeconds);
|
||||
}
|
||||
|
||||
private long? AnonymousFragmentBytes(long? userId)
|
||||
{
|
||||
if (userId != null || playbackConfiguration.AnonymousFragmentSeconds <= 0)
|
||||
return null;
|
||||
|
||||
return (long)playbackConfiguration.AnonymousFragmentSeconds * playbackConfiguration.EstimatedAudioBytesPerSecond;
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -42,17 +42,17 @@ public sealed class UploadIntentValidator(
|
||||
var intent = await database.UploadIntents
|
||||
.FirstOrDefaultAsync(i => i.Id == intentId, cancellationToken);
|
||||
|
||||
if (intent is null || intent.UserId != userId)
|
||||
if (intent == null || intent.UserId != userId)
|
||||
return Error.NotFound(description: "Upload intent not found or not accessible.");
|
||||
|
||||
if (intent.Status == UploadIntentStatus.Consumed)
|
||||
if (intent.IsConsumed)
|
||||
return Error.Conflict(description: "Upload intent has already been consumed.");
|
||||
|
||||
if (intent.Status == UploadIntentStatus.Expired || intent.ExpiresAt < DateTime.UtcNow)
|
||||
if (intent.IsExpired)
|
||||
return Error.Validation(description: "Upload intent has expired.");
|
||||
|
||||
var metadata = await storageService.HeadObjectAsync(intent.Bucket, intent.Key, cancellationToken);
|
||||
if (metadata is null)
|
||||
if (metadata == null)
|
||||
return Error.NotFound(description: "Uploaded object not found in storage. Upload the file first.");
|
||||
|
||||
if (metadata.ContentLength > config.MaxUploadBytes)
|
||||
+42
-12
@@ -17,7 +17,8 @@ namespace Musify.Application.Tracks
|
||||
long UserId,
|
||||
string Title,
|
||||
Guid PictureIntentId,
|
||||
Guid AudioIntentId)
|
||||
Guid AudioIntentId,
|
||||
IReadOnlyCollection<Genre> Tags)
|
||||
: ICommand<ErrorOr<TrackApplicationResponse>>;
|
||||
|
||||
public class CreateTrackCommandHandler(
|
||||
@@ -32,14 +33,31 @@ namespace Musify.Application.Tracks
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(CreateTrackCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userExists = await database.Users.AsNoTracking()
|
||||
.AnyAsync(u => u.Id == request.UserId, cancellationToken);
|
||||
if (!userExists)
|
||||
var user = await database.Users
|
||||
.SingleOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
|
||||
if (user == null)
|
||||
{
|
||||
logger.LogWarning("User {UserId} not found", request.UserId);
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
}
|
||||
|
||||
var distinctTags = request.Tags.Distinct().ToList();
|
||||
if (distinctTags.Count == 0)
|
||||
{
|
||||
logger.LogWarning("Track {Title} was submitted without any tags", request.Title);
|
||||
return Error.Validation(description: "At least one tag is required.");
|
||||
}
|
||||
|
||||
var tagConflicts = GenreCompatibility.FindConflicts(distinctTags);
|
||||
if (tagConflicts.Count > 0)
|
||||
{
|
||||
var conflict = tagConflicts.First();
|
||||
logger.LogWarning(
|
||||
"Track {Title} was submitted with incompatible tags {First} and {Second}",
|
||||
request.Title, conflict.First, conflict.Second);
|
||||
return Error.Validation(description: $"Tags '{conflict.First}' and '{conflict.Second}' are not compatible.");
|
||||
}
|
||||
|
||||
var pictureValidation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration,
|
||||
request.PictureIntentId, request.UserId, cancellationToken);
|
||||
@@ -63,15 +81,27 @@ namespace Musify.Application.Tracks
|
||||
{
|
||||
Title = request.Title,
|
||||
NormalizedTitle = request.Title.ToUpperInvariant(),
|
||||
OriginalPictureName = pictureIntent.ObjectName,
|
||||
OriginalAudioName = audioIntent.ObjectName,
|
||||
SmallPictureName = trackConfiguration.Routes.PresetSmallPicture,
|
||||
MediumPictureName = trackConfiguration.Routes.PresetMediumPicture,
|
||||
LargePictureName = trackConfiguration.Routes.PresetLargePicture,
|
||||
PicturesProcessingStatus = ProcessingStatus.Pending,
|
||||
AudioTranscodeProcessingStatus = ProcessingStatus.Pending
|
||||
OwnerUserId = user.Id,
|
||||
Owner = user,
|
||||
Pictures = new TrackPictures
|
||||
{
|
||||
OriginalName = pictureIntent.ObjectName,
|
||||
SmallName = trackConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = trackConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = trackConfiguration.Routes.PresetLargePicture,
|
||||
ProcessingStatus = ProcessingStatus.Pending
|
||||
},
|
||||
Audio = new TrackAudio
|
||||
{
|
||||
OriginalName = audioIntent.ObjectName,
|
||||
TranscodeStatus = ProcessingStatus.Pending
|
||||
}
|
||||
};
|
||||
|
||||
trackEntity.Tags = distinctTags
|
||||
.Select(tag => new TrackTag { TrackId = trackEntity.Id, Tag = tag })
|
||||
.ToList();
|
||||
|
||||
await database.Tracks.AddAsync(trackEntity, cancellationToken);
|
||||
|
||||
await database.UserHasTracks.AddAsync(new UserHasTrack
|
||||
@@ -123,7 +153,7 @@ namespace Musify.Application.Tracks
|
||||
return Error.Failure(description: $"Failed to create track for {request.Title}");
|
||||
}
|
||||
|
||||
return TrackApplicationResponse.FromEntity(trackEntity);
|
||||
return TrackApplicationResponse.FromEntity(trackEntity, listensCount: 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-7
@@ -2,6 +2,7 @@ using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using Musify.Application.Events;
|
||||
using Musify.Application.Contracts;
|
||||
@@ -22,23 +23,19 @@ namespace Musify.Application.Tracks
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeleteTrackCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var track = await database.Tracks.SingleOrDefaultAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (track is null)
|
||||
if (track == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
var isOwner = await database.UserHasTracks
|
||||
.AsNoTracking()
|
||||
.AnyAsync(ut => ut.TrackId == request.TrackId && ut.UserId == request.UserId, cancellationToken);
|
||||
if (!isOwner)
|
||||
if (track.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} unauthorized to delete track {TrackId}", request.UserId, request.TrackId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
if (track.AudioTranscodeProcessingStatus == ProcessingStatus.Processing
|
||||
|| track.AudioTranscodeProcessingStatus == ProcessingStatus.Pending)
|
||||
if (track.Audio.IsInProgress)
|
||||
{
|
||||
logger.LogWarning("Track {TrackId} is currently being processed and cannot be deleted", request.TrackId);
|
||||
return Error.Conflict(description: "Track is currently being processed and cannot be deleted");
|
||||
@@ -0,0 +1,30 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record GetLastTrackListenedByUserIdQuery(long UserId) : IQuery<ErrorOr<TrackApplicationResponse>>;
|
||||
|
||||
public class GetLastTrackListenedByUserIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetLastTrackListenedByUserIdQuery, ErrorOr<TrackApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(GetLastTrackListenedByUserIdQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var track = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Include(t => t.Track.Owner)
|
||||
.Include(t => t.Track.Tags)
|
||||
.Where(t => t.UserId == query.UserId)
|
||||
.OrderByDescending(t => t.ListenedAt)
|
||||
.Select(t => TrackApplicationResponse.FromEntity(t.Track, t.Track.ListeningHistories.Count))
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
return track == null
|
||||
? Error.NotFound("Track.NotFound", "No track found for the given user ID.")
|
||||
: track;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record GetListeningHistoryQuery(long UserId) : IQuery<IEnumerable<TrackApplicationResponse>>;
|
||||
|
||||
public class GetListeningHistoryQueryHandler(
|
||||
IDatabase database)
|
||||
: IQueryHandler<GetListeningHistoryQuery, IEnumerable<TrackApplicationResponse>>
|
||||
{
|
||||
public const int ListSize = 15;
|
||||
|
||||
public async ValueTask<IEnumerable<TrackApplicationResponse>> Handle(GetListeningHistoryQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var recentTrackIds = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(l => l.UserId == query.UserId)
|
||||
.GroupBy(l => l.TrackId)
|
||||
.OrderByDescending(g => g.Max(l => l.ListenedAt))
|
||||
.Select(g => g.Key)
|
||||
.Take(ListSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var tracksById = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(t => t.Owner)
|
||||
.Include(t => t.Tags)
|
||||
.Where(t => recentTrackIds.Contains(t.Id))
|
||||
.Select(t => new { t.Id, Track = t, ListensCount = t.ListeningHistories.Count })
|
||||
.ToDictionaryAsync(t => t.Id, cancellationToken);
|
||||
|
||||
return recentTrackIds
|
||||
.Select(id => tracksById[id])
|
||||
.Select(t => TrackApplicationResponse.FromEntity(t.Track, t.ListensCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -14,15 +14,17 @@ namespace Musify.Application.Tracks
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(GetTrackByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var track = await database.Tracks.AsNoTracking()
|
||||
var entity = await database.Tracks.AsNoTracking()
|
||||
.Include(t => t.Owner)
|
||||
.Include(t => t.Tags)
|
||||
.Where(t => t.Id == request.TrackId)
|
||||
.Select(t => TrackApplicationResponse.FromEntity(t))
|
||||
.Select(t => new { Track = t, ListensCount = t.ListeningHistories.Count })
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (track is null)
|
||||
if (entity == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return track;
|
||||
return TrackApplicationResponse.FromEntity(entity.Track, entity.ListensCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user