Author SHA1 Message Date
Admin d874e06d64 Merge direct upload queue 2026-09-25 01:52:28 +02:00
Admin f3ed68856c Refresh processing tracks live, apply publish and delete optimistically and guard unsaved album edits 2026-09-25 01:52:27 +02:00
Admin 3eccf6dc53 Upload from the library queue straight to storage and retire the upload page 2026-09-25 01:51:20 +02:00
Admin e19aba777d Add upload queue store with concurrent uploads, progress, cancel and retry 2026-09-25 01:51:20 +02:00
Admin 493cc74cfb Add direct upload API for presigning, creating tracks and following processing 2026-09-25 01:51:19 +02:00
Admin 9f592cfdb8 Filter library tracks on the server and add track publishing, bulk delete and album types 2026-09-25 01:49:44 +02:00
Admin 93d7a23c53 Regenerate API schema for track publication, album types and batch uploads 2026-09-25 01:43:38 +02:00
Admin 202164aa50 Merge backend library endpoints 2026-09-25 01:38:19 +02:00
Admin ebfd41b160 Add track publication, album types, optional track pictures and batch upload URLs
Tracks
- Track.IsPublished (migration marks existing tracks as published). New
  tracks are created unpublished.
- PUT /tracks/{id}/published and PUT /tracks/published change the flag;
  publishing requires completed audio processing (the batch endpoint
  reports skipped tracks).
- An unpublished track is only visible to its owner. A WherePublished /
  VisibleTo filter is applied to search, genres, listening history, last
  listened, likes, mixes, album and playlist contents and counts, recently
  listened albums, public user tracks, track details and stream tickets.
- isPublished is part of the track responses, GET /tracks/users/{userId}
  accepts a published filter and status-counts reports published and
  unpublished totals.
- CreateTrackRequest.pictureIntentId is optional: without it the track
  uses the album cover or the preset picture and no picture processing
  runs. CreateTrackResourcesEvent carries nullable picture fields, so
  queues must be drained before deploying.
- POST /tracks/upload-urls accepts an audios list and one optional picture
  shared by all of them, and returns an intent per file. The upload intent
  limits are raised so a batch fits.

Albums
- AlbumType (Album, EP, Single) on create, update and responses.
- CreateAlbumRequest.trackIds creates the album and links the tracks in a
  single save.
2026-09-25 01:37:55 +02:00
Admin 1c20e106fa Merge library components and styles work 2026-09-25 01:24:00 +02:00
Admin 43928ba9b9 Animate library tabs, rows, editor track lists, status badges and dropzone
Tabs get a sliding indicator that persists across library routes, grid rows flip and collapse on removal, the selection bar and filters crossfade, album tracks move between lists with a crossfade, processing badges pulse and the dropzone scales while dragging.
2026-09-25 01:23:40 +02:00
Admin ebe9769d4e Align library styles with the design system
Use type recipes and Button danger variant, add danger tint, dropzone and cover-fill tokens, give SearchInput a size prop so the top bar keeps its larger search, show queue details inline on mobile, derive upload limits from constants and document the card hover style.
2026-09-25 01:20:32 +02:00
Admin 074ea7bf26 Extract shared data grid, selection bar, file dropzone and genre picker components
Track lists and the upload queue now render through a declarative DataGrid, the album editor reuses AlbumForm with a split layout and a track picker, and genre labels and types are shared helpers.
2026-09-25 01:17:59 +02:00
Admin 7cac6ff446 Move library album and track operations into shared server modules 2026-09-25 01:15:04 +02:00
Admin d839a72700 Add track status filter and counts, album track ids and bulk track deletion
GET /tracks/users/{userId} accepts repeated status values and returns the
albums each track belongs to. GET /tracks/users/{userId}/status-counts,
GET /albums/{id}/tracks/ids and DELETE /tracks with a list of track ids
are new.
2026-09-25 01:14:59 +02:00
Admin 797bed8e7d Split the library page into song, album and upload routes with linked tabs 2026-09-25 01:11:01 +02:00
Admin 9928840577 Add library manager with tracks, albums and uploads sections 2026-09-25 01:07:15 +02:00
Admin 4ac73d8fa3 Update sidebar to the new page 2026-09-24 19:25:15 +02:00
Admin 88487064e1 Update Sidebar.svelte to adjust padding for playlist display 2026-09-24 19:10:04 +02:00
Admin e4e4617f6e Copy .editorconfig into the migrator image so analyzers match the local build 2026-09-24 19:08:50 +02:00
Admin c2100c189f Added worker to the launch file 2026-09-24 18:02:52 +02:00
Admin 1a302491d1 Changes 2026-09-24 17:58:48 +02:00
Admin e84c16cf92 A lot of changes 2026-09-24 17:54:16 +02:00
Admin ece6ce2a43 Merge branch 'backend-refactor-rev' into audit-merge-three
Adapt the refactored web player to the new backend API (id path params,
bulk track adds, flat list items, mix kind) and port AddAlbumToPlayList
to the backend conventions.
2026-09-24 17:30:40 +02:00
Admin ecf9faf640 Merge branch 'frontend-refactor-rev' into audit-merge-three 2026-09-24 17:25:31 +02:00
Admin 35d6314ce8 Point the IDE dev settings at the shared Infrastructure stack
CI/CD / BackEnd (push) Successful in 1m18s
CI/CD / WebPlayer (push) Successful in 41s
CI/CD / Deploy (push) Skipped
appsettings.Development.json still targeted Musify's old own Postgres
(port 59000) with the superuser, the default RabbitMQ vhost as guest and
the admin S3 keys. They now use Infrastructure's dev ports and Musify's
own dev credentials (role, vhost and S3 identity), the same defaults as
deploy/.env.example.

The API's non-secret Zitadel settings (issuer, metadata, endpoints) move
there too, so user-secrets only need the per-machine client id.
2026-09-24 17:11:50 +02:00
Admin f99f74f4a1 Use Musify's own credentials on the shared services
Infrastructure now gives each project its own Postgres role, RabbitMQ
user and vhost, S3 identity limited to its bucket and a Zitadel service
account that owns only its project, instead of handing out the admin
accounts.

- Postgres, RabbitMQ and S3 settings default to Musify's own (musify).
- MassTransit connects to the `musify` vhost (RABBITMQ_VHOST, taken from
  the address path); RABBITMQ_DEFAULT_USER/PASS become RABBITMQ_USER and
  RABBITMQ_PASSWORD.
- zitadel-init mounts ZITADEL_PAT_DIR (Infrastructure's
  zitadel/.output/musify) and uses that PAT. It no longer creates the
  Zitadel project, which that account can't do: Infrastructure does.
2026-09-24 17:05:23 +02:00
Admin f2765e2e7b Call the API by container name from the web player
In prod every project shares infra-net, where the `api` service name
can resolve to another project's container as well.
2026-09-24 15:06:25 +02:00
Admin 7b8f3f1222 Use a reverse-domain redirect scheme for the native app
- Android/iOS now return to cat.ikerdemo.musify:/callback instead of
  musify://callback: a private-use scheme based on a domain we own
  (RFC 8252 section 7.1), so another app is unlikely to claim it.
- The Musify Native app no longer needs devMode: loopback and custom
  scheme redirects are both valid for a native app.
- zitadel-init also updates an existing app's config, so the change
  reaches instances created before it (the client id is kept).
- iOS takes the scheme from everything before the first ':', since the
  new URI has a single slash.
2026-09-24 15:06:25 +02:00
Admin c33b0e8bfd Stop disabling Zitadel Login V2 from zitadel-init
The shared Infrastructure stack now runs the Login V2 container, and
turning the feature off here would switch every project on the shared
instance back to the old login.
2026-09-24 15:06:25 +02:00
Admin 8e85af2b3b Render unknown URLs inside the app shell and move ListeningStats to the domain types
CI/CD / BackEnd (push) Successful in 1m19s
CI/CD / WebPlayer (push) Successful in 46s
CI/CD / Deploy (push) Skipped
Add catch-all routes so unknown pages 404 inside the (app) layout and unknown
/api URLs return a JSON 404 instead of redirecting to the login page. Restore
the full root error page.
2026-09-24 14:29:45 +02:00
Admin 2d23eb87c6 Update frontend docs for the new structure and fix session test typing 2026-09-24 14:06:46 +02:00
Admin e5ce63a192 Add tests for API endpoints, liked store, listen tracker and paged list 2026-09-24 14:04:43 +02:00
Admin b5c9658d65 Add tests for sessions, guards, API error details and the app layout load 2026-09-24 14:03:35 +02:00
Admin ba0a2373b5 Normalize API counters in the server mappers instead of route loaders 2026-09-24 14:02:23 +02:00
Admin b0163f6a4d Split the explore page into genre grid, top result and search results components 2026-09-24 14:01:33 +02:00
Admin 0a192645d6 Drive the theme accent from the app layout instead of the player 2026-09-24 13:59:54 +02:00
Admin 351b333529 Split the server API module into client, guards, form fields and action helpers 2026-09-24 13:59:21 +02:00
Admin 155f0e2b6a Move liked tracks state to state/ and recently played merge to player/ 2026-09-24 13:58:43 +02:00
Admin a54d1ef077 Move store-connected components out of ui/ into components/music and lint the ui boundary 2026-09-24 13:58:13 +02:00
Admin 2361b88e0a Rename the app shell components folder and move AccountMenu next to its consumers 2026-09-24 13:57:35 +02:00
Admin e7c2fd5571 Move the app shell and its data loading into the (app) route group layout 2026-09-24 13:57:02 +02:00
Admin 3126cb6dd6 web-player: regenerate package-lock with npm 10 so npm ci works on Node 22
CI/CD / BackEnd (push) Successful in 1m19s
CI/CD / WebPlayer (push) Successful in 45s
CI/CD / Deploy (push) Skipped
2026-09-24 13:16:43 +02:00
Admin 03afcc8a90 web-player: sync package-lock with missing emnapi optional dependencies
CI/CD / BackEnd (push) Successful in 1m24s
CI/CD / WebPlayer (push) Failing after 8s
CI/CD / Deploy (push) Skipped
2026-09-24 13:02:38 +02:00
Admin f210fa4702 web-player: add albums to playlists through the bulk endpoint
CI/CD / BackEnd (push) Successful in 1m29s
CI/CD / WebPlayer (push) Failing after 7s
CI/CD / Deploy (push) Skipped
2026-09-24 12:05:34 +02:00
Admin 4b708aa987 backend: add endpoint to add a whole album to a playlist 2026-09-24 12:04:28 +02:00
Admin bd07b1134e web-player: fix icon size guardrail and add larger icon tokens 2026-09-24 11:56:09 +02:00
Admin c041daf649 web-player: add lint guardrails for imports, non-null assertions, unused props and icon sizes; refresh docs 2026-09-24 11:54:38 +02:00
Admin 975fa7e4fd web-player: consistent imports, tokens, glossary and app route grouping 2026-09-24 11:52:57 +02:00
Admin 1a2ae37f49 web-player: show only real upload steps 2026-09-24 11:51:47 +02:00
Admin 1cad36b929 web-player: extract menu, paged list and play-all components from pages 2026-09-24 11:51:14 +02:00
Admin 8cb9386447 web-player: unify primitive link/button rendering, add onEscape action and self-contained AccountMenu 2026-09-24 05:27:25 +02:00
Admin 5cda7cb4c1 web-player: split player, navigation and accent state into focused modules 2026-09-24 05:25:35 +02:00
Admin e89463fb83 web-player: use playlist totals from the API, cache genres and parallelize explore requests 2026-09-24 05:21:29 +02:00
Admin b011ccdd5b backend: expose track count and duration on playlist responses 2026-09-24 05:20:20 +02:00
Admin 1df7f6ccf6 web-player: share form limits between client and server and extract form parsers 2026-09-24 05:19:41 +02:00
Admin 2915737f03 web-player: centralize server helpers (apiFor, authedAction, form readers) and unify page sizes 2026-09-24 05:13:51 +02:00
Admin 5b2a0e4d46 web-player: normalize tracks, albums and playlists into single domain types at the server boundary 2026-09-24 05:09:37 +02:00
Admin 37fc229bf6 web-player: remove dead code and unused props 2026-09-24 05:04:09 +02:00
Admin bc43b4b6eb web-player: fix playlist ownership, sidebar counts, home spotlight and assorted page bugs 2026-09-24 05:02:26 +02:00
Admin dda8c30d45 backend: expose owner user id on playlist responses 2026-09-24 04:59:50 +02:00
Admin 906f38140a web-player: dedupe queue, stop at end of queue, open queue once and harden localStorage 2026-09-24 04:59:28 +02:00
Admin 3e546d4a1e web-player: fix open redirect via returnTo, require SESSION_SECRET and validate API inputs 2026-09-24 04:58:08 +02:00
Admin b2f450dcf7 web-player: add Vitest, unit tests and pure queue operations 2026-09-24 04:54:09 +02:00
383 changed files with 15683 additions and 4339 deletions
+6
View File
@@ -14,6 +14,12 @@
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.Api"],
"port": 5111
},
{
"name": "musify-worker",
"runtimeExecutable": "dotnet",
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.Worker"],
"port": 5112
},
{
"name": "musify-streaming-gateway",
"runtimeExecutable": "dotnet",
@@ -9,7 +9,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.Albums
{
/// <summary>Appends your own tracks to an album in the given order, skipping the ones it already has.</summary>
public record AddTracksToAlbumCommand(long UserId, Guid AlbumId, IReadOnlyList<Guid> TrackIds)
: ICommand<ErrorOr<Success>>;
@@ -50,7 +49,6 @@ namespace Musify.Application.Albums
if (toAdd.Count == 0)
return Result.Success;
// Album track numbers are user-visible, so they start at 1.
var nextTrackNumber = (await database.AlbumHasTracks
.Where(link => link.AlbumId == request.AlbumId)
.MaxAsync(link => (int?)link.TrackNumber, cancellationToken) ?? 0) + 1;
@@ -19,7 +19,9 @@ namespace Musify.Application.Albums
string Title,
string? Description,
int? ReleaseYear,
Guid PictureIntentId)
Guid PictureIntentId,
AlbumType Type = AlbumType.Album,
IReadOnlyList<Guid>? TrackIds = null)
: ICommand<ErrorOr<AlbumApplicationResponse>>;
public class CreateAlbumCommandHandler(
@@ -38,6 +40,21 @@ namespace Musify.Application.Albums
if (!userExists)
return AppErrors.NotFound("User", request.UserId);
var trackIds = (request.TrackIds ?? []).Distinct().ToList();
var tracks = await database.Tracks
.AsNoTracking()
.Where(track => trackIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
.Select(track => new { track.Id, track.OwnerUserId, track.IsPublished })
.ToListAsync(cancellationToken);
var missing = trackIds.FirstOrDefault(id => tracks.All(track => track.Id != id));
if (missing != Guid.Empty)
return AppErrors.NotFound("Track", missing);
var foreign = tracks.FirstOrDefault(track => track.OwnerUserId != request.UserId);
if (foreign != null)
return AppErrors.Forbidden("Track", foreign.Id);
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, request.PictureIntentId, request.UserId, UploadIntentPurpose.AlbumPicture, albumConfiguration, cancellationToken);
if (prepared.IsError)
@@ -53,11 +70,19 @@ namespace Musify.Application.Albums
NormalizedTitle = TextNormalizer.Normalize(title),
Description = request.Description,
ReleaseYear = request.ReleaseYear,
Type = request.Type,
Pictures = picture.Pictures
};
await database.Albums.AddAsync(album, cancellationToken);
for (var index = 0; index < trackIds.Count; index++)
{
await database.AlbumHasTracks.AddAsync(
new AlbumHasTrack { AlbumId = album.Id, TrackId = trackIds[index], TrackNumber = index + 1 },
cancellationToken);
}
await eventBus.PublishAsync(
new CreateAlbumResourcesEvent(
album.Id, picture.Intent.Id, picture.Intent.Bucket, picture.Intent.Key, picture.FinalKey, picture.Sizes),
@@ -65,9 +90,15 @@ namespace Musify.Application.Albums
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("Created album {AlbumId} for user {UserId}", album.Id, request.UserId);
logger.LogInformation("Created album {AlbumId} for user {UserId} with {Count} tracks", album.Id, request.UserId, trackIds.Count);
return AlbumApplicationResponse.FromEntity(album, trackCount: 0);
var published = tracks.Where(track => track.IsPublished).Select(track => track.Id).ToHashSet();
var visibleTrackIds = trackIds.Where(published.Contains).ToList();
return AlbumApplicationResponse.FromEntity(
album,
visibleTrackIds.Count,
[.. visibleTrackIds.Take(AlbumProjections.CoverTrackCount)]);
}
}
}
@@ -0,0 +1,35 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Albums.Responses;
using Musify.Application.Contracts;
using Musify.Application.Shared;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Albums
{
public record GetAlbumTrackIdsQuery(long UserId, Guid AlbumId)
: IQuery<ErrorOr<AlbumTrackIdsResponse>>;
public class GetAlbumTrackIdsQueryHandler(IDatabase database)
: IQueryHandler<GetAlbumTrackIdsQuery, ErrorOr<AlbumTrackIdsResponse>>
{
public async ValueTask<ErrorOr<AlbumTrackIdsResponse>> Handle(GetAlbumTrackIdsQuery request, CancellationToken cancellationToken)
{
var found = await database.Albums.FindOwnedAsync(request.AlbumId, request.UserId, cancellationToken);
if (found.IsError)
return found.Errors;
var trackIds = await database.AlbumHasTracks
.AsNoTracking()
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId
&& albumTrack.Track.LifeCycleStatus == LifeCycleStatus.Active)
.OrderBy(albumTrack => albumTrack.TrackNumber)
.ThenBy(albumTrack => albumTrack.Id)
.Select(albumTrack => albumTrack.TrackId)
.ToListAsync(cancellationToken);
return new AlbumTrackIdsResponse(trackIds);
}
}
}
@@ -28,7 +28,7 @@ namespace Musify.Application.Albums
return await database.AlbumHasTracks
.AsNoTracking()
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId && albumTrack.Track.LifeCycleStatus == Domain.ValueObjects.LifeCycleStatus.Active)
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId && albumTrack.Track.LifeCycleStatus == Domain.ValueObjects.LifeCycleStatus.Active && albumTrack.Track.IsPublished)
.OrderBy(albumTrack => albumTrack.TrackNumber)
.ThenBy(albumTrack => albumTrack.Id)
.Select(albumTrack => albumTrack.Track)
@@ -20,6 +20,7 @@ namespace Musify.Application.Albums
var ranked = await database.AlbumHasTracks
.AsNoTracking()
.Where(albumTrack => albumTrack.Album.LifeCycleStatus == Domain.ValueObjects.LifeCycleStatus.Active)
.Where(albumTrack => albumTrack.Track.LifeCycleStatus == Domain.ValueObjects.LifeCycleStatus.Active && albumTrack.Track.IsPublished)
.Join(
listens,
albumTrack => albumTrack.TrackId,
@@ -1,4 +1,5 @@
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Albums.Responses
{
@@ -14,7 +15,8 @@ namespace Musify.Application.Albums.Responses
string? LargeImageKeyName,
DateTime CreatedAt,
DateTime UpdatedAt,
IReadOnlyList<Guid> CoverTrackIds)
IReadOnlyList<Guid> CoverTrackIds,
AlbumType Type)
{
public const int CoverTrackCount = AlbumProjections.CoverTrackCount;
@@ -35,7 +37,8 @@ namespace Musify.Application.Albums.Responses
album.Pictures?.LargeName,
album.CreatedAt,
album.UpdatedAt,
coverTrackIds ?? []);
coverTrackIds ?? [],
album.Type);
}
}
}
@@ -17,16 +17,18 @@ namespace Musify.Application.Albums.Responses
album.Description,
album.ReleaseYear,
album.OwnerUserId,
album.AlbumTracks.Count,
album.AlbumTracks.Count(albumTrack => albumTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && albumTrack.Track.IsPublished),
album.Pictures!.SmallName,
album.Pictures!.MediumName,
album.Pictures!.LargeName,
album.CreatedAt,
album.UpdatedAt,
album.AlbumTracks
.Where(albumTrack => albumTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && albumTrack.Track.IsPublished)
.OrderBy(albumTrack => albumTrack.TrackNumber)
.Take(CoverTrackCount)
.Select(albumTrack => albumTrack.TrackId)
.ToList()));
.ToList(),
album.Type));
}
}
@@ -0,0 +1,4 @@
namespace Musify.Application.Albums.Responses
{
public record AlbumTrackIdsResponse(IReadOnlyList<Guid> TrackIds);
}
@@ -3,11 +3,7 @@ using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Albums.Responses;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Application.Events;
using Musify.Application.Pictures;
using Musify.Application.Services;
using Musify.Application.Shared;
using Musify.Domain.ValueObjects;
@@ -19,15 +15,12 @@ namespace Musify.Application.Albums
string Title,
string? Description,
int? ReleaseYear,
Guid? NewPictureIntentId)
AlbumType? Type = null)
: ICommand<ErrorOr<AlbumApplicationResponse>>;
public class UpdateAlbumCommandHandler(
IEventBus eventBus,
IDatabase database,
UploadIntentValidator uploadIntentValidator,
ILogger<UpdateAlbumCommandHandler> logger,
AlbumConfiguration albumConfiguration)
ILogger<UpdateAlbumCommandHandler> logger)
: ICommandHandler<UpdateAlbumCommand, ErrorOr<AlbumApplicationResponse>>
{
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(UpdateAlbumCommand request, CancellationToken cancellationToken)
@@ -41,24 +34,9 @@ namespace Musify.Application.Albums
album.Title = title;
album.NormalizedTitle = TextNormalizer.Normalize(title);
album.Description = request.Description;
album.Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim();
album.ReleaseYear = request.ReleaseYear;
if (request.NewPictureIntentId is { } intentId)
{
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, intentId, request.UserId, UploadIntentPurpose.AlbumPicture, albumConfiguration, cancellationToken);
if (prepared.IsError)
return prepared.Errors;
var picture = prepared.Value;
album.Pictures = picture.Pictures;
await eventBus.PublishAsync(
new UpdateAlbumPictureSourceEvent(
album.Id, picture.Intent.Id, picture.Intent.Bucket, picture.Intent.Key, picture.FinalKey, picture.Sizes),
cancellationToken);
}
album.Type = request.Type ?? album.Type;
await database.SaveChangesAsync(cancellationToken);
@@ -0,0 +1,59 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Albums.Responses;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Application.Events;
using Musify.Application.Pictures;
using Musify.Application.Services;
using Musify.Application.Shared;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Albums
{
public record UpdateAlbumPictureCommand(long UserId, Guid AlbumId, Guid PictureIntentId)
: ICommand<ErrorOr<AlbumApplicationResponse>>;
public class UpdateAlbumPictureCommandHandler(
IEventBus eventBus,
IDatabase database,
UploadIntentValidator uploadIntentValidator,
ILogger<UpdateAlbumPictureCommandHandler> logger,
AlbumConfiguration albumConfiguration)
: ICommandHandler<UpdateAlbumPictureCommand, ErrorOr<AlbumApplicationResponse>>
{
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(UpdateAlbumPictureCommand request, CancellationToken cancellationToken)
{
var found = await database.Albums.FindOwnedAsync(request.AlbumId, request.UserId, cancellationToken);
if (found.IsError)
return found.Errors;
var album = found.Value;
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, request.PictureIntentId, request.UserId, UploadIntentPurpose.AlbumPicture, albumConfiguration, cancellationToken);
if (prepared.IsError)
return prepared.Errors;
var picture = prepared.Value;
album.Pictures = picture.Pictures;
await eventBus.PublishAsync(
new UpdateAlbumPictureSourceEvent(
album.Id, picture.Intent.Id, picture.Intent.Bucket, picture.Intent.Key, picture.FinalKey, picture.Sizes),
cancellationToken);
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("Updated picture of album {AlbumId}", album.Id);
return await database.Albums
.AsNoTracking()
.Where(a => a.Id == album.Id)
.SelectResponse()
.SingleAsync(cancellationToken);
}
}
}
@@ -83,7 +83,6 @@ namespace Musify.Application.Configuration
public static class PictureSizeParser
{
/// <summary>Parses the <c>size</c> query value; anything unknown means <see cref="PictureSize.Medium"/>.</summary>
public static PictureSize Parse(string? value) =>
Enum.TryParse<PictureSize>(value, ignoreCase: true, out var size) && Enum.IsDefined(size)
? size
@@ -10,10 +10,10 @@ namespace Musify.Application.Configuration
public int UploadUrlExpiresInSeconds { get; set; } = 120;
[Range(1, 100)]
public int MaxActiveUploadIntentsPerUser { get; set; } = 5;
public int MaxActiveUploadIntentsPerUser { get; set; } = 50;
[Range(1, long.MaxValue)]
public long MaxActiveUploadBytesPerUser { get; set; } = 200L * 1024 * 1024;
public long MaxActiveUploadBytesPerUser { get; set; } = 1024L * 1024 * 1024;
[Range(1, long.MaxValue)]
public long MaxUploadBytes { get; set; } = 100L * 1024 * 1024;
@@ -2,7 +2,6 @@ namespace Musify.Application.Contracts
{
public interface IStorageService
{
/// <summary>Opens an object for reading, or returns null when it does not exist.</summary>
public Task<Stream?> GetFileAsync(string bucket, string key, CancellationToken cancellationToken);
public Task<ObjectMetaData?> HeadObjectAsync(string bucket, string key, CancellationToken cancellationToken);
@@ -4,11 +4,11 @@ namespace Musify.Application.Events
{
public record CreateTrackResourcesEvent(
Guid TrackId,
Guid PictureIntentId,
Guid? PictureIntentId,
Guid AudioIntentId,
string Bucket,
string PictureSourceKey,
string PictureDestinationKey,
string? PictureSourceKey,
string? PictureDestinationKey,
string AudioSourceKey,
string AudioDestinationKey,
string AudioProcessedFolderKey,
@@ -11,7 +11,7 @@ namespace Musify.Application.Genres
{
public ValueTask<IReadOnlyList<AvailableGenreResponse>> Handle(GetAvailableGenresQuery request, CancellationToken cancellationToken)
{
var all = Enum.GetValues<Genre>();
var all = Enum.GetValues<Genre>().Where(genre => genre != Genre.None).ToArray();
IReadOnlyList<AvailableGenreResponse> result = all
.Select(genre => new AvailableGenreResponse(
@@ -15,7 +15,7 @@ namespace Musify.Application.Genres
{
var rows = await database.TrackTags
.AsNoTracking()
.Where(tag => tag.Track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(tag => tag.Track.LifeCycleStatus == LifeCycleStatus.Active && tag.Track.IsPublished)
.GroupBy(tag => tag.Tag)
.Select(group => new { Genre = group.Key, TrackCount = group.Select(tag => tag.TrackId).Distinct().Count() })
.ToListAsync(cancellationToken);
@@ -20,7 +20,7 @@ namespace Musify.Application.Likes
{
return await database.TrackLikes
.AsNoTracking()
.Where(like => like.UserId == request.UserId && like.Track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(like => like.UserId == request.UserId && like.Track.LifeCycleStatus == LifeCycleStatus.Active && like.Track.IsPublished)
.OrderByDescending(like => like.CreatedAt)
.ThenBy(like => like.Id)
.Select(like => like.Track)
@@ -21,7 +21,7 @@ namespace Musify.Application.Likes
{
var trackExists = await database.Tracks
.AsNoTracking()
.AnyAsync(t => t.Id == request.TrackId && t.LifeCycleStatus == LifeCycleStatus.Active, cancellationToken);
.AnyAsync(t => t.Id == request.TrackId && t.LifeCycleStatus == LifeCycleStatus.Active && t.IsPublished, cancellationToken);
if (!trackExists)
return AppErrors.NotFound("Track", request.TrackId);
@@ -44,7 +44,6 @@ namespace Musify.Application.Likes
nowLiked = true;
}
// A concurrent double click can hit the unique index; the outcome is already in place, so treat it as a no-op.
var saved = await database.TrySaveChangesAsync(
AppErrors.Conflict("TrackLike.Duplicate", "Track is already liked."), cancellationToken);
if (saved.IsError)
@@ -25,7 +25,7 @@ namespace Musify.Application.Mixes
var libraryTrackIds = await database.Tracks
.AsNoTracking()
.Where(track => track.OwnerUserId == userId && track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(track => track.OwnerUserId == userId && track.LifeCycleStatus == LifeCycleStatus.Active && track.IsPublished)
.Select(track => track.Id)
.ToListAsync(cancellationToken);
@@ -25,7 +25,13 @@ namespace Musify.Application.Mixes
mix => mix.Id,
mix => mix.Items.OrderBy(item => item.Position).ToList());
var coverItems = orderedItemsByMix.Values
var visibleTrackIds = await MixItemMapper.VisibleTrackIdsAsync(
database, orderedItemsByMix.Values.SelectMany(items => items), cancellationToken);
var visibleItemsByMix = orderedItemsByMix.ToDictionary(
entry => entry.Key,
entry => entry.Value.Where(item => visibleTrackIds.Contains(item.TrackId)).ToList());
var coverItems = visibleItemsByMix.Values
.SelectMany(items => items.Take(MixApplicationResponse.CoverItemCount))
.ToList();
var coverResponses = (await MixItemMapper.ToResponsesAsync(database, coverItems, cancellationToken))
@@ -35,7 +41,7 @@ namespace Musify.Application.Mixes
var responses = new List<MixApplicationResponse>(mixes.Count);
foreach (var mix in mixes)
{
var orderedItems = orderedItemsByMix[mix.Id];
var orderedItems = visibleItemsByMix[mix.Id];
var covers = orderedItems
.Take(MixApplicationResponse.CoverItemCount)
.Where(item => coverResponses.ContainsKey(item.TrackId))
@@ -9,6 +9,22 @@ namespace Musify.Application.Mixes
internal static class MixItemMapper
{
public static async Task<HashSet<Guid>> VisibleTrackIdsAsync(
IDatabase database,
IEnumerable<MixItem> items,
CancellationToken cancellationToken)
{
var trackIds = items.Select(item => item.TrackId).Distinct().ToList();
var visible = await database.Tracks
.AsNoTracking()
.Where(track => trackIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active && track.IsPublished)
.Select(track => track.Id)
.ToListAsync(cancellationToken);
return [.. visible];
}
public static async Task<List<MixItemApplicationResponse>> ToResponsesAsync(
IDatabase database,
IReadOnlyList<MixItem> orderedItems,
@@ -19,7 +35,7 @@ namespace Musify.Application.Mixes
var tracksById = await database.Tracks
.AsNoTracking()
.Include(track => track.Owner)
.Where(track => trackIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(track => trackIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active && track.IsPublished)
.Select(track => new { Track = track, ListensCount = track.ListeningHistories.Count(l => l.IsCounted) })
.ToDictionaryAsync(x => x.Track.Id, cancellationToken);
@@ -35,10 +35,7 @@ namespace Musify.Application.Pictures
{
var (source, routes) = request.Owner switch
{
CoverOwner.Track => (await database.Tracks.AsNoTracking()
.Where(t => t.Id == request.Id && t.LifeCycleStatus == LifeCycleStatus.Active)
.Select(t => new CoverSource(t.OwnerUserId, t.Pictures.OriginalName, t.Pictures.SmallName, t.Pictures.MediumName, t.Pictures.LargeName))
.SingleOrDefaultAsync(cancellationToken), trackConfiguration.Routes),
CoverOwner.Track => await FindTrackSourceAsync(request.Id, cancellationToken),
CoverOwner.Album => (await database.Albums.AsNoTracking()
.Where(a => a.Id == request.Id && a.LifeCycleStatus == LifeCycleStatus.Active && a.Pictures != null)
.Select(a => new CoverSource(a.OwnerUserId, a.Pictures!.OriginalName, a.Pictures.SmallName, a.Pictures.MediumName, a.Pictures.LargeName))
@@ -60,7 +57,6 @@ namespace Musify.Application.Pictures
_ => source.Medium
};
// The resized files only exist once processing has finished; until then serve the original.
var (name, key) = !string.IsNullOrEmpty(resizedName)
? (resizedName, routes.BuildPicturePath(request.Size, resizedName))
: !string.IsNullOrEmpty(source.Original)
@@ -72,5 +68,34 @@ namespace Musify.Application.Pictures
return new CoverLocation(storageConfiguration.Bucket, key, MimeUtility.GetMimeMapping(name));
}
private async Task<(CoverSource? Source, PictureRoutes Routes)> FindTrackSourceAsync(Guid trackId, CancellationToken cancellationToken)
{
var track = await database.Tracks.AsNoTracking()
.Where(t => t.Id == trackId && t.LifeCycleStatus == LifeCycleStatus.Active)
.Select(t => new
{
Own = new CoverSource(t.OwnerUserId, t.Pictures.OriginalName, t.Pictures.SmallName, t.Pictures.MediumName, t.Pictures.LargeName),
Album = t.AlbumTracks
.Where(albumTrack => albumTrack.Album.LifeCycleStatus == LifeCycleStatus.Active && albumTrack.Album.Pictures != null)
.OrderBy(albumTrack => albumTrack.AddedAt)
.ThenBy(albumTrack => albumTrack.AlbumId)
.Select(albumTrack => new CoverSource(
albumTrack.Album.OwnerUserId,
albumTrack.Album.Pictures!.OriginalName,
albumTrack.Album.Pictures.SmallName,
albumTrack.Album.Pictures.MediumName,
albumTrack.Album.Pictures.LargeName))
.FirstOrDefault()
})
.SingleOrDefaultAsync(cancellationToken);
if (track == null)
return (null, trackConfiguration.Routes);
return string.IsNullOrEmpty(track.Own.Original) && track.Album != null
? (track.Album, albumConfiguration.Routes)
: (track.Own, trackConfiguration.Routes);
}
}
}
@@ -7,7 +7,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.Pictures
{
/// <summary>What an album or playlist needs to switch to a freshly uploaded picture.</summary>
public sealed record PreparedPicture(UploadIntent Intent, EntityPictures Pictures, string FinalKey, ImageSizes Sizes);
public static class PictureSourceChange
@@ -0,0 +1,81 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Albums.Responses;
using Musify.Application.Contracts;
using Musify.Application.PlayLists.Responses;
using Musify.Application.Shared;
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
namespace Musify.Application.PlayLists
{
public record AddAlbumToPlayListCommand(long UserId, Guid PlayListId, Guid AlbumId)
: ICommand<ErrorOr<AddAlbumToPlayListResponse>>;
public class AddAlbumToPlayListCommandHandler(
IDatabase database,
ILogger<AddAlbumToPlayListCommandHandler> logger)
: ICommandHandler<AddAlbumToPlayListCommand, ErrorOr<AddAlbumToPlayListResponse>>
{
public async ValueTask<ErrorOr<AddAlbumToPlayListResponse>> Handle(AddAlbumToPlayListCommand request, CancellationToken cancellationToken)
{
var playList = await database.PlayLists.FindOwnedAsync(request.PlayListId, request.UserId, cancellationToken);
if (playList.IsError)
return playList.Errors;
var albumExists = await database.Albums
.AsNoTracking()
.Active()
.AnyAsync(album => album.Id == request.AlbumId, cancellationToken);
if (!albumExists)
return AppErrors.NotFound("Album", request.AlbumId);
var albumTrackIds = await database.AlbumHasTracks
.AsNoTracking()
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId && albumTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && albumTrack.Track.IsPublished)
.OrderBy(albumTrack => albumTrack.TrackNumber)
.Select(albumTrack => albumTrack.TrackId)
.ToListAsync(cancellationToken);
var playListTracksQuery = database.PlayListHasTracks
.Where(link => link.PlayListId == request.PlayListId);
var existingTrackIds = (await playListTracksQuery
.Select(link => link.TrackId)
.ToListAsync(cancellationToken)).ToHashSet();
var newTrackIds = albumTrackIds
.Where(trackId => !existingTrackIds.Contains(trackId))
.ToList();
if (newTrackIds.Count == 0)
return new AddAlbumToPlayListResponse(0);
var nextPosition = existingTrackIds.Count > 0
? await playListTracksQuery.MaxAsync(link => link.Position, cancellationToken) + 1
: 0;
foreach (var trackId in newTrackIds)
{
await database.PlayListHasTracks.AddAsync(new PlayListHasTrack
{
PlayListId = request.PlayListId,
TrackId = trackId,
Position = nextPosition++
}, cancellationToken);
}
var saved = await database.TrySaveChangesAsync(
AppErrors.Conflict("PlayList.ConcurrentChange", "The playlist changed while adding tracks. Try again."), cancellationToken);
if (saved.IsError)
return saved.Errors;
logger.LogInformation("Added {Count} tracks from album {AlbumId} to playlist {PlayListId}",
newTrackIds.Count, request.AlbumId, request.PlayListId);
return new AddAlbumToPlayListResponse(newTrackIds.Count);
}
}
}
@@ -9,7 +9,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.PlayLists
{
/// <summary>Appends tracks to a playlist in the given order, skipping the ones it already has.</summary>
public record AddTracksToPlayListCommand(long UserId, Guid PlayListId, IReadOnlyList<Guid> TrackIds)
: ICommand<ErrorOr<Success>>;
@@ -28,7 +27,7 @@ namespace Musify.Application.PlayLists
var existingIds = await database.Tracks
.AsNoTracking()
.Where(track => requestedIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(track => requestedIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active && track.IsPublished)
.Select(track => track.Id)
.ToListAsync(cancellationToken);
@@ -46,10 +45,12 @@ namespace Musify.Application.PlayLists
if (toAdd.Count == 0)
return Result.Success;
// Playlist positions are internal indexes, so they start at 0.
var nextPosition = (await database.PlayListHasTracks
.Where(link => link.PlayListId == request.PlayListId)
.MaxAsync(link => (int?)link.Position, cancellationToken) ?? -1) + 1;
var playListTracksQuery = database.PlayListHasTracks
.Where(link => link.PlayListId == request.PlayListId);
var nextPosition = await playListTracksQuery.AnyAsync(cancellationToken)
? await playListTracksQuery.MaxAsync(link => link.Position, cancellationToken) + 1
: 0;
foreach (var trackId in toAdd)
{
@@ -39,10 +39,10 @@ namespace Musify.Application.PlayLists
return AppErrors.NotFound("User", request.UserId);
PreparedPicture? picture = null;
if (request.PictureIntentId is { } intentId)
if (request.PictureIntentId.HasValue)
{
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, intentId, request.UserId, UploadIntentPurpose.PlayListPicture, playListConfiguration, cancellationToken);
uploadIntentValidator, request.PictureIntentId.Value, request.UserId, UploadIntentPurpose.PlayListPicture, playListConfiguration, cancellationToken);
if (prepared.IsError)
return prepared.Errors;
@@ -31,7 +31,7 @@ namespace Musify.Application.PlayLists
return await database.PlayListHasTracks
.AsNoTracking()
.Where(playListTrack => playListTrack.PlayListId == request.PlayListId && playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(playListTrack => playListTrack.PlayListId == request.PlayListId && playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && playListTrack.Track.IsPublished)
.OrderBy(playListTrack => playListTrack.Position)
.ThenBy(playListTrack => playListTrack.Id)
.Select(playListTrack => playListTrack.Track)
@@ -0,0 +1,4 @@
namespace Musify.Application.PlayLists.Responses
{
public record AddAlbumToPlayListResponse(int AddedCount);
}
@@ -25,14 +25,15 @@ namespace Musify.Application.PlayLists.Responses
playList.CreatedAt,
playList.UpdatedAt,
playList.PlayListTracks
.Where(playListTrack => playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && playListTrack.Track.IsPublished)
.OrderBy(playListTrack => playListTrack.Position)
.Take(CoverTrackCount)
.Select(playListTrack => playListTrack.TrackId)
.ToList(),
playList.OwnerUserId,
playList.PlayListTracks.Count(playListTrack => playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active),
playList.PlayListTracks.Count(playListTrack => playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && playListTrack.Track.IsPublished),
playList.PlayListTracks
.Where(playListTrack => playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(playListTrack => playListTrack.Track.LifeCycleStatus == LifeCycleStatus.Active && playListTrack.Track.IsPublished)
.Sum(playListTrack => playListTrack.Track.DurationSeconds)));
}
}
@@ -2,12 +2,8 @@ using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Application.Events;
using Musify.Application.Pictures;
using Musify.Application.PlayLists.Responses;
using Musify.Application.Services;
using Musify.Application.Shared;
using Musify.Domain.ValueObjects;
@@ -16,18 +12,14 @@ namespace Musify.Application.PlayLists
public record UpdatePlayListCommand(
long UserId,
Guid PlayListId,
string? NewName,
string NewName,
string? NewDescription,
Guid? NewPictureIntentId,
PlayListVisibility? NewVisibility = null)
PlayListVisibility NewVisibility)
: ICommand<ErrorOr<PlayListApplicationResponse>>;
public class UpdatePlayListCommandHandler(
IEventBus eventBus,
IDatabase database,
UploadIntentValidator uploadIntentValidator,
ILogger<UpdatePlayListCommandHandler> logger,
PlayListConfiguration playListConfiguration)
ILogger<UpdatePlayListCommandHandler> logger)
: ICommandHandler<UpdatePlayListCommand, ErrorOr<PlayListApplicationResponse>>
{
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(UpdatePlayListCommand request, CancellationToken cancellationToken)
@@ -38,34 +30,10 @@ namespace Musify.Application.PlayLists
var playList = found.Value;
if (!string.IsNullOrWhiteSpace(request.NewName))
{
playList.Name = request.NewName.Trim();
playList.NormalizedName = TextNormalizer.Normalize(request.NewName);
}
// null means "unchanged"; a blank description clears it.
if (request.NewDescription != null)
playList.Description = string.IsNullOrWhiteSpace(request.NewDescription) ? null : request.NewDescription.Trim();
if (request.NewVisibility is { } visibility)
playList.Visibility = visibility;
if (request.NewPictureIntentId is { } intentId)
{
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, intentId, request.UserId, UploadIntentPurpose.PlayListPicture, playListConfiguration, cancellationToken);
if (prepared.IsError)
return prepared.Errors;
var picture = prepared.Value;
playList.Pictures = picture.Pictures;
await eventBus.PublishAsync(
new UpdatePlayListPictureSourceEvent(
playList.Id, picture.Intent.Id, picture.Intent.Bucket, picture.Intent.Key, picture.FinalKey, picture.Sizes),
cancellationToken);
}
playList.Name = request.NewName.Trim();
playList.NormalizedName = TextNormalizer.Normalize(request.NewName);
playList.Description = string.IsNullOrWhiteSpace(request.NewDescription) ? null : request.NewDescription.Trim();
playList.Visibility = request.NewVisibility;
await database.SaveChangesAsync(cancellationToken);
@@ -0,0 +1,59 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Configuration;
using Musify.Application.Contracts;
using Musify.Application.Events;
using Musify.Application.Pictures;
using Musify.Application.PlayLists.Responses;
using Musify.Application.Services;
using Musify.Application.Shared;
using Musify.Domain.ValueObjects;
namespace Musify.Application.PlayLists
{
public record UpdatePlayListPictureCommand(long UserId, Guid PlayListId, Guid PictureIntentId)
: ICommand<ErrorOr<PlayListApplicationResponse>>;
public class UpdatePlayListPictureCommandHandler(
IEventBus eventBus,
IDatabase database,
UploadIntentValidator uploadIntentValidator,
ILogger<UpdatePlayListPictureCommandHandler> logger,
PlayListConfiguration playListConfiguration)
: ICommandHandler<UpdatePlayListPictureCommand, ErrorOr<PlayListApplicationResponse>>
{
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(UpdatePlayListPictureCommand request, CancellationToken cancellationToken)
{
var found = await database.PlayLists.FindOwnedAsync(request.PlayListId, request.UserId, cancellationToken);
if (found.IsError)
return found.Errors;
var playList = found.Value;
var prepared = await PictureSourceChange.PrepareAsync(
uploadIntentValidator, request.PictureIntentId, request.UserId, UploadIntentPurpose.PlayListPicture, playListConfiguration, cancellationToken);
if (prepared.IsError)
return prepared.Errors;
var picture = prepared.Value;
playList.Pictures = picture.Pictures;
await eventBus.PublishAsync(
new UpdatePlayListPictureSourceEvent(
playList.Id, picture.Intent.Id, picture.Intent.Bucket, picture.Intent.Key, picture.FinalKey, picture.Sizes),
cancellationToken);
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("Updated picture of playlist {PlayListId}", playList.Id);
return await database.PlayLists
.AsNoTracking()
.Where(p => p.Id == playList.Id)
.SelectResponse()
.SingleAsync(cancellationToken);
}
}
}
@@ -4,7 +4,6 @@ using Musify.Application.Tracks.Responses;
namespace Musify.Application.Services
{
/// <summary>Builds the stream URL and signed ticket for a processed track. It never touches the database.</summary>
public sealed class TrackStreamIssuer(
IStreamTicketService ticketService,
TrackConfiguration trackConfiguration,
@@ -15,7 +15,8 @@ namespace Musify.Application.Services
PictureRoutes Routes,
string FileType,
string ContentType,
long? ExpectedSizeBytes);
long? ExpectedSizeBytes,
int? SharedKeyGroup = null);
public sealed record IssuedUpload(
Guid IntentId,
@@ -24,7 +25,6 @@ namespace Musify.Application.Services
string ContentType,
string UploadUrl);
/// <summary>Issues pre-signed upload URLs and the upload intents that track them, checking the user quota first.</summary>
public sealed class UploadIntentIssuer(
IDatabase database,
IStorageService storageService,
@@ -44,11 +44,15 @@ namespace Musify.Application.Services
if (!userExists)
return AppErrors.NotFound("User", userId);
var sharedKeys = new Dictionary<int, string>();
var planned = requests
.Select(request =>
{
var objectName = $"{Guid.NewGuid()}.{request.FileType.TrimStart('.').ToLowerInvariant()}";
var key = request.Routes.BuildTempPath(uploadIntentConfiguration.TempRootPrefix, userId, objectName);
if (request.SharedKeyGroup is { } group)
key = sharedKeys.TryAdd(group, key) ? key : sharedKeys[group];
var size = request.ExpectedSizeBytes ?? DefaultSize(request.Purpose);
return (Request: request, ObjectName: objectName, Key: key, Size: size);
})
@@ -7,10 +7,6 @@ namespace Musify.Application.Shared
{
public static class OwnershipExtensions
{
/// <summary>
/// Loads an active, tracked entity owned by <paramref name="userId"/>: NotFound when it is missing
/// or not active, Forbidden when someone else owns it.
/// </summary>
public static async Task<ErrorOr<T>> FindOwnedAsync<T>(
this DbSet<T> set, Guid id, long userId, CancellationToken cancellationToken)
where T : class, IOwnedEntity, IHasLifeCycle
@@ -18,7 +18,6 @@ namespace Musify.Application.Shared
public static class PaginationExtensions
{
/// <summary>Counts and pages the same (already filtered, ordered and projected) query.</summary>
public static async Task<PaginatedResponse<T>> ToPaginatedAsync<T>(
this IQueryable<T> query, PageRequest page, CancellationToken cancellationToken)
{
@@ -16,7 +16,7 @@ namespace Musify.Application.Tracks
public record CreateTrackCommand(
long UserId,
string Title,
Guid PictureIntentId,
Guid? PictureIntentId,
Guid AudioIntentId,
IReadOnlyCollection<Genre> Tags,
bool IsExplicit = false)
@@ -45,20 +45,27 @@ namespace Musify.Application.Tracks
if (request.PictureIntentId == request.AudioIntentId)
return Error.Validation(description: "Picture and audio must use different upload intents.");
var pictureValidation = await uploadIntentValidator.ValidateAndLoadAsync(
request.PictureIntentId, request.UserId, UploadIntentPurpose.TrackPicture, cancellationToken);
if (pictureValidation.IsError)
return pictureValidation.Errors;
UploadIntent? pictureIntent = null;
if (request.PictureIntentId is { } pictureIntentId)
{
var pictureValidation = await uploadIntentValidator.ValidateAndLoadAsync(
pictureIntentId, request.UserId, UploadIntentPurpose.TrackPicture, cancellationToken);
if (pictureValidation.IsError)
return pictureValidation.Errors;
pictureIntent = pictureValidation.Value;
}
var audioValidation = await uploadIntentValidator.ValidateAndLoadAsync(
request.AudioIntentId, request.UserId, UploadIntentPurpose.TrackAudio, cancellationToken);
if (audioValidation.IsError)
return audioValidation.Errors;
var pictureIntent = pictureValidation.Value;
var audioIntent = audioValidation.Value;
var finalPictureKey = trackConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
var finalPictureKey = pictureIntent == null
? null
: trackConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
var finalAudioKey = trackConfiguration.Routes.BuildOriginalAudioPath(request.UserId, audioIntent.ObjectName);
var audioProcessedFolderKey = trackConfiguration.Routes.BuildProcessedAudioPath(Guid.NewGuid().ToString());
@@ -71,11 +78,11 @@ namespace Musify.Application.Tracks
IsExplicit = request.IsExplicit,
Pictures = new TrackPictures
{
OriginalName = pictureIntent.ObjectName,
OriginalName = pictureIntent?.ObjectName,
SmallName = trackConfiguration.Routes.PresetSmallPicture,
MediumName = trackConfiguration.Routes.PresetMediumPicture,
LargeName = trackConfiguration.Routes.PresetLargePicture,
ProcessingStatus = ProcessingStatus.Pending
ProcessingStatus = pictureIntent == null ? ProcessingStatus.Completed : ProcessingStatus.Pending
},
Audio = new TrackAudio
{
@@ -90,15 +97,14 @@ namespace Musify.Application.Tracks
await database.Tracks.AddAsync(trackEntity, cancellationToken);
var sizes = trackConfiguration.PicturesSizes.ToImageSizes(trackConfiguration.Routes);
await eventBus.PublishAsync(
new CreateTrackResourcesEvent(
trackEntity.Id,
pictureIntent.Id,
pictureIntent?.Id,
audioIntent.Id,
pictureIntent.Bucket,
pictureIntent.Key,
audioIntent.Bucket,
pictureIntent?.Key,
finalPictureKey,
audioIntent.Key,
finalAudioKey,
@@ -0,0 +1,60 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Application.Events;
using Musify.Application.Shared;
using Musify.Application.Tracks.Responses;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
public record DeleteTracksCommand(long UserId, IReadOnlyList<Guid> TrackIds)
: ICommand<ErrorOr<DeleteTracksResponse>>;
public class DeleteTracksCommandHandler(
IDatabase database,
IEventBus eventBus,
ILogger<DeleteTracksCommandHandler> logger)
: ICommandHandler<DeleteTracksCommand, ErrorOr<DeleteTracksResponse>>
{
public async ValueTask<ErrorOr<DeleteTracksResponse>> Handle(DeleteTracksCommand request, CancellationToken cancellationToken)
{
var requestedIds = request.TrackIds.Distinct().ToList();
var tracks = await database.Tracks
.Where(track => requestedIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
.ToListAsync(cancellationToken);
var foreign = tracks.FirstOrDefault(track => track.OwnerUserId != request.UserId);
if (foreign != null)
return AppErrors.Forbidden("Track", foreign.Id);
var deleted = new List<Guid>();
var failed = new List<Guid>();
foreach (var trackId in requestedIds)
{
var track = tracks.SingleOrDefault(candidate => candidate.Id == trackId);
if (track == null || track.Audio.IsInProgress)
{
failed.Add(trackId);
continue;
}
track.LifeCycleStatus = LifeCycleStatus.Removing;
await eventBus.PublishAsync(new DeleteTrackEvent(track.Id, request.UserId), cancellationToken);
deleted.Add(trackId);
}
if (deleted.Count > 0)
{
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("Marked {Count} tracks of user {UserId} as removing", deleted.Count, request.UserId);
}
return new DeleteTracksResponse(deleted, failed);
}
}
}
@@ -17,7 +17,7 @@ namespace Musify.Application.Tracks
.AsNoTracking()
.Include(t => t.Track.Owner)
.Include(t => t.Track.Tags)
.Where(t => t.UserId == query.UserId && t.IsCounted && t.Track.LifeCycleStatus == LifeCycleStatus.Active)
.Where(t => t.UserId == query.UserId && t.IsCounted && t.Track.LifeCycleStatus == LifeCycleStatus.Active && t.Track.IsPublished)
.OrderByDescending(t => t.ListenedAt)
.ThenBy(t => t.Id)
.Select(t => TrackApplicationResponse.FromEntity(t.Track, t.Track.ListeningHistories.Count(l => l.IsCounted)))
@@ -27,6 +27,7 @@ namespace Musify.Application.Tracks
var tracksById = await database.Tracks
.AsNoTracking()
.Active()
.WherePublished()
.Where(t => recentTrackIds.Contains(t.Id))
.SelectResponse()
.ToDictionaryAsync(t => t.Id, cancellationToken);
@@ -7,7 +7,7 @@ using Musify.Application.Tracks.Responses;
namespace Musify.Application.Tracks
{
public record GetTrackByIdQuery(Guid TrackId)
public record GetTrackByIdQuery(Guid TrackId, long? ViewerId = null)
: IQuery<ErrorOr<TrackApplicationResponse>>;
public class GetTrackByIdQueryHandler(IDatabase database)
@@ -18,6 +18,7 @@ namespace Musify.Application.Tracks
var track = await database.Tracks
.AsNoTracking()
.Active()
.VisibleTo(request.ViewerId)
.Where(t => t.Id == request.TrackId)
.SelectResponse()
.SingleOrDefaultAsync(cancellationToken);
@@ -0,0 +1,40 @@
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Tracks.Responses;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
public record GetTrackStatusCountsQuery(long UserId)
: IQuery<TrackStatusCountsResponse>;
public class GetTrackStatusCountsQueryHandler(IDatabase database)
: IQueryHandler<GetTrackStatusCountsQuery, TrackStatusCountsResponse>
{
public async ValueTask<TrackStatusCountsResponse> Handle(GetTrackStatusCountsQuery request, CancellationToken cancellationToken)
{
var counts = await database.Tracks
.AsNoTracking()
.Active()
.Where(track => track.OwnerUserId == request.UserId)
.GroupBy(track => new { track.Audio.TranscodeStatus, track.IsPublished })
.Select(group => new { group.Key.TranscodeStatus, group.Key.IsPublished, Count = group.Count() })
.ToListAsync(cancellationToken);
int CountOf(ProcessingStatus status) => counts.Where(c => c.TranscodeStatus == status).Sum(c => c.Count);
var published = counts.Where(c => c.IsPublished).Sum(c => c.Count);
var total = counts.Sum(c => c.Count);
return new TrackStatusCountsResponse(
total,
CountOf(ProcessingStatus.Pending),
CountOf(ProcessingStatus.Processing),
CountOf(ProcessingStatus.Completed),
CountOf(ProcessingStatus.Failed),
published,
total - published);
}
}
}
@@ -17,7 +17,8 @@ namespace Musify.Application.Tracks
{
var tracksQuery = database.Tracks
.AsNoTracking()
.Active();
.Active()
.WherePublished();
if (!string.IsNullOrWhiteSpace(request.Name))
{
@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Shared;
using Musify.Application.Tracks.Responses;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
@@ -11,29 +12,44 @@ namespace Musify.Application.Tracks
long UserId,
string? Name,
int PageNumber,
int PageSize)
: IQuery<ErrorOr<PaginatedResponse<TrackApplicationResponse>>>;
int PageSize,
IReadOnlyList<ProcessingStatus>? Statuses = null,
long? ViewerId = null,
bool? IsPublished = null)
: IQuery<ErrorOr<PaginatedResponse<UserTrackApplicationResponse>>>;
public class GetTracksByUserIdQueryHandler(IDatabase database)
: IQueryHandler<GetTracksByUserIdQuery, ErrorOr<PaginatedResponse<TrackApplicationResponse>>>
: IQueryHandler<GetTracksByUserIdQuery, ErrorOr<PaginatedResponse<UserTrackApplicationResponse>>>
{
public async ValueTask<ErrorOr<PaginatedResponse<TrackApplicationResponse>>> Handle(GetTracksByUserIdQuery request, CancellationToken cancellationToken)
public async ValueTask<ErrorOr<PaginatedResponse<UserTrackApplicationResponse>>> Handle(GetTracksByUserIdQuery request, CancellationToken cancellationToken)
{
var tracksQuery = database.Tracks
.AsNoTracking()
.Active()
.Where(track => track.OwnerUserId == request.UserId);
if (request.ViewerId != request.UserId)
tracksQuery = tracksQuery.WherePublished();
if (!string.IsNullOrWhiteSpace(request.Name))
{
var normalizedName = TextNormalizer.Normalize(request.Name);
tracksQuery = tracksQuery.Where(track => track.NormalizedTitle.Contains(normalizedName));
}
if (request.Statuses is { Count: > 0 } statuses)
{
var statusList = statuses.Distinct().ToList();
tracksQuery = tracksQuery.Where(track => statusList.Contains(track.Audio.TranscodeStatus));
}
if (request.IsPublished is { } isPublished)
tracksQuery = tracksQuery.Where(track => track.IsPublished == isPublished);
return await tracksQuery
.OrderByDescending(track => track.CreatedAt)
.ThenBy(track => track.Id)
.SelectResponse()
.SelectUserResponse()
.ToPaginatedAsync(new PageRequest(request.PageNumber, request.PageSize), cancellationToken);
}
}
@@ -7,14 +7,17 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
public record AudioUploadSpec(string FileType, string ContentType, long? ExpectedSizeBytes = null);
public record RequestTrackUploadUrlsCommand(
long UserId,
string PictureFileType,
string PictureContentType,
string AudioFileType,
string AudioContentType,
string? PictureFileType,
string? PictureContentType,
string? AudioFileType = null,
string? AudioContentType = null,
long? ExpectedPictureSizeBytes = null,
long? ExpectedAudioSizeBytes = null)
long? ExpectedAudioSizeBytes = null,
IReadOnlyList<AudioUploadSpec>? Audios = null)
: ICommand<ErrorOr<TrackUploadUrlsResponse>>;
public class RequestTrackUploadUrlsCommandHandler(
@@ -24,35 +27,75 @@ namespace Musify.Application.Tracks
UploadIntentConfiguration uploadIntentConfiguration)
: ICommandHandler<RequestTrackUploadUrlsCommand, ErrorOr<TrackUploadUrlsResponse>>
{
private const int PictureKeyGroup = 1;
public async ValueTask<ErrorOr<TrackUploadUrlsResponse>> Handle(RequestTrackUploadUrlsCommand request, CancellationToken cancellationToken)
{
var audios = ResolveAudios(request);
if (audios.Count == 0)
return Error.Validation(description: "At least one audio file is required.");
var hasPicture = request.PictureFileType != null && request.PictureContentType != null;
var routes = trackConfiguration.Routes;
var issued = await issuer.IssueAsync(
request.UserId,
[
new UploadRequest(UploadIntentPurpose.TrackPicture, routes, request.PictureFileType, request.PictureContentType, request.ExpectedPictureSizeBytes),
new UploadRequest(UploadIntentPurpose.TrackAudio, routes, request.AudioFileType, request.AudioContentType, request.ExpectedAudioSizeBytes)
],
cancellationToken);
var uploads = new List<UploadRequest>();
if (hasPicture)
{
for (var index = 0; index < audios.Count; index++)
{
uploads.Add(new UploadRequest(
UploadIntentPurpose.TrackPicture, routes, request.PictureFileType!, request.PictureContentType!,
request.ExpectedPictureSizeBytes, PictureKeyGroup));
}
}
uploads.AddRange(audios.Select(audio =>
new UploadRequest(UploadIntentPurpose.TrackAudio, routes, audio.FileType, audio.ContentType, audio.ExpectedSizeBytes)));
var issued = await issuer.IssueAsync(request.UserId, uploads, cancellationToken);
if (issued.IsError)
return issued.Errors;
var picture = issued.Value[0];
var audio = issued.Value[1];
var pictures = hasPicture ? issued.Value.Take(audios.Count).ToList() : [];
var audioUploads = issued.Value.Skip(pictures.Count).ToList();
var items = audioUploads
.Select((audio, index) => new TrackAudioUpload(
audio.IntentId,
hasPicture ? pictures[index].IntentId : null,
audio.Key,
audio.ObjectName,
audio.ContentType,
audio.UploadUrl))
.ToList();
var firstPicture = pictures.Count > 0 ? pictures[0] : null;
var firstAudio = audioUploads[0];
return new TrackUploadUrlsResponse(
picture.IntentId,
audio.IntentId,
firstPicture?.IntentId,
firstAudio.IntentId,
storageConfiguration.Bucket,
picture.Key,
picture.ObjectName,
picture.ContentType,
picture.UploadUrl,
audio.Key,
audio.ObjectName,
audio.ContentType,
audio.UploadUrl,
uploadIntentConfiguration.UploadUrlExpiresInSeconds);
firstPicture?.Key,
firstPicture?.ObjectName,
firstPicture?.ContentType,
firstPicture?.UploadUrl,
firstAudio.Key,
firstAudio.ObjectName,
firstAudio.ContentType,
firstAudio.UploadUrl,
uploadIntentConfiguration.UploadUrlExpiresInSeconds,
items);
}
private static IReadOnlyList<AudioUploadSpec> ResolveAudios(RequestTrackUploadUrlsCommand request)
{
if (request.Audios is { Count: > 0 } audios)
return audios;
return request.AudioFileType != null && request.AudioContentType != null
? [new AudioUploadSpec(request.AudioFileType, request.AudioContentType, request.ExpectedAudioSizeBytes)]
: [];
}
}
}
@@ -0,0 +1,6 @@
namespace Musify.Application.Tracks.Responses
{
public record DeleteTracksResponse(
IReadOnlyList<Guid> DeletedTrackIds,
IReadOnlyList<Guid> FailedTrackIds);
}
@@ -0,0 +1,6 @@
namespace Musify.Application.Tracks.Responses
{
public record SetTracksPublishedResponse(
IReadOnlyList<Guid> UpdatedTrackIds,
IReadOnlyList<Guid> SkippedTrackIds);
}
@@ -14,7 +14,8 @@ namespace Musify.Application.Tracks.Responses
DateTime UpdatedAt,
long OwnerUserId,
IReadOnlyCollection<Genre> Tags,
bool IsExplicit)
bool IsExplicit,
bool IsPublished)
{
public static TrackApplicationResponse FromEntity(Track track, int listensCount) =>
new(
@@ -28,6 +29,7 @@ namespace Musify.Application.Tracks.Responses
track.UpdatedAt,
track.OwnerUserId,
track.Tags.Select(tag => tag.Tag).ToList(),
track.IsExplicit);
track.IsExplicit,
track.IsPublished);
}
}
@@ -8,6 +8,12 @@ namespace Musify.Application.Tracks.Responses
public static IQueryable<Track> Active(this IQueryable<Track> query) =>
query.Where(track => track.LifeCycleStatus == LifeCycleStatus.Active);
public static IQueryable<Track> WherePublished(this IQueryable<Track> query) =>
query.Where(track => track.IsPublished);
public static IQueryable<Track> VisibleTo(this IQueryable<Track> query, long? viewerId) =>
query.Where(track => track.IsPublished || track.OwnerUserId == viewerId);
public static IQueryable<TrackApplicationResponse> SelectResponse(this IQueryable<Track> query) =>
query.Select(track => new TrackApplicationResponse(
track.Id,
@@ -20,6 +26,28 @@ namespace Musify.Application.Tracks.Responses
track.UpdatedAt,
track.OwnerUserId,
track.Tags.Select(tag => tag.Tag).ToList(),
track.IsExplicit));
track.IsExplicit,
track.IsPublished));
public static IQueryable<UserTrackApplicationResponse> SelectUserResponse(this IQueryable<Track> query) =>
query.Select(track => new UserTrackApplicationResponse(
track.Id,
track.Title,
track.Owner.Name,
track.Audio.TranscodeStatus,
track.DurationSeconds,
track.ListeningHistories.Count(listen => listen.IsCounted),
track.CreatedAt,
track.UpdatedAt,
track.OwnerUserId,
track.Tags.Select(tag => tag.Tag).ToList(),
track.IsExplicit,
track.IsPublished,
track.AlbumTracks
.Where(albumTrack => albumTrack.Album.LifeCycleStatus == LifeCycleStatus.Active)
.OrderBy(albumTrack => albumTrack.AddedAt)
.ThenBy(albumTrack => albumTrack.AlbumId)
.Select(albumTrack => new TrackAlbumReference(albumTrack.AlbumId, albumTrack.Album.Title))
.ToList()));
}
}
@@ -0,0 +1,11 @@
namespace Musify.Application.Tracks.Responses
{
public record TrackStatusCountsResponse(
int Total,
int Pending,
int Processing,
int Completed,
int Failed,
int Published,
int Unpublished);
}
@@ -1,16 +1,25 @@
namespace Musify.Application.Tracks.Responses
{
public record TrackAudioUpload(
Guid IntentId,
Guid? PictureIntentId,
string Key,
string Name,
string ContentType,
string UploadUrl);
public record TrackUploadUrlsResponse(
Guid PictureIntentId,
Guid? PictureIntentId,
Guid AudioIntentId,
string Bucket,
string PictureKey,
string PictureName,
string PictureContentType,
string PictureUploadUrl,
string? PictureKey,
string? PictureName,
string? PictureContentType,
string? PictureUploadUrl,
string AudioKey,
string AudioName,
string AudioContentType,
string AudioUploadUrl,
int ExpiresInSeconds);
int ExpiresInSeconds,
IReadOnlyList<TrackAudioUpload> Audios);
}
@@ -0,0 +1,21 @@
using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks.Responses
{
public record TrackAlbumReference(Guid Id, string Title);
public record UserTrackApplicationResponse(
Guid Id,
string Title,
string? Artist,
ProcessingStatus AudioStatus,
double Duration,
int ListensCount,
DateTime CreatedAt,
DateTime UpdatedAt,
long OwnerUserId,
IReadOnlyCollection<Genre> Tags,
bool IsExplicit,
bool IsPublished,
IReadOnlyList<TrackAlbumReference> Albums);
}
@@ -0,0 +1,38 @@
using ErrorOr;
using Mediator;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Application.Shared;
namespace Musify.Application.Tracks
{
public record SetTrackPublishedCommand(long UserId, Guid TrackId, bool IsPublished)
: ICommand<ErrorOr<Success>>;
public class SetTrackPublishedCommandHandler(
IDatabase database,
ILogger<SetTrackPublishedCommandHandler> logger)
: ICommandHandler<SetTrackPublishedCommand, ErrorOr<Success>>
{
public async ValueTask<ErrorOr<Success>> Handle(SetTrackPublishedCommand request, CancellationToken cancellationToken)
{
var found = await database.Tracks.FindOwnedAsync(request.TrackId, request.UserId, cancellationToken);
if (found.IsError)
return found.Errors;
var track = found.Value;
if (request.IsPublished && !track.Audio.IsProcessed)
return Error.Validation("Track.NotProcessed", "Only tracks whose audio finished processing can be published.");
if (track.IsPublished == request.IsPublished)
return Result.Success;
track.IsPublished = request.IsPublished;
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("{Action} track {TrackId}", request.IsPublished ? "Published" : "Unpublished", track.Id);
return Result.Success;
}
}
}
@@ -0,0 +1,58 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Application.Shared;
using Musify.Application.Tracks.Responses;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
public record SetTracksPublishedCommand(long UserId, IReadOnlyList<Guid> TrackIds, bool IsPublished)
: ICommand<ErrorOr<SetTracksPublishedResponse>>;
public class SetTracksPublishedCommandHandler(
IDatabase database,
ILogger<SetTracksPublishedCommandHandler> logger)
: ICommandHandler<SetTracksPublishedCommand, ErrorOr<SetTracksPublishedResponse>>
{
public async ValueTask<ErrorOr<SetTracksPublishedResponse>> Handle(SetTracksPublishedCommand request, CancellationToken cancellationToken)
{
var requestedIds = request.TrackIds.Distinct().ToList();
var tracks = await database.Tracks
.Where(track => requestedIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
.ToListAsync(cancellationToken);
var foreign = tracks.FirstOrDefault(track => track.OwnerUserId != request.UserId);
if (foreign != null)
return AppErrors.Forbidden("Track", foreign.Id);
var updated = new List<Guid>();
var skipped = new List<Guid>();
foreach (var trackId in requestedIds)
{
var track = tracks.SingleOrDefault(candidate => candidate.Id == trackId);
if (track == null || (request.IsPublished && !track.Audio.IsProcessed))
{
skipped.Add(trackId);
continue;
}
track.IsPublished = request.IsPublished;
updated.Add(trackId);
}
if (updated.Count > 0)
{
await database.SaveChangesAsync(cancellationToken);
logger.LogInformation("{Action} {Count} tracks of user {UserId}",
request.IsPublished ? "Published" : "Unpublished", updated.Count, request.UserId);
}
return new SetTracksPublishedResponse(updated, skipped);
}
}
}
@@ -13,7 +13,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.Tracks
{
/// <summary>Starts a listen: records it for signed-in users and issues the stream ticket.</summary>
public record StartListeningCommand(Guid TrackId, long? UserId)
: ICommand<ErrorOr<TrackStreamResponse>>;
@@ -31,6 +30,7 @@ namespace Musify.Application.Tracks
var track = await database.Tracks.AsNoTracking()
.Where(t => t.Id == request.TrackId && t.LifeCycleStatus == LifeCycleStatus.Active)
.VisibleTo(request.UserId)
.Select(t => new { t.Id, t.Audio })
.SingleOrDefaultAsync(cancellationToken);
@@ -5,7 +5,6 @@ using Musify.Application.Contracts;
namespace Musify.Application.UploadIntents
{
/// <summary>Deletes temporary upload objects that nobody claimed within the retention window.</summary>
public record DeleteStaleTempUploadsCommand : ICommand<int>;
public class DeleteStaleTempUploadsCommandHandler(
@@ -7,7 +7,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Application.UploadIntents
{
/// <summary>Marks overdue upload intents as expired and deletes the ones expired for longer than the retention window.</summary>
public record ExpireUploadIntentsCommand : ICommand<int>;
public class ExpireUploadIntentsCommandHandler(
@@ -38,7 +38,6 @@ namespace Musify.Application.Users
FollowedId = request.FollowedId
}, cancellationToken);
// A concurrent double click can hit the unique index; already following is a successful no-op.
var saved = await database.TrySaveChangesAsync(
AppErrors.Conflict("UserFollow.Duplicate", "Already following this user."), cancellationToken);
if (saved.IsError)
@@ -22,6 +22,8 @@ namespace Musify.Domain.Entities
public int? ReleaseYear { get; set; }
public AlbumType Type { get; set; }
public EntityPictures? Pictures { get; set; }
public required long OwnerUserId { get; set; }
@@ -28,6 +28,8 @@ namespace Musify.Domain.Entities
public bool IsExplicit { get; set; }
public bool IsPublished { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
@@ -0,0 +1,12 @@
using System.Diagnostics.CodeAnalysis;
namespace Musify.Domain.ValueObjects
{
public enum AlbumType
{
Album = 0,
EP = 1,
[SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "Part of the public API contract.")]
Single = 2
}
}
@@ -2,7 +2,6 @@ using System.ComponentModel.DataAnnotations;
namespace Musify.Domain.ValueObjects
{
/// <summary>The picture file names of an album or playlist. Resized names stay null until processing finishes.</summary>
public class EntityPictures
{
[Required]
@@ -2,31 +2,32 @@ namespace Musify.Domain.ValueObjects
{
public enum Genre
{
Pop = 0,
Rock = 1,
HipHop = 2,
RnB = 3,
Jazz = 4,
Blues = 5,
Classical = 6,
Electronic = 7,
House = 8,
Techno = 9,
Trance = 10,
Dubstep = 11,
DrumAndBass = 12,
Metal = 13,
Punk = 14,
Reggae = 15,
Reggaeton = 16,
Country = 17,
Folk = 18,
Indie = 19,
KPop = 20,
Latin = 21,
Soul = 22,
Funk = 23,
Ambient = 24,
Lofi = 25
None = 0,
Pop = 1,
Rock = 2,
HipHop = 3,
RnB = 4,
Jazz = 5,
Blues = 6,
Classical = 7,
Electronic = 8,
House = 9,
Techno = 10,
Trance = 11,
Dubstep = 12,
DrumAndBass = 13,
Metal = 14,
Punk = 15,
Reggae = 16,
Reggaeton = 17,
Country = 18,
Folk = 19,
Indie = 20,
KPop = 21,
Latin = 22,
Soul = 23,
Funk = 24,
Ambient = 25,
Lofi = 26
}
}
@@ -4,7 +4,6 @@ using Musify.Application.Configuration;
namespace Musify.Infrastructure.Jobs
{
/// <summary>Registers every recurring Hangfire job when the host starts.</summary>
public sealed class RecurringJobsRegistrar(
IRecurringJobManager recurringJobManager,
UploadIntentConfiguration uploadIntentConfiguration)
@@ -30,7 +29,6 @@ namespace Musify.Infrastructure.Jobs
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Hangfire cron has a one-minute resolution, so the interval is rounded up to whole minutes.</summary>
internal static string EveryCron(int intervalSeconds)
{
var minutes = Math.Max(1, (int)Math.Ceiling(intervalSeconds / 60.0));
@@ -5,7 +5,6 @@ using Musify.Domain.ValueObjects;
namespace Musify.Infrastructure.MassTransit.Activities.Audio
{
/// <summary>Shared bookkeeping of the audio processing activities.</summary>
internal static class TrackAudioStatus
{
public static async Task<Track> LoadAsync(IDatabase database, Guid trackId, CancellationToken cancellationToken) =>
@@ -8,7 +8,6 @@ using Musify.Infrastructure.MassTransit.Arguments;
namespace Musify.Infrastructure.MassTransit.Activities.LifeCycle
{
/// <summary>Sets the life-cycle status of an entity (removing, failed, ...). A missing entity is skipped.</summary>
internal abstract class MarkLifeCycleActivity<TEntity>(IDatabase database, ILogger logger)
: IExecuteActivity<MarkLifeCycleArguments>
where TEntity : class, IHasLifeCycle
@@ -33,7 +32,6 @@ namespace Musify.Infrastructure.MassTransit.Activities.LifeCycle
}
}
/// <summary>Deletes an entity row. A missing entity is skipped.</summary>
internal abstract class DeleteEntityActivity<TEntity>(IDatabase database, ILogger logger)
: IExecuteActivity<DeleteEntityArguments>
where TEntity : class, IHasLifeCycle
@@ -58,8 +56,6 @@ namespace Musify.Infrastructure.MassTransit.Activities.LifeCycle
}
}
// One concrete activity per entity keeps a separate queue for each of them:
// the endpoint name is the kebab-cased class name.
internal sealed class MarkTrackLifeCycleActivity(IDatabase database, ILogger<MarkTrackLifeCycleActivity> logger)
: MarkLifeCycleActivity<Track>(database, logger)
{
@@ -12,7 +12,6 @@ namespace Musify.Infrastructure.MassTransit.Activities.Pictures
{
internal sealed record PictureNames(string? Original, string? Small, string? Medium, string? Large);
/// <summary>Stores the processed picture names on the owner and reports it; compensation restores the previous names.</summary>
internal abstract class UpdatePicturesActivity<TEntity>(
IDatabase database,
IPublishEndpoint publishEndpoint,
@@ -24,7 +23,6 @@ namespace Musify.Infrastructure.MassTransit.Activities.Pictures
protected abstract Task<TEntity?> FindAsync(Guid id, CancellationToken cancellationToken);
/// <summary>Reads the current names; throws when the entity has no pending picture.</summary>
protected abstract PictureNames Read(TEntity entity);
protected abstract void Write(TEntity entity, PictureNames names, bool succeeded);
@@ -16,13 +16,16 @@ namespace Musify.Infrastructure.MassTransit.Activities.Tracks
{
var arguments = executeContext.Arguments;
await publishEndpoint.Publish(
new UpdateTrackPictureEvent(
arguments.TrackId,
arguments.Bucket,
arguments.FinalPictureKey,
arguments.Sizes),
executeContext.CancellationToken);
if (arguments.FinalPictureKey != null)
{
await publishEndpoint.Publish(
new UpdateTrackPictureEvent(
arguments.TrackId,
arguments.Bucket,
arguments.FinalPictureKey,
arguments.Sizes),
executeContext.CancellationToken);
}
await publishEndpoint.Publish(
new UpdateTrackAudioEvent(
@@ -5,7 +5,7 @@ namespace Musify.Infrastructure.MassTransit.Arguments
public record PublishTrackProcessingEventsArguments(
Guid TrackId,
string Bucket,
string FinalPictureKey,
string? FinalPictureKey,
string FinalAudioKey,
string AudioDestinationFolderKey,
ImageSizes Sizes);
@@ -7,7 +7,6 @@ namespace Musify.Infrastructure.MassTransit.Consumers
{
internal static class ProcessingFailedCleanup
{
/// <summary>Removes whatever files were left behind and marks the entity as failed.</summary>
public static Task ExecuteAsync(
IBus bus,
Guid subjectId,
@@ -11,11 +11,21 @@ namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
{
public RoutingSlipBuilder Build(CreateTrackResourcesEvent message, Guid? correlationId)
{
var builder = RoutingSlips.Create(correlationId)
.AddStep(
var builder = RoutingSlips.Create(correlationId);
var hasPicture = message.PictureIntentId != null
&& message.PictureSourceKey != null
&& message.PictureDestinationKey != null;
if (hasPicture)
{
builder.AddStep(
ActivityNames.CopyPictureToFinal,
CopyFileInBucketActivity.ExecuteEndpointName,
new CopyFileInBucketArguments(message.Bucket, message.PictureSourceKey, message.Bucket, message.PictureDestinationKey))
new CopyFileInBucketArguments(message.Bucket, message.PictureSourceKey!, message.Bucket, message.PictureDestinationKey!));
}
builder
.AddStep(
ActivityNames.CopyAudioToFinal,
CopyFileInBucketActivity.ExecuteEndpointName,
@@ -23,21 +33,23 @@ namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
.AddStep(
ActivityNames.ConsumeUploadIntents,
ConsumeUploadIntentsActivity.ExecuteEndpointName,
new ConsumeUploadIntentsArguments([message.PictureIntentId, message.AudioIntentId]))
new ConsumeUploadIntentsArguments(
hasPicture ? [message.PictureIntentId!.Value, message.AudioIntentId] : [message.AudioIntentId]))
.AddStep(
ActivityNames.PublishTrackProcessingEvents,
PublishTrackProcessingEventsActivity.ExecuteEndpointName,
new PublishTrackProcessingEventsArguments(
message.TrackId,
message.Bucket,
message.PictureDestinationKey,
hasPicture ? message.PictureDestinationKey : null,
message.AudioDestinationKey,
message.AudioProcessedFolderKey,
message.Sizes))
.TrackFaults(message.TrackId, RoutingSlipVariableNames.ProcessKinds.TrackCreation);
builder.AddVariable(RoutingSlipVariableNames.Workflow.Bucket, message.Bucket);
builder.AddVariable(RoutingSlipVariableNames.Workflow.PictureKey, message.PictureDestinationKey);
if (hasPicture)
builder.AddVariable(RoutingSlipVariableNames.Workflow.PictureKey, message.PictureDestinationKey!);
builder.AddVariable(RoutingSlipVariableNames.Workflow.AudioKey, message.AudioDestinationKey);
return builder;
@@ -8,7 +8,6 @@ using Musify.Infrastructure.MassTransit.Arguments;
namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
{
/// <summary>Marks an entity as removing, deletes its files from the bucket and finally deletes its row.</summary>
public class DeleteRoutingSlipBuilder(
IDatabase database,
TrackConfiguration trackConfiguration,
@@ -48,8 +47,7 @@ namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
routes.BuildOriginalPicturePath(userId, track.Pictures.OriginalName));
}
// Unprocessed tracks still point at the shared preset pictures, which must never be deleted.
if (track.Pictures.IsProcessed)
if (track.Pictures.IsProcessed && !string.IsNullOrEmpty(track.Pictures.OriginalName))
{
builder.AddRemoveFile(ActivityNames.RemoveTrackSmallPicture, bucket, routes.BuildPicturePath(PictureSize.Small, track.Pictures.SmallName));
builder.AddRemoveFile(ActivityNames.RemoveTrackMediumPicture, bucket, routes.BuildPicturePath(PictureSize.Medium, track.Pictures.MediumName));
@@ -8,10 +8,6 @@ using Musify.Infrastructure.MassTransit.Arguments;
namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
{
/// <summary>
/// Moves an uploaded album/playlist picture to its final key, consumes the upload intent and hands over to the picture workflow.
/// Creation faults mark the whole entity as failed; update faults only report the picture as failed.
/// </summary>
public class PictureSourceRoutingSlipBuilder
{
public RoutingSlipBuilder Build(CreateAlbumResourcesEvent message, Guid? correlationId) =>
@@ -8,7 +8,6 @@ using Musify.Infrastructure.MassTransit.Arguments;
namespace Musify.Infrastructure.MassTransit.RoutingSlip.Builders
{
/// <summary>Downloads a picture, resizes it to the three sizes, uploads them and records the result on the owner.</summary>
public class PictureWorkflowRoutingSlipBuilder(WorkerConfiguration workerConfiguration)
{
public RoutingSlipBuilder Build(UpdateTrackPictureEvent message, Guid? correlationId) =>
@@ -6,14 +6,12 @@ using Musify.Infrastructure.MassTransit.Consumers;
namespace Musify.Infrastructure.MassTransit.RoutingSlip
{
/// <summary>Shared building blocks for every routing slip in the worker.</summary>
internal static class RoutingSlips
{
public static Uri ExecuteUri(string endpointName) => new($"queue:{endpointName}_execute");
public static Uri ConsumerUri(string queueName) => new($"queue:{queueName}");
/// <summary>A new slip that carries the correlation id and always cleans its temporary directory up.</summary>
public static RoutingSlipBuilder Create(Guid? correlationId)
{
var builder = new RoutingSlipBuilder(NewId.NextGuid());
@@ -32,7 +30,6 @@ namespace Musify.Infrastructure.MassTransit.RoutingSlip
return builder;
}
/// <summary>Publishes a failure event for the subject when the slip faults.</summary>
public static RoutingSlipBuilder TrackFaults(
this RoutingSlipBuilder builder, Guid subjectId, string processKind)
{
@@ -48,6 +48,7 @@ namespace Musify.Infrastructure.MassTransit.Sagas
context.Saga.UpdatedAt = DateTime.UtcNow;
context.Saga.Bucket = context.Message.Bucket;
context.Saga.PictureKey = context.Message.PictureDestinationKey;
context.Saga.PictureProcessed = context.Message.PictureDestinationKey == null;
context.Saga.AudioKey = context.Message.AudioDestinationKey;
})
.TransitionTo(Processing));
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,26 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class GenreNone : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("Npgsql:Enum:genre", "ambient,blues,classical,country,drum_and_bass,dubstep,electronic,folk,funk,hip_hop,house,indie,jazz,k_pop,latin,lofi,metal,none,pop,punk,reggae,reggaeton,rn_b,rock,soul,techno,trance")
.OldAnnotation("Npgsql:Enum:genre", "ambient,blues,classical,country,drum_and_bass,dubstep,electronic,folk,funk,hip_hop,house,indie,jazz,k_pop,latin,lofi,metal,pop,punk,reggae,reggaeton,rn_b,rock,soul,techno,trance");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("Npgsql:Enum:genre", "ambient,blues,classical,country,drum_and_bass,dubstep,electronic,folk,funk,hip_hop,house,indie,jazz,k_pop,latin,lofi,metal,pop,punk,reggae,reggaeton,rn_b,rock,soul,techno,trance")
.OldAnnotation("Npgsql:Enum:genre", "ambient,blues,classical,country,drum_and_bass,dubstep,electronic,folk,funk,hip_hop,house,indie,jazz,k_pop,latin,lofi,metal,none,pop,punk,reggae,reggaeton,rn_b,rock,soul,techno,trance");
}
}
}
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class TrackPublicationAndAlbumType : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsPublished",
table: "Tracks",
type: "boolean",
nullable: false,
defaultValue: false);
migrationBuilder.Sql("UPDATE \"Tracks\" SET \"IsPublished\" = TRUE;");
migrationBuilder.AddColumn<int>(
name: "Type",
table: "Albums",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsPublished",
table: "Tracks");
migrationBuilder.DropColumn(
name: "Type",
table: "Albums");
}
}
}
@@ -21,7 +21,7 @@ namespace Musify.Infrastructure.Persistence.Migrations
.HasAnnotation("ProductVersion", "10.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "genre", new[] { "ambient", "blues", "classical", "country", "drum_and_bass", "dubstep", "electronic", "folk", "funk", "hip_hop", "house", "indie", "jazz", "k_pop", "latin", "lofi", "metal", "pop", "punk", "reggae", "reggaeton", "rn_b", "rock", "soul", "techno", "trance" });
NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "genre", new[] { "ambient", "blues", "classical", "country", "drum_and_bass", "dubstep", "electronic", "folk", "funk", "hip_hop", "house", "indie", "jazz", "k_pop", "latin", "lofi", "metal", "none", "pop", "punk", "reggae", "reggaeton", "rn_b", "rock", "soul", "techno", "trance" });
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MassTransit.EntityFrameworkCoreIntegration.InboxState", b =>
@@ -224,6 +224,9 @@ namespace Musify.Infrastructure.Persistence.Migrations
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("Type")
.HasColumnType("integer");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -435,6 +438,9 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Property<bool>("IsExplicit")
.HasColumnType("boolean");
b.Property<bool>("IsPublished")
.HasColumnType("boolean");
b.Property<int>("LifeCycleStatus")
.HasColumnType("integer");
@@ -5,9 +5,6 @@ using Musify.Infrastructure.MassTransit.Sagas;
namespace Musify.Infrastructure.Persistence
{
/// <summary>
/// Entity model shared by <see cref="Database"/> and the in-memory test database, so both always agree.
/// </summary>
public static class ModelConfiguration
{
public static void Apply(ModelBuilder modelBuilder)
@@ -1,8 +1,12 @@
using Musify.Domain.ValueObjects;
namespace Musify.Api.DataTransferObjects.Albums
{
public record CreateAlbumRequest(
string Title,
string? Description,
int? ReleaseYear,
Guid PictureIntentId);
Guid PictureIntentId,
AlbumType Type = AlbumType.Album,
IReadOnlyList<Guid>? TrackIds = null);
}
@@ -0,0 +1,4 @@
namespace Musify.Api.DataTransferObjects.Albums
{
public record UpdateAlbumPictureRequest(Guid PictureIntentId);
}
@@ -1,8 +1,10 @@
using Musify.Domain.ValueObjects;
namespace Musify.Api.DataTransferObjects.Albums
{
public record UpdateAlbumRequest(
string Title,
string? Description,
int? ReleaseYear,
Guid? PictureIntentId);
AlbumType? Type = null);
}
@@ -0,0 +1,4 @@
namespace Musify.Api.DataTransferObjects.PlayLists
{
public record UpdatePlayListPictureRequest(Guid PictureIntentId);
}
@@ -3,8 +3,7 @@ using Musify.Domain.ValueObjects;
namespace Musify.Api.DataTransferObjects.PlayLists
{
public record UpdatePlayListRequest(
string? Name,
string Name,
string? Description,
Guid? PictureIntentId,
PlayListVisibility? Visibility = null);
PlayListVisibility? Visibility);
}
@@ -4,7 +4,7 @@ namespace Musify.Api.DataTransferObjects.Tracks
{
public record CreateTrackRequest(
string Title,
Guid PictureIntentId,
Guid? PictureIntentId,
Guid AudioIntentId,
IReadOnlyCollection<Genre> Tags,
bool IsExplicit = false);
@@ -0,0 +1,4 @@
namespace Musify.Api.DataTransferObjects.Tracks
{
public record DeleteTracksRequest(IReadOnlyList<Guid> TrackIds);
}
@@ -1,10 +1,16 @@
namespace Musify.Api.DataTransferObjects.Tracks
{
public record AudioUploadRequest(
string FileType,
string ContentType,
long? ExpectedSizeBytes = null);
public record RequestTrackUploadUrlsRequest(
string PictureFileType,
string PictureContentType,
string AudioFileType,
string AudioContentType,
string? PictureFileType = null,
string? PictureContentType = null,
string? AudioFileType = null,
string? AudioContentType = null,
long? ExpectedPictureSizeBytes = null,
long? ExpectedAudioSizeBytes = null);
long? ExpectedAudioSizeBytes = null,
IReadOnlyList<AudioUploadRequest>? Audios = null);
}
@@ -0,0 +1,4 @@
namespace Musify.Api.DataTransferObjects.Tracks
{
public record SetTrackPublishedRequest(bool IsPublished);
}
@@ -0,0 +1,4 @@
namespace Musify.Api.DataTransferObjects.Tracks
{
public record SetTracksPublishedRequest(IReadOnlyList<Guid> TrackIds, bool IsPublished);
}
@@ -57,6 +57,15 @@ namespace Musify.Api.Endpoints
.Produces<PaginatedResponse<TrackApplicationResponse>>()
.Produces(StatusCodes.Status404NotFound);
group.MapGet("/{id:guid}/tracks/ids", GetAlbumTrackIds)
.WithName("GetAlbumTrackIds")
.WithSummary("Get the ids of every track in one of your albums, ordered by track number")
.RequireAuthorization()
.Produces<AlbumTrackIdsResponse>()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapGet("/{id:guid}/cover", GetAlbumCover)
.WithName("GetAlbumCover")
.WithSummary("Get an album cover image")
@@ -75,12 +84,13 @@ namespace Musify.Api.Endpoints
group.MapPost("/", CreateAlbum)
.WithName("CreateAlbum")
.WithSummary("Create a new album")
.WithSummary("Create a new album, optionally with some of your tracks already in it")
.AddEndpointFilter<ValidationFilter<CreateAlbumRequest>>()
.RequireAuthorization()
.Produces<AlbumApplicationResponse>(StatusCodes.Status201Created)
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapPut("/{id:guid}", UpdateAlbum)
@@ -94,6 +104,17 @@ namespace Musify.Api.Endpoints
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapPut("/{id:guid}/picture", UpdateAlbumPicture)
.WithName("UpdateAlbumPicture")
.WithSummary("Replace an album picture with an uploaded image")
.AddEndpointFilter<ValidationFilter<UpdateAlbumPictureRequest>>()
.RequireAuthorization()
.Produces<AlbumApplicationResponse>()
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapDelete("/{id:guid}", DeleteAlbum)
.WithName("DeleteAlbum")
.WithSummary("Delete an album")
@@ -184,6 +205,16 @@ namespace Musify.Api.Endpoints
return result.ToHttpResult();
}
private static async Task<IResult> GetAlbumTrackIds(
IMediator mediator,
CurrentUser currentUser,
Guid id,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new GetAlbumTrackIdsQuery(currentUser.RequiredId, id), cancellationToken);
return result.ToHttpResult();
}
private static Task<IResult> GetAlbumCover(
IMediator mediator,
IStorageService storageService,
@@ -215,7 +246,8 @@ namespace Musify.Api.Endpoints
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new CreateAlbumCommand(currentUser.RequiredId, request.Title, request.Description, request.ReleaseYear, request.PictureIntentId),
new CreateAlbumCommand(
currentUser.RequiredId, request.Title, request.Description, request.ReleaseYear, request.PictureIntentId, request.Type, request.TrackIds),
cancellationToken);
return result.ToCreatedResult(album => $"/albums/{album.Id}");
@@ -229,7 +261,21 @@ namespace Musify.Api.Endpoints
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new UpdateAlbumCommand(currentUser.RequiredId, id, request.Title, request.Description, request.ReleaseYear, request.PictureIntentId),
new UpdateAlbumCommand(currentUser.RequiredId, id, request.Title, request.Description, request.ReleaseYear, request.Type),
cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> UpdateAlbumPicture(
IMediator mediator,
CurrentUser currentUser,
Guid id,
UpdateAlbumPictureRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new UpdateAlbumPictureCommand(currentUser.RequiredId, id, request.PictureIntentId),
cancellationToken);
return result.ToHttpResult();
@@ -68,6 +68,17 @@ namespace Musify.Api.Endpoints
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapPut("/{id:guid}/picture", UpdatePlayListPicture)
.WithName("UpdatePlayListPicture")
.WithSummary("Replace a playlist picture with an uploaded image")
.AddEndpointFilter<ValidationFilter<UpdatePlayListPictureRequest>>()
.RequireAuthorization()
.Produces<PlayListApplicationResponse>()
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapDelete("/{id:guid}", DeletePlayList)
.WithName("DeletePlayList")
.WithSummary("Delete a playlist")
@@ -99,6 +110,15 @@ namespace Musify.Api.Endpoints
.Produces(StatusCodes.Status404NotFound)
.Produces(StatusCodes.Status409Conflict);
group.MapPost("/{id:guid}/albums/{albumId:guid}", AddAlbumToPlayList)
.WithName("AddAlbumToPlayList")
.WithSummary("Add all the tracks of an album to a playlist, skipping the ones it already has")
.RequireAuthorization()
.Produces<AddAlbumToPlayListResponse>()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapDelete("/{id:guid}/tracks/{trackId:guid}", RemoveTrackFromPlayList)
.WithName("RemoveTrackFromPlayList")
.WithSummary("Remove a track from a playlist")
@@ -176,7 +196,21 @@ namespace Musify.Api.Endpoints
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new UpdatePlayListCommand(currentUser.RequiredId, id, request.Name, request.Description, request.PictureIntentId, request.Visibility),
new UpdatePlayListCommand(currentUser.RequiredId, id, request.Name, request.Description, request.Visibility!.Value),
cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> UpdatePlayListPicture(
IMediator mediator,
CurrentUser currentUser,
Guid id,
UpdatePlayListPictureRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new UpdatePlayListPictureCommand(currentUser.RequiredId, id, request.PictureIntentId),
cancellationToken);
return result.ToHttpResult();
@@ -219,6 +253,20 @@ namespace Musify.Api.Endpoints
return result.ToHttpResult();
}
private static async Task<IResult> AddAlbumToPlayList(
IMediator mediator,
CurrentUser currentUser,
Guid id,
Guid albumId,
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new AddAlbumToPlayListCommand(currentUser.RequiredId, id, albumId),
cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> RemoveTrackFromPlayList(
IMediator mediator,
CurrentUser currentUser,
@@ -1,4 +1,5 @@
using Mediator;
using Microsoft.AspNetCore.Mvc;
using Musify.Api.Authentication;
using Musify.Api.DataTransferObjects.Tracks;
using Musify.Api.Extensions;
@@ -9,6 +10,7 @@ using Musify.Application.Pictures;
using Musify.Application.Shared;
using Musify.Application.Tracks;
using Musify.Application.Tracks.Responses;
using Musify.Domain.ValueObjects;
namespace Musify.Api.Endpoints
{
@@ -57,12 +59,20 @@ namespace Musify.Api.Endpoints
group.MapGet("/users/{userId:long}", GetTracksByUserId)
.AddEndpointFilter<ValidationFilter<PageQuery>>()
.WithName("GetTracksByUserId")
.WithSummary("Get paginated tracks for a user")
.Produces<PaginatedResponse<TrackApplicationResponse>>();
.WithSummary("Get paginated tracks for a user, optionally filtered by name, audio processing status and published state. Each track lists the albums it belongs to. Only the owner sees unpublished tracks")
.Produces<PaginatedResponse<UserTrackApplicationResponse>>();
group.MapGet("/users/{userId:long}/status-counts", GetTrackStatusCounts)
.WithName("GetTrackStatusCounts")
.WithSummary("Get how many of your tracks are in each audio processing status")
.RequireAuthorization()
.Produces<TrackStatusCountsResponse>()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden);
group.MapPost("/", CreateTrack)
.WithName("CreateTrack")
.WithSummary("Create a new track")
.WithSummary("Create a new track, unpublished, from upload intents. The picture is optional")
.AddEndpointFilter<ValidationFilter<CreateTrackRequest>>()
.RequireAuthorization()
.Produces<TrackApplicationResponse>(StatusCodes.Status201Created)
@@ -81,9 +91,39 @@ namespace Musify.Api.Endpoints
.Produces(StatusCodes.Status404NotFound)
.Produces(StatusCodes.Status409Conflict);
group.MapDelete("/", DeleteTracks)
.WithName("DeleteTracks")
.WithSummary("Delete several of your tracks at once. Tracks that are missing or still processing are returned as failed")
.AddEndpointFilter<ValidationFilter<DeleteTracksRequest>>()
.RequireAuthorization()
.Produces<DeleteTracksResponse>()
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden);
group.MapPut("/{id:guid}/published", SetTrackPublished)
.WithName("SetTrackPublished")
.WithSummary("Publish or unpublish one of your tracks. Only tracks with completed audio processing can be published")
.RequireAuthorization()
.Produces(StatusCodes.Status204NoContent)
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
group.MapPut("/published", SetTracksPublished)
.WithName("SetTracksPublished")
.WithSummary("Publish or unpublish several of your tracks at once. Missing tracks and tracks that cannot be published yet are returned as skipped")
.AddEndpointFilter<ValidationFilter<SetTracksPublishedRequest>>()
.RequireAuthorization()
.Produces<SetTracksPublishedResponse>()
.ProducesValidationProblem()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status403Forbidden);
group.MapPost("/upload-urls", RequestTrackUploadUrls)
.WithName("RequestTrackUploadUrls")
.WithSummary("Request pre-signed URLs to upload track picture and audio")
.WithSummary("Request pre-signed URLs to upload the audio of one or many tracks and an optional picture shared by all of them")
.AddEndpointFilter<ValidationFilter<RequestTrackUploadUrlsRequest>>()
.RequireAuthorization()
.Produces<TrackUploadUrlsResponse>()
@@ -108,10 +148,11 @@ namespace Musify.Api.Endpoints
private static async Task<IResult> GetTrackById(
IMediator mediator,
CurrentUser currentUser,
Guid id,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new GetTrackByIdQuery(id), cancellationToken);
var result = await mediator.Send(new GetTrackByIdQuery(id, currentUser.Id), cancellationToken);
return result.ToHttpResult();
}
@@ -151,12 +192,63 @@ namespace Musify.Api.Endpoints
private static async Task<IResult> GetTracksByUserId(
IMediator mediator,
CurrentUser currentUser,
long userId,
string? name,
[AsParameters] PageQuery page,
CancellationToken cancellationToken,
ProcessingStatus[]? status = null,
bool? published = null)
{
var result = await mediator.Send(
new GetTracksByUserIdQuery(userId, name, page.PageNumber, page.PageSize, status, currentUser.Id, published),
cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> SetTrackPublished(
IMediator mediator,
CurrentUser currentUser,
Guid id,
SetTrackPublishedRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new GetTracksByUserIdQuery(userId, name, page.PageNumber, page.PageSize), cancellationToken);
var result = await mediator.Send(new SetTrackPublishedCommand(currentUser.RequiredId, id, request.IsPublished), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> SetTracksPublished(
IMediator mediator,
CurrentUser currentUser,
SetTracksPublishedRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(
new SetTracksPublishedCommand(currentUser.RequiredId, request.TrackIds, request.IsPublished),
cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> GetTrackStatusCounts(
IMediator mediator,
CurrentUser currentUser,
long userId,
CancellationToken cancellationToken)
{
if (currentUser.RequiredId != userId)
return Results.Problem("You can only read the status counts of your own tracks.", statusCode: StatusCodes.Status403Forbidden);
var result = await mediator.Send(new GetTrackStatusCountsQuery(userId), cancellationToken);
return Results.Ok(result);
}
private static async Task<IResult> DeleteTracks(
IMediator mediator,
CurrentUser currentUser,
[FromBody] DeleteTracksRequest request,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new DeleteTracksCommand(currentUser.RequiredId, request.TrackIds), cancellationToken);
return result.ToHttpResult();
}
@@ -197,7 +289,8 @@ namespace Musify.Api.Endpoints
request.AudioFileType,
request.AudioContentType,
request.ExpectedPictureSizeBytes,
request.ExpectedAudioSizeBytes),
request.ExpectedAudioSizeBytes,
request.Audios?.Select(audio => new AudioUploadSpec(audio.FileType, audio.ContentType, audio.ExpectedSizeBytes)).ToList()),
cancellationToken);
return result.ToHttpResult();
@@ -2,12 +2,11 @@ using Musify.Domain.ValueObjects;
namespace Musify.Api.Models
{
/// <summary>Query-string binding for a genre name (case-insensitive); unknown names are rejected with a 400.</summary>
public readonly record struct GenreParameter(Genre Value)
{
public static bool TryParse(string? value, out GenreParameter result)
{
if (Enum.TryParse<Genre>(value, ignoreCase: true, out var genre) && Enum.IsDefined(genre))
if (Enum.TryParse<Genre>(value, ignoreCase: true, out var genre) && genre != Genre.None && Enum.IsDefined(genre))
{
result = new GenreParameter(genre);
return true;
@@ -1,9 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using Musify.Application.Shared;
namespace Musify.Api.Models
{
/// <summary>Query-string binding for <see cref="PageRequest"/>, keeping the camelCase parameter names of the API.</summary>
public record PageQuery(
[property: FromQuery(Name = "pageNumber")] int PageNumber = 1,
[property: FromQuery(Name = "pageSize")] int PageSize = 20);
@@ -40,8 +40,6 @@ namespace Musify.Api.OpenApi
options.AddSchemaTransformer((schema, context, _) =>
{
// Every long the API returns is a user id, serialized as a string (JS loses precision above 2^53).
// Request DTOs only carry byte sizes, which may be sent as numbers or strings.
if (context.JsonPropertyInfo is { } property
&& (property.PropertyType == typeof(long) || property.PropertyType == typeof(long?)))
{
@@ -57,7 +55,6 @@ namespace Musify.Api.OpenApi
options.AddOperationTransformer((operation, context, _) =>
{
// Route parameters constrained with :long are user ids, which travel as strings like every other long.
foreach (var parameter in operation.Parameters?.OfType<OpenApiParameter>() ?? [])
{
if (parameter.Schema is OpenApiSchema { Type: JsonSchemaType.Integer, Format: "int64" } schema)
@@ -5,6 +5,8 @@ namespace Musify.Api.Validators.Albums
{
public sealed class CreateAlbumRequestValidator : AbstractValidator<CreateAlbumRequest>
{
public const int MaxTracksOnCreate = 500;
public CreateAlbumRequestValidator()
{
RuleFor(x => x.Title)
@@ -20,6 +22,18 @@ namespace Musify.Api.Validators.Albums
RuleFor(x => x.PictureIntentId)
.NotEmpty();
RuleFor(x => x.Type)
.IsInEnum();
RuleFor(x => x.TrackIds)
.Must(ids => ids!.Count <= MaxTracksOnCreate)
.WithMessage($"At most {MaxTracksOnCreate} tracks can be added at once.")
.When(x => x.TrackIds != null);
RuleForEach(x => x.TrackIds)
.NotEmpty()
.When(x => x.TrackIds != null);
}
}
}
@@ -0,0 +1,14 @@
using FluentValidation;
using Musify.Api.DataTransferObjects.Albums;
namespace Musify.Api.Validators.Albums
{
public sealed class UpdateAlbumPictureRequestValidator : AbstractValidator<UpdateAlbumPictureRequest>
{
public UpdateAlbumPictureRequestValidator()
{
RuleFor(x => x.PictureIntentId)
.NotEmpty();
}
}
}

Some files were not shown because too many files have changed in this diff Show More