Compare commits
155
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e85af2b3b | ||
|
|
2d23eb87c6 | ||
|
|
e5ce63a192 | ||
|
|
b5c9658d65 | ||
|
|
ba0a2373b5 | ||
|
|
b0163f6a4d | ||
|
|
0a192645d6 | ||
|
|
351b333529 | ||
|
|
155f0e2b6a | ||
|
|
a54d1ef077 | ||
|
|
2361b88e0a | ||
|
|
e7c2fd5571 | ||
|
|
3126cb6dd6 | ||
|
|
03afcc8a90 | ||
|
|
f210fa4702 | ||
|
|
4b708aa987 | ||
|
|
bd07b1134e | ||
|
|
c041daf649 | ||
|
|
975fa7e4fd | ||
|
|
1a2ae37f49 | ||
|
|
1cad36b929 | ||
|
|
8cb9386447 | ||
|
|
5cda7cb4c1 | ||
|
|
e89463fb83 | ||
|
|
b011ccdd5b | ||
|
|
1df7f6ccf6 | ||
|
|
2915737f03 | ||
|
|
5b2a0e4d46 | ||
|
|
37fc229bf6 | ||
|
|
bc43b4b6eb | ||
|
|
dda8c30d45 | ||
|
|
906f38140a | ||
|
|
3e546d4a1e | ||
|
|
b2f450dcf7 | ||
|
|
87c3f97529 | ||
|
|
302dd1e0f8 | ||
|
|
421fc929e8 | ||
|
|
c4ab5dc388 | ||
|
|
920dcc6779 | ||
|
|
430c711ff2 | ||
|
|
cfdc61a4b8 | ||
|
|
0f28e19c1d | ||
|
|
7316e355ee | ||
|
|
b39e55fd87 | ||
|
|
cb046bba9e | ||
|
|
b9a40186b1 | ||
|
|
fd0a39b879 | ||
|
|
cc7afe4326 | ||
|
|
72cbc18a48 | ||
|
|
84408b842b | ||
|
|
339fcb56ad | ||
|
|
74cf534be5 | ||
|
|
89820c1377 | ||
|
|
2fe26b15dd | ||
|
|
2cb560fda4 | ||
|
|
d8530b9209 | ||
|
|
5049b0ba91 | ||
|
|
1b98a75c0e | ||
|
|
cbbde95773 | ||
|
|
26bb8a50a3 | ||
|
|
bf19bb31f9 | ||
|
|
55cc803708 | ||
|
|
805e521b1d | ||
|
|
f8d431a0d7 | ||
|
|
7b72db8a24 | ||
|
|
b61ff1ebec | ||
|
|
8870c65c6f | ||
|
|
5df5e635f3 | ||
|
|
d5e3cadc43 | ||
|
|
505ae05c53 | ||
|
|
a7929c0ac9 | ||
|
|
4d39008eab | ||
|
|
5efd59826b | ||
|
|
8970f29410 | ||
|
|
523318fc06 | ||
|
|
ba531b4f61 | ||
|
|
3d51f08e0b | ||
|
|
2660c124d5 | ||
|
|
d7199b4d1d | ||
|
|
c60704080b | ||
|
|
1e3e46cfdc | ||
|
|
93d4220f3a | ||
|
|
8a748f2b3a | ||
|
|
2138a4a890 | ||
|
|
94a1981a4c | ||
|
|
2272a401bb | ||
|
|
3ab43a2ef6 | ||
|
|
79698f2265 | ||
|
|
94f80c03c5 | ||
|
|
d98d01ab20 | ||
|
|
6be5c43e6d | ||
|
|
8deb762a52 | ||
|
|
fe21c19810 | ||
|
|
6e86c3d2c5 | ||
|
|
aca4b73fac | ||
|
|
078f7ac6f6 | ||
|
|
b168df6ca6 | ||
|
|
8d178884d4 | ||
|
|
cd2131ef6f | ||
|
|
d6bff15f11 | ||
|
|
b82fca0bc2 | ||
|
|
4fbd4fa81d | ||
|
|
68b5709d88 | ||
|
|
434b2c1305 | ||
|
|
9064ef687c | ||
|
|
c93f3d352c | ||
|
|
a9bfcbbe2f | ||
|
|
717e939038 | ||
|
|
dd1cb8a5d1 | ||
|
|
7c9399a342 | ||
|
|
a3ec9d19d3 | ||
|
|
5f2b5bd5a2 | ||
|
|
3bb4e66ad0 | ||
|
|
fbb102ffbd | ||
|
|
76f7535ffa | ||
|
|
7fcf0645da | ||
|
|
50618865e7 | ||
|
|
fe2f6a785a | ||
|
|
53fc24d4bc | ||
|
|
ff5fa501af | ||
|
|
6e9883018a | ||
|
|
a985ff4fb3 | ||
|
|
63018a7c72 | ||
|
|
c5748e9765 | ||
|
|
23e30d96fc | ||
|
|
3f8d517ee3 | ||
|
|
2662abe460 | ||
|
|
1b6d7ecb42 | ||
|
|
b60a87adb5 | ||
|
|
5fa901c2e6 | ||
|
|
8975e43729 | ||
|
|
1bdd7ec9f1 | ||
|
|
964dfc809f | ||
|
|
8cea298b2a | ||
|
|
fb4a8ccc0e | ||
|
|
14ee1dc45d | ||
|
|
1320b12699 | ||
|
|
aa20e70671 | ||
|
|
a4ca1f32d3 | ||
|
|
58eb670fed | ||
|
|
7b1b81c45a | ||
|
|
ea9bf07126 | ||
|
|
11789e78fe | ||
|
|
96c75a32c8 | ||
|
|
a963e2c9af | ||
|
|
4251d292e1 | ||
|
|
3f5e01f910 | ||
|
|
c14db5a711 | ||
|
|
5ae9955bd0 | ||
|
|
31032bd8e8 | ||
|
|
5696683859 | ||
|
|
f1756468bc | ||
|
|
7861600081 | ||
|
|
dc1ba89a6d | ||
|
|
389b3b9244 |
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "musify-web",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["--prefix", "web-player", "run", "dev"],
|
||||
"port": 3000,
|
||||
"autoPort": true
|
||||
},
|
||||
{
|
||||
"name": "musify-api",
|
||||
"runtimeExecutable": "dotnet",
|
||||
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.Api"],
|
||||
"port": 5111
|
||||
},
|
||||
{
|
||||
"name": "musify-streaming-gateway",
|
||||
"runtimeExecutable": "dotnet",
|
||||
"runtimeArgs": ["run", "--project", "backend/Hosts/Musify.StreamingGateway"],
|
||||
"port": 8081
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
name: CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
pull_request:
|
||||
branches: ['**']
|
||||
|
||||
concurrency:
|
||||
group: production-deploy
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
backend-tests:
|
||||
name: BackEnd
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
defaults:
|
||||
run:
|
||||
working-directory: backend
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore Musify.slnx
|
||||
|
||||
- name: Build
|
||||
run: dotnet build Musify.slnx --no-restore -c Release
|
||||
|
||||
- name: Test
|
||||
run: dotnet test Musify.slnx --no-build -c Release
|
||||
|
||||
web-player-checks:
|
||||
name: WebPlayer
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
defaults:
|
||||
run:
|
||||
working-directory: web-player
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: web-player/package-lock.json
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Type-check
|
||||
run: npm run check
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
# Runs on the production host itself, through the existing self-hosted
|
||||
# Gitea Actions runner (act_runner), which also carries a "production"
|
||||
# label registered in native (non-docker) mode so its steps see the host's
|
||||
# real Docker daemon directly (Docker socket + a bind-mounted deploy
|
||||
# directory — see deploy/README.md for how that runner is set up).
|
||||
#
|
||||
# DEPLOY_PATH is the persistent clone already on that host (the one whose
|
||||
# deploy/.env.prod is filled in and matches SharedServices/.env.prod) —
|
||||
# deploy reuses it instead of a fresh checkout, since .env.prod is
|
||||
# untracked and only lives there.
|
||||
deploy:
|
||||
name: Deploy
|
||||
needs: [backend-tests, web-player-checks]
|
||||
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
|
||||
runs-on: [production]
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
DEPLOY_PATH: /home/ubuntu/deploys/musify
|
||||
COMPOSE: docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml
|
||||
steps:
|
||||
- name: Pull latest master
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git config --global --add safe.directory "$DEPLOY_PATH"
|
||||
cd "$DEPLOY_PATH"
|
||||
git fetch origin master
|
||||
git reset --hard origin/master
|
||||
|
||||
- name: Generate stream-ticket keys
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE run --rm --no-deps keys-init
|
||||
|
||||
# The migrations are baked into the migrator image, so it is rebuilt on
|
||||
# every deploy (plain `up` would reuse the stale image and re-apply the
|
||||
# old migrations). `run --rm` starts wait-for-postgres, blocks until the
|
||||
# migration finishes and propagates its exit code, so a failed migration
|
||||
# aborts the deploy before the new API is started against an old schema.
|
||||
- name: Migrate database
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE build migrate
|
||||
$COMPOSE run --rm migrate
|
||||
|
||||
# Both jobs verify themselves through the public auth./s3. URLs, served
|
||||
# by the shared edge nginx (Infrastructure's edge/), and are idempotent.
|
||||
- name: Create OIDC app and S3 bucket
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE up -d seaweedfs-init zitadel-init
|
||||
for job in musify-seaweedfs-init musify-zitadel-init; do
|
||||
code=$(docker wait "$job")
|
||||
if [ "$code" != "0" ]; then
|
||||
docker logs "$job"
|
||||
echo "$job exited with $code"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Build and start apps
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "$DEPLOY_PATH"
|
||||
$COMPOSE --profile apps up -d --build api worker gateway web-player
|
||||
+3
-1
@@ -7,6 +7,9 @@ obj/
|
||||
*.userosscache
|
||||
.vs/
|
||||
artifacts/
|
||||
TestResults/
|
||||
*.trx
|
||||
*.coverage
|
||||
|
||||
# Rider / VS
|
||||
.idea/
|
||||
@@ -25,5 +28,4 @@ Thumbs.db
|
||||
# Deploy secrets and runtime state
|
||||
deploy/keys/
|
||||
deploy/secrets/
|
||||
deploy/nginx/certs/
|
||||
deploy/zitadel/.output/
|
||||
|
||||
@@ -1,57 +1,55 @@
|
||||
# Musify
|
||||
|
||||
Music streaming platform: upload your own tracks (or import them from YouTube),
|
||||
process them asynchronously (audio transcoded to `.m4a`, thumbnails generated)
|
||||
and stream them without the bytes ever going through the API.
|
||||
A music streaming app. Upload your own tracks, organize them into playlists
|
||||
and albums, and stream them back with a web player built around your
|
||||
listening habits: auto-generated mixes, a home feed, search, likes, and an
|
||||
Explore page for finding something new.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Upload and organize your own music**: tracks, albums, cover art, artist credits.
|
||||
- **Playlists**, likes, and a "recently played" history.
|
||||
- **Mixes**, playlists generated automatically from what you actually listen to.
|
||||
- **Explore**, genre browsing and search across tracks, albums, playlists and people.
|
||||
- **Real streaming**, not just file downloads: seek, queue, shuffle, repeat.
|
||||
- **Accounts via OIDC login**, with an optional anonymous listening mode.
|
||||
- Light and dark themes, and a layout that works on both desktop and mobile.
|
||||
|
||||
## How it's built
|
||||
|
||||
**Backend**: .NET 10, split into a REST API, a background worker, and a
|
||||
dedicated streaming gateway.
|
||||
- Clean architecture (Domain / Application / Infrastructure) with CQRS (Mediator) and `ErrorOr` results.
|
||||
- PostgreSQL via EF Core for metadata. RabbitMQ and MassTransit handle async processing (audio transcoding, thumbnails) with saga-based rollback.
|
||||
- SeaweedFS (S3-compatible) for file storage. Uploads and downloads go straight between the client and storage, never through the API.
|
||||
- ffmpeg for audio transcoding, ImageSharp for thumbnails.
|
||||
- A YARP reverse proxy that streams the audio and checks a signed, short-lived ticket on every request.
|
||||
- Zitadel for login (OIDC/OAuth2).
|
||||
|
||||
**Web client**: SvelteKit 2 on Svelte 5 (runes), TypeScript, Tailwind 4.
|
||||
The session lives on the server, so the backend access token never reaches the browser.
|
||||
|
||||
**Infrastructure**: Musify's own apps run from Docker Compose (dev and
|
||||
production overlays). Postgres, RabbitMQ, SeaweedFS, Zitadel and Jaeger are
|
||||
shared infrastructure that lives in a separate `Infrastructure` git
|
||||
repository, used by Musify and by other projects that need the same OIDC
|
||||
provider and object storage.
|
||||
|
||||
## Project layout
|
||||
|
||||
```
|
||||
backend/ .NET 10 — Domain / Application / Infrastructure / Api / Worker / StreamingGateway / Tests
|
||||
web-player/ SvelteKit 2 + Svelte 5 + Tailwind 4 web client
|
||||
deploy/ Docker Compose stacks — self-contained, no wrapper scripts
|
||||
docs/ What each piece does and why (in Spanish)
|
||||
backend/ .NET solution: Api, Worker, StreamingGateway, and the shared Domain/Application/Infrastructure
|
||||
web-player/ the SvelteKit web client
|
||||
deploy/ Docker Compose stacks for dev and production
|
||||
docs/ architecture notes, one file per area
|
||||
```
|
||||
|
||||
```sh
|
||||
dotnet test backend/Musify.slnx # backend/Tests/ — Docker running (Testcontainers: Postgres, SeaweedFS)
|
||||
```
|
||||
Postgres, Zitadel, SeaweedFS, RabbitMQ and Jaeger are not part of this
|
||||
layout. They live in the separate `Infrastructure` repository instead.
|
||||
|
||||
## Run it
|
||||
## Digging deeper
|
||||
|
||||
Development (Docker Desktop):
|
||||
|
||||
```sh
|
||||
docker compose -f deploy/compose.yml -f deploy/compose.dev.yml up -d
|
||||
```
|
||||
|
||||
Infrastructure plus stream-ticket keys, database migrations and Zitadel OIDC
|
||||
provisioning — all as one-shot jobs baked into the compose file. Apps run from
|
||||
the IDE by default; add `--profile apps up -d --build` as a second command to
|
||||
run them in Docker instead.
|
||||
|
||||
Production, on a server with a domain:
|
||||
|
||||
```sh
|
||||
cp deploy/.env.prod.example deploy/.env.prod # fill in the domain and secrets
|
||||
docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml up -d
|
||||
docker compose --env-file deploy/.env.prod -f deploy/compose.yml -f deploy/compose.prod.yml --profile apps up -d --build
|
||||
```
|
||||
|
||||
Idempotent — run the same commands again to deploy an update. See
|
||||
[deploy/README.md](deploy/README.md) for the details, the port map and the
|
||||
production prerequisites.
|
||||
|
||||
## Components
|
||||
|
||||
| Service | Port (dev) | Role |
|
||||
|---|---|---|
|
||||
| `Musify.Api` | 5111 | REST API, issues presigned upload URLs and stream tickets |
|
||||
| `Musify.StreamingGateway` | 8081 | YARP proxy that validates the stream ticket and serves the audio |
|
||||
| `Musify.Worker` | — | MassTransit consumers: transcoding, thumbnails, YouTube downloads |
|
||||
| `web-player` | 5173 / 3000 | Web client (SvelteKit, server-side OIDC session) |
|
||||
| Zitadel | 8080 | Identity (OIDC/OAuth2) |
|
||||
| PostgreSQL / RabbitMQ / SeaweedFS / Jaeger | 59000 / 5672 / 8333 / 16686 | Metadata, messaging, object storage, traces |
|
||||
|
||||
More in [docs/](docs/README.md): [architecture](docs/architecture.md),
|
||||
[authentication](docs/authentication.md), [storage](docs/storage.md),
|
||||
[streaming](docs/streaming.md), [media processing](docs/media-processing.md),
|
||||
[development](docs/development.md).
|
||||
[docs/](docs/README.md) covers how each piece works and why: architecture,
|
||||
authentication, storage, streaming, media processing, and the local dev
|
||||
setup. [deploy/README.md](deploy/README.md) has the full instructions for
|
||||
running the stack, in development or on a production server.
|
||||
|
||||
@@ -17,10 +17,10 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(AddTrackToAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.UserAlbums
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album is null)
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
@@ -32,19 +32,16 @@ namespace Musify.Application.Albums
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var trackExists = await database.Tracks
|
||||
var track = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.AnyAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (!trackExists)
|
||||
.SingleOrDefaultAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (track == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound(description: $"Track {request.TrackId} not found");
|
||||
}
|
||||
|
||||
var localTrack = await database.LocalTracks
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (localTrack is not null && localTrack.OwnerUserId != request.UserId)
|
||||
if (track.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} does not own track {TrackId}", request.UserId, request.TrackId);
|
||||
return Error.Unauthorized();
|
||||
|
||||
@@ -50,7 +50,7 @@ namespace Musify.Application.Albums
|
||||
var intent = pictureIntent.Value;
|
||||
var title = request.Title.Trim();
|
||||
|
||||
var album = new UserAlbum
|
||||
var album = new Album
|
||||
{
|
||||
OwnerUserId = request.UserId,
|
||||
Title = title,
|
||||
@@ -66,7 +66,7 @@ namespace Musify.Application.Albums
|
||||
}
|
||||
};
|
||||
|
||||
await database.UserAlbums.AddAsync(album, cancellationToken);
|
||||
await database.Albums.AddAsync(album, cancellationToken);
|
||||
|
||||
var finalPictureKey = albumConfiguration.Routes.BuildOriginalPicturePath(request.UserId, intent.ObjectName);
|
||||
var publishResult = await PublishCreateAlbumEventAsync(album.Id, intent, finalPictureKey, cancellationToken);
|
||||
|
||||
@@ -16,9 +16,9 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeleteAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.UserAlbums
|
||||
var album = await database.Albums
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album is null)
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogDebug("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
@@ -30,7 +30,7 @@ namespace Musify.Application.Albums
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
database.UserAlbums.Remove(album);
|
||||
database.Albums.Remove(album);
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(GetAlbumByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.UserAlbums
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.Where(a => a.Id == request.Id)
|
||||
.Select(a => new
|
||||
@@ -29,7 +29,7 @@ namespace Musify.Application.Albums
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (album is null)
|
||||
if (album == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return AlbumApplicationResponse.FromEntity(album.Album, album.TrackCount, album.CoverTrackIds);
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace Musify.Application.Albums
|
||||
.Select(a => a.Pictures)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (pictures is null)
|
||||
if (pictures == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var routes = albumConfiguration.Routes;
|
||||
|
||||
@@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
@@ -29,16 +28,15 @@ namespace Musify.Application.Albums
|
||||
|
||||
var tracksQuery = database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(albumTrack => ((ExternalTrack)albumTrack.Track).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(albumTrack => ((LocalTrack)albumTrack.Track).Owner)
|
||||
.Include(albumTrack => albumTrack.Track.Owner)
|
||||
.Include(albumTrack => albumTrack.Track.Tags)
|
||||
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId);
|
||||
|
||||
var totalCount = await tracksQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Select(albumTrack => new { albumTrack.Track, ListensCount = albumTrack.Track.ListeningHistories.Count })
|
||||
.Select(albumTrack => new { albumTrack.Track, ListensCount = albumTrack.Track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
|
||||
|
||||
@@ -1,29 +1,19 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Albums
|
||||
{
|
||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize, string? YoutubeContinuationToken = null)
|
||||
public record GetAlbumsQuery(string? Title, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<AlbumsSearchResponse>>;
|
||||
|
||||
public class GetAlbumsQueryHandler(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
ILogger<GetAlbumsQueryHandler> logger)
|
||||
public class GetAlbumsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetAlbumsQuery, ErrorOr<AlbumsSearchResponse>>
|
||||
{
|
||||
// Mirrors GetTracksQueryHandler's threshold: a title shorter than this is too likely to
|
||||
// still be mid-keystroke to justify a live call to the external search API.
|
||||
private const int MinTitleLengthForYouTubeSearch = 2;
|
||||
|
||||
public async ValueTask<ErrorOr<AlbumsSearchResponse>> Handle(GetAlbumsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var albumsQuery = database.Albums
|
||||
@@ -52,62 +42,19 @@ namespace Musify.Application.Albums
|
||||
})
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var localItems = pagedEntities
|
||||
var items = pagedEntities
|
||||
.Select(entry => AlbumSearchItemResponse.FromAlbum(
|
||||
AlbumApplicationResponse.FromEntity(entry.Album, entry.TrackCount, entry.CoverTrackIds)))
|
||||
.ToList();
|
||||
|
||||
var knownExternalIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in pagedEntities)
|
||||
{
|
||||
if (entry.Album is ExternalAlbum { Source: TrackSource.YouTube } external)
|
||||
knownExternalIds.Add(external.ExternalId);
|
||||
}
|
||||
|
||||
var youtubeItems = new List<AlbumSearchItemResponse>();
|
||||
string? nextContinuationToken = null;
|
||||
var youtubeUnavailable = false;
|
||||
|
||||
if (request.Title?.Trim().Length >= MinTitleLengthForYouTubeSearch)
|
||||
(youtubeItems, nextContinuationToken, youtubeUnavailable) =
|
||||
await SearchYouTubeAsync(request.Title, request.YoutubeContinuationToken, knownExternalIds, cancellationToken);
|
||||
|
||||
return AlbumsSearchResponse.Create(
|
||||
[.. localItems, .. youtubeItems],
|
||||
return new AlbumsSearchResponse(
|
||||
items,
|
||||
pagedEntities.PageNumber,
|
||||
pagedEntities.PageSize,
|
||||
pagedEntities.PageCount,
|
||||
pagedEntities.TotalItemCount,
|
||||
pagedEntities.HasPreviousPage,
|
||||
pagedEntities.HasNextPage,
|
||||
nextContinuationToken,
|
||||
youtubeUnavailable);
|
||||
}
|
||||
|
||||
private async Task<(List<AlbumSearchItemResponse> Items, string? NextContinuationToken, bool Unavailable)> SearchYouTubeAsync(
|
||||
string title,
|
||||
string? continuationToken,
|
||||
HashSet<string> knownExternalIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var searchResult = await youTubeMusicService.SearchAlbumsAsync(title, continuationToken ?? string.Empty, cancellationToken);
|
||||
if (searchResult.IsError)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"YouTube album search unavailable while combining album results: {Error}", searchResult.FirstError.Description);
|
||||
return ([], null, true);
|
||||
}
|
||||
|
||||
var items = searchResult.Value.Items
|
||||
.Where(album => knownExternalIds.Add(album.AlbumId))
|
||||
.Select(AlbumSearchItemResponse.FromYouTubeAlbum)
|
||||
.ToList();
|
||||
|
||||
var nextToken = string.IsNullOrEmpty(searchResult.Value.ContinuationToken)
|
||||
? null
|
||||
: searchResult.Value.ContinuationToken;
|
||||
|
||||
return (items, nextToken, false);
|
||||
pagedEntities.HasNextPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace Musify.Application.Albums
|
||||
if (!userExists)
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
|
||||
var albumsQuery = database.UserAlbums
|
||||
var albumsQuery = database.Albums
|
||||
.AsNoTracking()
|
||||
.Where(album => album.OwnerUserId == request.UserId);
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
var listenedTrackIds = database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(history => history.UserId == request.UserId);
|
||||
.Where(history => history.UserId == request.UserId && history.IsCounted);
|
||||
|
||||
var ranked = await database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
|
||||
@@ -16,10 +16,10 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(RemoveTrackFromAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.UserAlbums
|
||||
var album = await database.Albums
|
||||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album is null)
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
@@ -37,7 +37,7 @@ namespace Musify.Application.Albums
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var link = albumTracks.SingleOrDefault(albumTrack => albumTrack.TrackId == request.TrackId);
|
||||
if (link is null)
|
||||
if (link == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not in album {AlbumId}", request.TrackId, request.AlbumId);
|
||||
return Error.NotFound(description: "Track is not in the album.");
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Application.Serialization;
|
||||
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
// [JsonPolymorphic]/[JsonDerivedType] are required here, not optional: without them
|
||||
// System.Text.Json serializes strictly by the declared CLR type at each call site
|
||||
// (AlbumApplicationResponse, both as a bare return type and nested inside
|
||||
// AlbumSearchItemResponse.Album), so an ExternalAlbumApplicationResponse instance would
|
||||
// silently lose ExternalId/ThumbnailUrl on the wire. This also gives every response a
|
||||
// "source" discriminator field for free, matching AlbumSearchItemResponse.Source.
|
||||
[JsonPolymorphic(TypeDiscriminatorPropertyName = "source")]
|
||||
[JsonDerivedType(typeof(AlbumApplicationResponse), typeDiscriminator: "Local")]
|
||||
[JsonDerivedType(typeof(ExternalAlbumApplicationResponse), typeDiscriminator: "YouTube")]
|
||||
public record AlbumApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Description,
|
||||
int? ReleaseYear,
|
||||
long OwnerUserId,
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId,
|
||||
int TrackCount,
|
||||
string? SmallImageKeyName,
|
||||
string? MediumImageKeyName,
|
||||
@@ -29,7 +21,7 @@ namespace Musify.Application.Albums.Responses
|
||||
public const int CoverTrackCount = 4;
|
||||
|
||||
public static AlbumApplicationResponse FromEntity(
|
||||
UserAlbum album,
|
||||
Album album,
|
||||
int trackCount,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
@@ -47,18 +39,5 @@ namespace Musify.Application.Albums.Responses
|
||||
album.UpdatedAt,
|
||||
coverTrackIds ?? []);
|
||||
}
|
||||
|
||||
public static AlbumApplicationResponse FromEntity(
|
||||
Album album,
|
||||
int trackCount,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
return album switch
|
||||
{
|
||||
ExternalAlbum externalAlbum => ExternalAlbumApplicationResponse.FromEntity(externalAlbum, trackCount, coverTrackIds),
|
||||
UserAlbum userAlbum => FromEntity(userAlbum, trackCount, coverTrackIds),
|
||||
_ => throw new NotSupportedException($"Unsupported album entity type '{album.GetType().Name}'.")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
/// <summary>One item of a combined local/external album listing. Exactly one of
|
||||
/// <see cref="Album"/> or <see cref="YouTubeAlbum"/> is populated: <see cref="Album"/> for
|
||||
/// anything already in the catalog (locally created albums and external albums materialized
|
||||
/// earlier), <see cref="YouTubeAlbum"/> for a live external search hit that hasn't been
|
||||
/// materialized yet, so it has no album id.</summary>
|
||||
public record AlbumSearchItemResponse(
|
||||
TrackSource Source,
|
||||
AlbumApplicationResponse? Album,
|
||||
YouTubeAlbumResult? YouTubeAlbum)
|
||||
public record AlbumSearchItemResponse(AlbumApplicationResponse Album)
|
||||
{
|
||||
public static AlbumSearchItemResponse FromAlbum(AlbumApplicationResponse album) =>
|
||||
new(album is ExternalAlbumApplicationResponse ? TrackSource.YouTube : TrackSource.Local, album, null);
|
||||
|
||||
public static AlbumSearchItemResponse FromYouTubeAlbum(YouTubeAlbumResult album) =>
|
||||
new(TrackSource.YouTube, null, album);
|
||||
public static AlbumSearchItemResponse FromAlbum(AlbumApplicationResponse album) => new(album);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
/// <summary>Result of a combined albums listing/search: a page of local catalog albums
|
||||
/// (user-created and previously materialized external albums), plus, when a search term was
|
||||
/// given, live external hits appended after them. Pagination metadata (<see cref="PageNumber"/>,
|
||||
/// <see cref="PageSize"/>, <see cref="PageCount"/>, <see cref="TotalItemCount"/>) describes only
|
||||
/// the local page — the external source has no stable total, so its continuation is tracked
|
||||
/// separately via <see cref="NextYoutubeContinuationToken"/>.</summary>
|
||||
|
||||
public record AlbumsSearchResponse(
|
||||
IReadOnlyList<AlbumSearchItemResponse> Items,
|
||||
int PageNumber,
|
||||
@@ -13,26 +8,5 @@ namespace Musify.Application.Albums.Responses
|
||||
int PageCount,
|
||||
int TotalItemCount,
|
||||
bool HasPreviousPage,
|
||||
bool HasNextLocalPage,
|
||||
string? NextYoutubeContinuationToken,
|
||||
bool YoutubeUnavailable,
|
||||
bool HasNextPage)
|
||||
{
|
||||
// HasNextPage is a real field (not a computed property) so it shows up as a required member
|
||||
// of the generated OpenAPI schema, same as every other field here — a get-only property added
|
||||
// outside the primary constructor gets reflected as optional instead, which is never true here.
|
||||
public static AlbumsSearchResponse Create(
|
||||
IReadOnlyList<AlbumSearchItemResponse> items,
|
||||
int pageNumber,
|
||||
int pageSize,
|
||||
int pageCount,
|
||||
int totalItemCount,
|
||||
bool hasPreviousPage,
|
||||
bool hasNextLocalPage,
|
||||
string? nextYoutubeContinuationToken,
|
||||
bool youtubeUnavailable) =>
|
||||
new(items, pageNumber, pageSize, pageCount, totalItemCount, hasPreviousPage, hasNextLocalPage,
|
||||
nextYoutubeContinuationToken, youtubeUnavailable,
|
||||
HasNextPage: hasNextLocalPage || !string.IsNullOrEmpty(nextYoutubeContinuationToken));
|
||||
}
|
||||
bool HasNextPage);
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Albums.Responses
|
||||
{
|
||||
public record ExternalAlbumApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Description,
|
||||
int? ReleaseYear,
|
||||
long OwnerUserId,
|
||||
int TrackCount,
|
||||
string? SmallImageKeyName,
|
||||
string? MediumImageKeyName,
|
||||
string? LargeImageKeyName,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
IReadOnlyList<Guid> CoverTrackIds,
|
||||
string ExternalId,
|
||||
string? ThumbnailUrl)
|
||||
: AlbumApplicationResponse(
|
||||
Id, Title, Description, ReleaseYear, OwnerUserId, TrackCount,
|
||||
SmallImageKeyName, MediumImageKeyName, LargeImageKeyName,
|
||||
CreatedAt, UpdatedAt, CoverTrackIds)
|
||||
{
|
||||
public static ExternalAlbumApplicationResponse FromEntity(
|
||||
ExternalAlbum album,
|
||||
int trackCount,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
return new ExternalAlbumApplicationResponse(
|
||||
album.Id,
|
||||
album.Title,
|
||||
album.Description,
|
||||
album.ReleaseYear,
|
||||
0,
|
||||
trackCount,
|
||||
album.Pictures?.SmallName,
|
||||
album.Pictures?.MediumName,
|
||||
album.Pictures?.LargeName,
|
||||
album.CreatedAt,
|
||||
album.UpdatedAt,
|
||||
coverTrackIds ?? [],
|
||||
album.ExternalId,
|
||||
album.ThumbnailUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,9 @@ namespace Musify.Application.Albums
|
||||
{
|
||||
public async ValueTask<ErrorOr<AlbumApplicationResponse>> Handle(UpdateAlbumCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var album = await database.UserAlbums
|
||||
var album = await database.Albums
|
||||
.SingleOrDefaultAsync(a => a.Id == request.AlbumId, cancellationToken);
|
||||
if (album is null)
|
||||
if (album == null)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound();
|
||||
@@ -77,8 +77,6 @@ namespace Musify.Application.Albums
|
||||
finalPictureKey = albumConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
|
||||
}
|
||||
|
||||
database.UserAlbums.Update(album);
|
||||
|
||||
if (pictureIntent != null && finalPictureKey != null)
|
||||
{
|
||||
var publishResult = await PublishUpdateAlbumPictureSourceEventAsync(
|
||||
|
||||
@@ -12,7 +12,6 @@ public static class ApplicationDependencyInjection
|
||||
services.AddMediator();
|
||||
services.AddScoped<UploadIntentValidator>();
|
||||
services.AddScoped<TrackStreamIssuer>();
|
||||
services.AddScoped<YouTubeTrackProvisioner>();
|
||||
|
||||
services.AddValidatedOptions<ApplicationStorageConfiguration>(configuration, ApplicationStorageConfiguration.SectionName);
|
||||
services.AddValidatedOptions<PlayListConfiguration>(configuration, PlayListConfiguration.SectionName);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using Mediator;
|
||||
using Musify.Application.Configuration.Responses;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
|
||||
public record GetPlaybackPublicConfigQuery : IQuery<PlaybackPublicConfigResponse>;
|
||||
|
||||
public class GetPlaybackPublicConfigQueryHandler(PlaybackConfiguration playbackConfiguration)
|
||||
: IQueryHandler<GetPlaybackPublicConfigQuery, PlaybackPublicConfigResponse>
|
||||
{
|
||||
public ValueTask<PlaybackPublicConfigResponse> Handle(GetPlaybackPublicConfigQuery query, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult(new PlaybackPublicConfigResponse(
|
||||
playbackConfiguration.AllowAnonymousListening,
|
||||
playbackConfiguration.AnonymousFragmentSeconds));
|
||||
}
|
||||
}
|
||||
@@ -6,16 +6,7 @@ namespace Musify.Application.Configuration
|
||||
{
|
||||
public const string SectionName = "Mix";
|
||||
|
||||
[Range(1, 20)]
|
||||
public int ArtistMixCount { get; set; } = 3;
|
||||
|
||||
[Range(4, 100)]
|
||||
public int ItemsPerMix { get; set; } = 12;
|
||||
|
||||
[Range(1, 10)]
|
||||
public int SeedArtistCount { get; set; } = 3;
|
||||
|
||||
[Range(1, 100)]
|
||||
public int YouTubeResultsPerSeed { get; set; } = 12;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,6 @@ namespace Musify.Application.Configuration
|
||||
|
||||
[Required]
|
||||
public PlayListPicturesSizes PicturesSizes { get; set; } = new PlayListPicturesSizes();
|
||||
|
||||
public bool SeedPresetPictures { get; set; } = true;
|
||||
|
||||
public bool OverwritePresetPictures { get; set; } = false;
|
||||
}
|
||||
|
||||
public class PlayListRoutes
|
||||
@@ -38,18 +34,6 @@ namespace Musify.Application.Configuration
|
||||
[Required]
|
||||
public string LargePicturesFolder { get; set; } = "LargePictures";
|
||||
|
||||
[Required]
|
||||
public string PresetOriginalPicture { get; set; } = "PresetOriginalPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetSmallPicture { get; set; } = "PresetSmallPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetMediumPicture { get; set; } = "PresetMediumPicture.webp";
|
||||
|
||||
[Required]
|
||||
public string PresetLargePicture { get; set; } = "PresetLargePicture.webp";
|
||||
|
||||
public string SmallPicturesPath => StorageKey.Combine(ParentFolders, SmallPicturesFolder);
|
||||
|
||||
public string MediumPicturesPath => StorageKey.Combine(ParentFolders, MediumPicturesFolder);
|
||||
@@ -58,12 +42,6 @@ namespace Musify.Application.Configuration
|
||||
|
||||
public string OriginalPicturesPath => StorageKey.Combine(ParentFolders, OriginalPicturesFolder);
|
||||
|
||||
public string PresetSmallPicturePath => StorageKey.Combine(ParentFolders, SmallPicturesFolder, PresetSmallPicture);
|
||||
|
||||
public string PresetMediumPicturePath => StorageKey.Combine(ParentFolders, MediumPicturesFolder, PresetMediumPicture);
|
||||
|
||||
public string PresetLargePicturePath => StorageKey.Combine(ParentFolders, LargePicturesFolder, PresetLargePicture);
|
||||
|
||||
public string BuildOriginalPicturePath(string pictureName) => StorageKey.Combine(ParentFolders, OriginalPicturesFolder, pictureName);
|
||||
|
||||
public string BuildOriginalPicturePath(long userId, string pictureName) => StorageKey.Combine(UploadsFolder, userId.ToString(), ParentFolders, OriginalPicturesFolder, pictureName);
|
||||
|
||||
@@ -2,28 +2,16 @@ using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.Application.Configuration
|
||||
{
|
||||
/// <summary>Controls whether listeners without a session can stream music at all, and if so,
|
||||
/// how much of a track they get to hear before being cut off (a Spotify-style preview).</summary>
|
||||
|
||||
public sealed class PlaybackConfiguration
|
||||
{
|
||||
public const string SectionName = "Playback";
|
||||
|
||||
/// <summary>When false (the default), every stream endpoint requires a signed-in user, exactly
|
||||
/// like before this setting existed. When true, an anonymous request is issued a stream ticket
|
||||
/// too, capped by <see cref="AnonymousFragmentSeconds"/> if that is greater than zero.</summary>
|
||||
public bool AllowAnonymousListening { get; set; }
|
||||
|
||||
/// <summary>How many seconds of a track an anonymous listener may hear, enforced by the
|
||||
/// Streaming Gateway clamping the byte range it will serve for that ticket. Zero (the default)
|
||||
/// means no cap: anonymous listeners hear the full track, same as a signed-in user. Ignored
|
||||
/// when <see cref="AllowAnonymousListening"/> is false.</summary>
|
||||
[Range(0, 3600)]
|
||||
public int AnonymousFragmentSeconds { get; set; }
|
||||
|
||||
/// <summary>Bytes per second of the transcoded audio, used to turn <see cref="AnonymousFragmentSeconds"/>
|
||||
/// into a byte cap for the stream ticket. Defaults to the app's own transcoder output (128 kbps
|
||||
/// AAC, <c>AudioTranscoder:Ffmpeg:AudioBitrate</c>) — update this alongside that setting if it
|
||||
/// ever changes, since the two aren't wired together.</summary>
|
||||
[Range(1, int.MaxValue)]
|
||||
public int EstimatedAudioBytesPerSecond { get; set; } = 16_000;
|
||||
}
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
namespace Musify.Application.Configuration.Responses
|
||||
{
|
||||
|
||||
public record PlaybackPublicConfigResponse(bool AllowAnonymousListening, int AnonymousFragmentSeconds);
|
||||
}
|
||||
@@ -11,22 +11,10 @@ namespace Musify.Application.Contracts
|
||||
|
||||
DbSet<Album> Albums { get; }
|
||||
|
||||
DbSet<UserAlbum> UserAlbums { get; }
|
||||
|
||||
DbSet<ExternalAlbum> ExternalAlbums { get; }
|
||||
|
||||
DbSet<AlbumHasTrack> AlbumHasTracks { get; }
|
||||
|
||||
DbSet<Track> Tracks { get; }
|
||||
|
||||
DbSet<LocalTrack> LocalTracks { get; }
|
||||
|
||||
DbSet<ExternalTrack> ExternalTracks { get; }
|
||||
|
||||
DbSet<Artist> Artists { get; }
|
||||
|
||||
DbSet<TrackArtist> TrackArtists { get; }
|
||||
|
||||
DbSet<UserHasTrack> UserHasTracks { get; }
|
||||
|
||||
DbSet<PlayListHasTrack> PlayListHasTracks { get; }
|
||||
@@ -41,6 +29,12 @@ namespace Musify.Application.Contracts
|
||||
|
||||
DbSet<ListeningHistory> ListeningHistories { get; }
|
||||
|
||||
DbSet<TrackLike> TrackLikes { get; }
|
||||
|
||||
DbSet<TrackTag> TrackTags { get; }
|
||||
|
||||
DbSet<UserFollow> UserFollows { get; }
|
||||
|
||||
Task<IDatabaseTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken);
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
|
||||
|
||||
@@ -2,11 +2,7 @@ namespace Musify.Application.Contracts
|
||||
{
|
||||
public interface IStreamTicketService
|
||||
{
|
||||
/// <param name="userId">Null for an anonymous listener — the ticket is issued without a
|
||||
/// <c>sub</c> claim.</param>
|
||||
/// <param name="keyPrefix">The storage key (prefix) the ticket authorizes reading from.</param>
|
||||
/// <param name="maxBytes">When set, the Streaming Gateway clamps the byte range it will serve
|
||||
/// for this ticket to <c>[0, maxBytes)</c> — used for the anonymous preview fragment.</param>
|
||||
|
||||
StreamTicket IssueTicket(long? userId, string keyPrefix, long? maxBytes = null);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace Musify.Application.Contracts
|
||||
{
|
||||
public record YouTubeDownloadResult(int ExitCode, string StandardError);
|
||||
|
||||
public interface IYouTubeDownloaderService
|
||||
{
|
||||
Task<YouTubeDownloadResult> DownloadAudioAsync(string videoId, string destinationFilePath, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
using ErrorOr;
|
||||
|
||||
namespace Musify.Application.Contracts
|
||||
{
|
||||
public record YouTubeArtistRef(string? Id, string Name);
|
||||
|
||||
public record YouTubeSongResult(
|
||||
string VideoId,
|
||||
string Title,
|
||||
string Artist,
|
||||
string Album,
|
||||
int DurationSeconds,
|
||||
string ThumbnailUrl,
|
||||
bool IsExplicit,
|
||||
IReadOnlyList<YouTubeArtistRef> Artists);
|
||||
|
||||
public record YouTubeSearchResult(
|
||||
IReadOnlyList<YouTubeSongResult> Items,
|
||||
string ContinuationToken);
|
||||
|
||||
public record YouTubeAlbumResult(
|
||||
string AlbumId,
|
||||
string Title,
|
||||
string Artist,
|
||||
string ThumbnailUrl,
|
||||
int? ReleaseYear,
|
||||
bool IsSingle,
|
||||
bool IsEp,
|
||||
IReadOnlyList<YouTubeArtistRef> Artists);
|
||||
|
||||
public record YouTubeAlbumSearchResult(
|
||||
IReadOnlyList<YouTubeAlbumResult> Items,
|
||||
string ContinuationToken);
|
||||
|
||||
public record YouTubeAlbumTrack(
|
||||
string VideoId,
|
||||
string Title,
|
||||
int DurationSeconds,
|
||||
int TrackNumber,
|
||||
bool IsExplicit);
|
||||
|
||||
public record YouTubeAlbumDetail(
|
||||
YouTubeAlbumResult Album,
|
||||
string Description,
|
||||
int TotalDurationSeconds,
|
||||
IReadOnlyList<YouTubeAlbumTrack> Tracks);
|
||||
|
||||
public record YouTubeStreamInfo(string Url, int ExpiresInSeconds);
|
||||
|
||||
public interface IYouTubeMusicService
|
||||
{
|
||||
Task<ErrorOr<YouTubeSearchResult>> SearchSongsAsync(string query, string continuationToken, CancellationToken cancellationToken);
|
||||
|
||||
Task<ErrorOr<YouTubeAlbumSearchResult>> SearchAlbumsAsync(string query, string continuationToken, CancellationToken cancellationToken);
|
||||
|
||||
Task<ErrorOr<YouTubeAlbumDetail>> GetAlbumAsync(string albumId, CancellationToken cancellationToken);
|
||||
|
||||
Task<ErrorOr<YouTubeStreamInfo>> GetAudioStreamAsync(string videoId, CancellationToken cancellationToken);
|
||||
|
||||
Task<ErrorOr<YouTubeSongResult>> GetSongAsync(string videoId, CancellationToken cancellationToken);
|
||||
|
||||
string ResolveArtworkUrl(string thumbnailUrl);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using Musify.Application.Shared;
|
||||
|
||||
namespace Musify.Application.Events
|
||||
{
|
||||
public record DownloadYouTubeTrackEvent(
|
||||
Guid TrackId,
|
||||
string VideoId,
|
||||
string ThumbnailUrl,
|
||||
string Bucket,
|
||||
string AudioProcessedFolderKey,
|
||||
ImageSize Small,
|
||||
ImageSize Medium,
|
||||
ImageSize Large);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Mediator;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Genres
|
||||
{
|
||||
public record GetAvailableGenresQuery : IQuery<IReadOnlyList<AvailableGenreResponse>>;
|
||||
|
||||
public record AvailableGenreResponse(Genre Genre, IReadOnlyList<Genre> IncompatibleWith);
|
||||
|
||||
public class GetAvailableGenresQueryHandler
|
||||
: IQueryHandler<GetAvailableGenresQuery, IReadOnlyList<AvailableGenreResponse>>
|
||||
{
|
||||
public ValueTask<IReadOnlyList<AvailableGenreResponse>> Handle(GetAvailableGenresQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var all = Enum.GetValues<Genre>();
|
||||
|
||||
IReadOnlyList<AvailableGenreResponse> result = all
|
||||
.Select(genre => new AvailableGenreResponse(
|
||||
genre,
|
||||
all.Where(other => !GenreCompatibility.AreCompatible(genre, other)).ToList()))
|
||||
.ToList();
|
||||
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Genres
|
||||
{
|
||||
public record GetGenresQuery : IQuery<IReadOnlyList<GenreResponse>>;
|
||||
|
||||
public record GenreResponse(Genre Genre, int TrackCount);
|
||||
|
||||
public class GetGenresQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetGenresQuery, IReadOnlyList<GenreResponse>>
|
||||
{
|
||||
public async ValueTask<IReadOnlyList<GenreResponse>> Handle(GetGenresQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await database.TrackTags
|
||||
.AsNoTracking()
|
||||
.Where(tag => database.UserHasTracks.Any(userTrack => userTrack.TrackId == tag.TrackId))
|
||||
.GroupBy(tag => tag.Tag)
|
||||
.Select(group => new { Genre = group.Key, TrackCount = group.Select(tag => tag.TrackId).Distinct().Count() })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return rows
|
||||
.OrderByDescending(row => row.TrackCount)
|
||||
.ThenBy(row => row.Genre)
|
||||
.Select(row => new GenreResponse(row.Genre, row.TrackCount))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Likes
|
||||
{
|
||||
public record GetLikedTracksQuery(
|
||||
long UserId,
|
||||
int PageNumber,
|
||||
int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<TrackApplicationResponse>>>;
|
||||
|
||||
public class GetLikedTracksQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetLikedTracksQuery, ErrorOr<PaginatedResponse<TrackApplicationResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<TrackApplicationResponse>>> Handle(GetLikedTracksQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var likesQuery = database.TrackLikes
|
||||
.AsNoTracking()
|
||||
.Include(like => like.Track.Owner)
|
||||
.Include(like => like.Track.Tags)
|
||||
.Where(like => like.UserId == request.UserId);
|
||||
|
||||
var totalCount = await likesQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await likesQuery
|
||||
.OrderByDescending(like => like.CreatedAt)
|
||||
.Select(like => new { like.Track, ListensCount = like.Track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
|
||||
pagedEntities.Select(x => TrackApplicationResponse.FromEntity(x.Track, x.ListensCount)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<TrackApplicationResponse>.FromPagedList(pagedTracks);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Likes
|
||||
{
|
||||
public record ToggleTrackLikeCommand(long UserId, Guid TrackId)
|
||||
: ICommand<ErrorOr<bool>>;
|
||||
|
||||
public class ToggleTrackLikeCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<ToggleTrackLikeCommandHandler> logger)
|
||||
: ICommandHandler<ToggleTrackLikeCommand, ErrorOr<bool>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<bool>> Handle(ToggleTrackLikeCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackExists = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.AnyAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (!trackExists)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound(description: $"Track {request.TrackId} not found");
|
||||
}
|
||||
|
||||
var existingLike = await database.TrackLikes
|
||||
.SingleOrDefaultAsync(like => like.UserId == request.UserId && like.TrackId == request.TrackId, cancellationToken);
|
||||
|
||||
bool nowLiked;
|
||||
if (existingLike != null)
|
||||
{
|
||||
database.TrackLikes.Remove(existingLike);
|
||||
nowLiked = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
await database.TrackLikes.AddAsync(new TrackLike
|
||||
{
|
||||
UserId = request.UserId,
|
||||
TrackId = request.TrackId
|
||||
}, cancellationToken);
|
||||
nowLiked = true;
|
||||
}
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("User {UserId} {Action} track {TrackId}",
|
||||
request.UserId, nowLiked ? "liked" : "unliked", request.TrackId);
|
||||
|
||||
return nowLiked;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
@@ -15,60 +14,58 @@ namespace Musify.Application.Mixes
|
||||
|
||||
public class GenerateMixesForUserCommandHandler(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
MixConfiguration mixConfiguration,
|
||||
ILogger<GenerateMixesForUserCommandHandler> logger)
|
||||
: ICommandHandler<GenerateMixesForUserCommand, ErrorOr<Success>>
|
||||
{
|
||||
private sealed record SeedArtist(Guid Id, string Name);
|
||||
|
||||
private sealed record LocalCandidate(Guid TrackId, string Title, string? Artist, double DurationSeconds);
|
||||
|
||||
private sealed record MixDraft(string Title, string? Subtitle, IReadOnlyList<MixItem> Items);
|
||||
|
||||
private const int TitleLength = 300;
|
||||
private const int ArtistLength = 300;
|
||||
private const int ThumbnailUrlLength = 512;
|
||||
private const int MixTitleLength = 100;
|
||||
private sealed record MixDraft(string Title, string? Subtitle, IReadOnlyList<Guid> TrackIds);
|
||||
|
||||
public async ValueTask<ErrorOr<Success>> Handle(GenerateMixesForUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = request.UserId;
|
||||
|
||||
var libraryTrackIds = await database.UserHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(userTrack => userTrack.UserId == userId && userTrack.Track.LifeCycleStatus == LifeCycleStatus.Active)
|
||||
.Select(userTrack => userTrack.TrackId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (libraryTrackIds.Count == 0)
|
||||
{
|
||||
logger.LogInformation("User {UserId} has no tracks yet, skipping mix generation", userId);
|
||||
return new Success();
|
||||
}
|
||||
|
||||
var historyTrackIds = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(history => history.UserId == userId)
|
||||
.Where(history => history.UserId == userId && history.IsCounted)
|
||||
.Select(history => history.TrackId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (historyTrackIds.Count == 0)
|
||||
var historySet = new HashSet<Guid>(historyTrackIds);
|
||||
var unheardTrackIds = libraryTrackIds.Where(id => !historySet.Contains(id)).ToList();
|
||||
|
||||
var drafts = new List<MixDraft>();
|
||||
|
||||
var discovery = Take(Shuffle(unheardTrackIds));
|
||||
if (discovery.Count > 0)
|
||||
{
|
||||
logger.LogInformation("User {UserId} has no listening history yet, skipping mix generation", userId);
|
||||
return new Success();
|
||||
drafts.Add(new MixDraft(
|
||||
"Descubrimiento",
|
||||
"Canciones de tu biblioteca que todavía no has escuchado.",
|
||||
discovery));
|
||||
}
|
||||
|
||||
var seedArtists = await GetSeedArtistsAsync(historyTrackIds, cancellationToken);
|
||||
|
||||
if (seedArtists.Count == 0)
|
||||
var daily = Take(Interleave(Shuffle(historyTrackIds), Shuffle(unheardTrackIds)));
|
||||
if (daily.Count > 0)
|
||||
{
|
||||
logger.LogInformation("User {UserId} has no artists to seed mixes from, skipping mix generation", userId);
|
||||
return new Success();
|
||||
drafts.Add(new MixDraft(
|
||||
"Tu mezcla diaria",
|
||||
"Lo que más escuchas, con alguna sorpresa de tu biblioteca.",
|
||||
daily));
|
||||
}
|
||||
|
||||
var knownVideoIds = await database.ExternalTracks
|
||||
.AsNoTracking()
|
||||
.Where(track => track.Source == TrackSource.YouTube && historyTrackIds.Contains(track.Id))
|
||||
.Select(track => track.ExternalId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var excludedVideoIds = new HashSet<string>(knownVideoIds, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var youTubeByArtist = await SearchYouTubeAsync(seedArtists, excludedVideoIds, cancellationToken);
|
||||
var localByArtist = await GetLocalCandidatesAsync(seedArtists, historyTrackIds, cancellationToken);
|
||||
|
||||
var drafts = BuildDrafts(seedArtists, localByArtist, youTubeByArtist);
|
||||
|
||||
if (drafts.Count == 0)
|
||||
{
|
||||
logger.LogInformation("No candidate songs found for user {UserId}, skipping mix generation", userId);
|
||||
@@ -91,191 +88,15 @@ namespace Musify.Application.Mixes
|
||||
return new Success();
|
||||
}
|
||||
|
||||
private async Task<List<SeedArtist>> GetSeedArtistsAsync(
|
||||
IReadOnlyList<Guid> historyTrackIds,
|
||||
CancellationToken cancellationToken)
|
||||
private List<Guid> Take(IEnumerable<Guid> trackIds) =>
|
||||
[.. trackIds.Take(mixConfiguration.ItemsPerMix)];
|
||||
|
||||
private static List<Guid> Shuffle(IEnumerable<Guid> trackIds) =>
|
||||
[.. trackIds.OrderBy(_ => Guid.NewGuid())];
|
||||
|
||||
private static List<Guid> Interleave(IReadOnlyList<Guid> first, IReadOnlyList<Guid> second)
|
||||
{
|
||||
var ranked = await database.TrackArtists
|
||||
.AsNoTracking()
|
||||
.Where(trackArtist => historyTrackIds.Contains(trackArtist.TrackId))
|
||||
.GroupBy(trackArtist => trackArtist.ArtistId)
|
||||
.Select(group => new { ArtistId = group.Key, Listens = group.Count() } )
|
||||
.OrderByDescending(entry => entry.Listens)
|
||||
.Take(mixConfiguration.SeedArtistCount)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var artistIds = ranked.Select(entry => entry.ArtistId).ToList();
|
||||
|
||||
var names = await database.Artists
|
||||
.AsNoTracking()
|
||||
.Where(artist => artistIds.Contains(artist.Id))
|
||||
.ToDictionaryAsync(artist => artist.Id, artist => artist.Name, cancellationToken);
|
||||
|
||||
return [.. ranked
|
||||
.Where(entry => names.ContainsKey(entry.ArtistId))
|
||||
.Select(entry => new SeedArtist(entry.ArtistId, names[entry.ArtistId])) ];
|
||||
}
|
||||
|
||||
private async Task<Dictionary<Guid, List<MixItem>> > SearchYouTubeAsync(
|
||||
IReadOnlyList<SeedArtist> seedArtists,
|
||||
HashSet<string> excludedVideoIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var byArtist = new Dictionary<Guid, List<MixItem>>();
|
||||
|
||||
foreach (var seed in seedArtists)
|
||||
{
|
||||
var searchResult = await youTubeMusicService.SearchSongsAsync(seed.Name, string.Empty, cancellationToken);
|
||||
if (searchResult.IsError)
|
||||
{
|
||||
logger.LogWarning("YouTube Music search failed for seed artist {Artist}: {Error}",
|
||||
seed.Name, searchResult.FirstError.Description);
|
||||
byArtist[seed.Id] = [];
|
||||
continue;
|
||||
}
|
||||
|
||||
var songs = new List<MixItem>();
|
||||
foreach (var song in searchResult.Value.Items.Take(mixConfiguration.YouTubeResultsPerSeed))
|
||||
{
|
||||
if (!excludedVideoIds.Add(song.VideoId))
|
||||
continue;
|
||||
|
||||
songs.Add(new MixItem
|
||||
{
|
||||
MixId = Guid.Empty,
|
||||
Source = MixItemSource.YouTube,
|
||||
VideoId = song.VideoId,
|
||||
Title = Truncate(song.Title, TitleLength),
|
||||
Artist = Truncate(song.Artist, ArtistLength),
|
||||
ThumbnailUrl = Truncate(youTubeMusicService.ResolveArtworkUrl(song.ThumbnailUrl), ThumbnailUrlLength),
|
||||
DurationSeconds = song.DurationSeconds,
|
||||
IsExplicit = song.IsExplicit
|
||||
} );
|
||||
}
|
||||
|
||||
byArtist[seed.Id] = songs;
|
||||
}
|
||||
|
||||
return byArtist;
|
||||
}
|
||||
|
||||
private async Task<Dictionary<Guid, List<MixItem>> > GetLocalCandidatesAsync(
|
||||
IReadOnlyList<SeedArtist> seedArtists,
|
||||
IReadOnlyList<Guid> historyTrackIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var artistIds = seedArtists.Select(seed => seed.Id).ToList();
|
||||
|
||||
var links = await database.TrackArtists
|
||||
.AsNoTracking()
|
||||
.Where(trackArtist => artistIds.Contains(trackArtist.ArtistId) && !historyTrackIds.Contains(trackArtist.TrackId))
|
||||
.Select(trackArtist => new { trackArtist.ArtistId, trackArtist.TrackId } )
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var trackIds = links.Select(link => link.TrackId).Distinct().ToList();
|
||||
|
||||
var candidates = await LoadCandidatesAsync(trackIds, cancellationToken);
|
||||
|
||||
var byArtist = new Dictionary<Guid, List<MixItem>>();
|
||||
foreach (var seed in seedArtists)
|
||||
{
|
||||
byArtist[seed.Id] = [.. links
|
||||
.Where(link => link.ArtistId == seed.Id)
|
||||
.Select(link => candidates.GetValueOrDefault(link.TrackId))
|
||||
.Where(candidate => candidate is not null)
|
||||
.Select(candidate => ToMixItem(candidate!))];
|
||||
}
|
||||
|
||||
return byArtist;
|
||||
}
|
||||
|
||||
private async Task<Dictionary<Guid, LocalCandidate>> LoadCandidatesAsync(
|
||||
IReadOnlyList<Guid> trackIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (trackIds.Count == 0)
|
||||
return [];
|
||||
|
||||
var tracks = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.Where(track => trackIds.Contains(track.Id) && track.LifeCycleStatus == LifeCycleStatus.Active)
|
||||
.Include(track => ((ExternalTrack)track).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(track => ((LocalTrack)track).Owner)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return tracks
|
||||
.Select(track => TrackApplicationResponse.FromEntity(track, 0))
|
||||
.ToDictionary(
|
||||
response => response.Id,
|
||||
response => new LocalCandidate(response.Id, response.Title, response.Artist, response.Duration));
|
||||
}
|
||||
|
||||
private static MixItem ToMixItem(LocalCandidate candidate) => new()
|
||||
{
|
||||
MixId = Guid.Empty,
|
||||
Source = MixItemSource.Musify,
|
||||
TrackId = candidate.TrackId,
|
||||
Title = candidate.Title,
|
||||
Artist = candidate.Artist,
|
||||
DurationSeconds = candidate.DurationSeconds
|
||||
};
|
||||
|
||||
private List<MixDraft> BuildDrafts(
|
||||
IReadOnlyList<SeedArtist> seedArtists,
|
||||
IReadOnlyDictionary<Guid, List<MixItem>> localByArtist,
|
||||
IReadOnlyDictionary<Guid, List<MixItem>> youTubeByArtist)
|
||||
{
|
||||
var drafts = new List<MixDraft>();
|
||||
|
||||
var everyYouTube = seedArtists.SelectMany(seed => youTubeByArtist[seed.Id]).ToList();
|
||||
var everyLocal = seedArtists.SelectMany(seed => localByArtist[seed.Id]).ToList();
|
||||
|
||||
var discovery = Take(Shuffle(everyYouTube));
|
||||
if (discovery.Count > 0)
|
||||
{
|
||||
drafts.Add(new MixDraft(
|
||||
"Descubrimiento",
|
||||
"Canciones nuevas que todavía no has escuchado.",
|
||||
discovery));
|
||||
}
|
||||
|
||||
var daily = Take(Interleave(Shuffle(everyLocal), Shuffle(everyYouTube)));
|
||||
if (daily.Count > 0)
|
||||
{
|
||||
drafts.Add(new MixDraft(
|
||||
"Tu mezcla diaria",
|
||||
"Lo que más escuchas, con alguna sorpresa nueva.",
|
||||
daily));
|
||||
}
|
||||
|
||||
foreach (var seed in seedArtists.Take(mixConfiguration.ArtistMixCount))
|
||||
{
|
||||
var items = Take(Interleave(Shuffle(localByArtist[seed.Id]), Shuffle(youTubeByArtist[seed.Id])));
|
||||
if (items.Count == 0)
|
||||
continue;
|
||||
|
||||
drafts.Add(new MixDraft(
|
||||
Truncate(seed.Name, MixTitleLength),
|
||||
$"Canciones de {seed.Name} y de artistas parecidos.",
|
||||
items));
|
||||
}
|
||||
|
||||
return drafts;
|
||||
}
|
||||
|
||||
private List<MixItem> Take(IEnumerable<MixItem> items) =>
|
||||
[.. items.Take(mixConfiguration.ItemsPerMix)];
|
||||
|
||||
private static string Truncate(string value, int maxLength) =>
|
||||
value.Length <= maxLength ? value : value[..maxLength];
|
||||
|
||||
private static List<MixItem> Shuffle(IEnumerable<MixItem> items) =>
|
||||
[.. items.OrderBy(_ => Guid.NewGuid())];
|
||||
|
||||
private static List<MixItem> Interleave(IReadOnlyList<MixItem> first, IReadOnlyList<MixItem> second)
|
||||
{
|
||||
var merged = new List<MixItem>(first.Count + second.Count);
|
||||
var merged = new List<Guid>(first.Count + second.Count);
|
||||
for (var index = 0; index < Math.Max(first.Count, second.Count); index++)
|
||||
{
|
||||
if (index < first.Count)
|
||||
@@ -317,21 +138,13 @@ namespace Musify.Application.Mixes
|
||||
|
||||
await database.Mixes.AddAsync(mix, cancellationToken);
|
||||
|
||||
for (var itemPosition = 0; itemPosition < draft.Items.Count; itemPosition++)
|
||||
for (var itemPosition = 0; itemPosition < draft.TrackIds.Count; itemPosition++)
|
||||
{
|
||||
var item = draft.Items[itemPosition];
|
||||
await database.MixItems.AddAsync(new MixItem
|
||||
{
|
||||
MixId = mix.Id,
|
||||
Position = itemPosition,
|
||||
Source = item.Source,
|
||||
TrackId = item.TrackId,
|
||||
VideoId = item.VideoId,
|
||||
Title = item.Title,
|
||||
Artist = item.Artist,
|
||||
ThumbnailUrl = item.ThumbnailUrl,
|
||||
DurationSeconds = item.DurationSeconds,
|
||||
IsExplicit = item.IsExplicit
|
||||
TrackId = draft.TrackIds[itemPosition]
|
||||
}, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,12 +19,13 @@ namespace Musify.Application.Mixes
|
||||
.Include(mix => mix.Items)
|
||||
.SingleOrDefaultAsync(mix => mix.Id == request.MixId && mix.UserId == request.UserId, cancellationToken);
|
||||
|
||||
if (mix is null)
|
||||
if (mix == null)
|
||||
return Error.NotFound(description: $"Mix {request.MixId} was not found");
|
||||
|
||||
var items = mix.Items.OrderBy(item => item.Position).ToList();
|
||||
var orderedItems = mix.Items.OrderBy(item => item.Position).ToList();
|
||||
var items = await MixItemMapper.ToResponsesAsync(database, orderedItems, cancellationToken);
|
||||
|
||||
return MixApplicationResponse.FromEntity(mix, items.Count, items);
|
||||
return new MixApplicationResponse(mix.Id, mix.Title, mix.Subtitle, items.Count, items);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,24 +14,24 @@ namespace Musify.Application.Mixes
|
||||
{
|
||||
public async ValueTask<ErrorOr<IReadOnlyList<MixApplicationResponse>>> Handle(GetMixesByUserIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entries = await database.Mixes
|
||||
var mixes = await database.Mixes
|
||||
.AsNoTracking()
|
||||
.Where(mix => mix.UserId == request.UserId)
|
||||
.Include(mix => mix.Items)
|
||||
.OrderBy(mix => mix.Position)
|
||||
.Select(mix => new
|
||||
{
|
||||
Mix = mix,
|
||||
ItemCount = mix.Items.Count,
|
||||
CoverItems = mix.Items
|
||||
.OrderBy(item => item.Position)
|
||||
.Take(MixApplicationResponse.CoverItemCount)
|
||||
.ToList()
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return entries
|
||||
.Select(entry => MixApplicationResponse.FromEntity(entry.Mix, entry.ItemCount, entry.CoverItems))
|
||||
.ToList();
|
||||
var responses = new List<MixApplicationResponse>(mixes.Count);
|
||||
foreach (var mix in mixes)
|
||||
{
|
||||
var orderedItems = mix.Items.OrderBy(item => item.Position).ToList();
|
||||
var coverItems = await MixItemMapper.ToResponsesAsync(
|
||||
database, orderedItems.Take(MixApplicationResponse.CoverItemCount).ToList(), cancellationToken);
|
||||
|
||||
responses.Add(new MixApplicationResponse(mix.Id, mix.Title, mix.Subtitle, orderedItems.Count, coverItems));
|
||||
}
|
||||
|
||||
return responses;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Mixes.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Mixes
|
||||
{
|
||||
|
||||
internal static class MixItemMapper
|
||||
{
|
||||
public static async Task<List<MixItemApplicationResponse>> ToResponsesAsync(
|
||||
IDatabase database,
|
||||
IReadOnlyList<MixItem> orderedItems,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var trackIds = orderedItems.Select(item => item.TrackId).Distinct().ToList();
|
||||
|
||||
var tracksById = await database.Tracks
|
||||
.AsNoTracking()
|
||||
.Include(track => track.Owner)
|
||||
.Where(track => trackIds.Contains(track.Id))
|
||||
.Select(track => new { Track = track, ListensCount = track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToDictionaryAsync(x => x.Track.Id, cancellationToken);
|
||||
|
||||
return orderedItems
|
||||
.Where(item => tracksById.ContainsKey(item.TrackId))
|
||||
.Select(item =>
|
||||
{
|
||||
var entry = tracksById[item.TrackId];
|
||||
return new MixItemApplicationResponse(
|
||||
item.TrackId,
|
||||
entry.Track.Title,
|
||||
entry.Track.Owner.Name,
|
||||
entry.Track.DurationSeconds,
|
||||
entry.ListensCount);
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Mixes.Responses
|
||||
{
|
||||
public record MixApplicationResponse(
|
||||
@@ -10,16 +8,5 @@ namespace Musify.Application.Mixes.Responses
|
||||
IReadOnlyList<MixItemApplicationResponse> Items)
|
||||
{
|
||||
public const int CoverItemCount = 4;
|
||||
|
||||
public static MixApplicationResponse FromEntity(
|
||||
Mix mix,
|
||||
int itemCount,
|
||||
IReadOnlyList<MixItem> items) =>
|
||||
new(
|
||||
mix.Id,
|
||||
mix.Title,
|
||||
mix.Subtitle,
|
||||
itemCount,
|
||||
[.. items.Select(MixItemApplicationResponse.FromEntity)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,9 @@
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Mixes.Responses
|
||||
{
|
||||
public record MixItemApplicationResponse(
|
||||
MixItemSource Source,
|
||||
Guid? TrackId,
|
||||
string? VideoId,
|
||||
Guid TrackId,
|
||||
string Title,
|
||||
string? Artist,
|
||||
string? ThumbnailUrl,
|
||||
double DurationSeconds,
|
||||
bool IsExplicit)
|
||||
{
|
||||
public static MixItemApplicationResponse FromEntity(MixItem item) =>
|
||||
new(
|
||||
item.Source,
|
||||
item.TrackId,
|
||||
item.VideoId,
|
||||
item.Title ?? string.Empty,
|
||||
item.Artist,
|
||||
item.ThumbnailUrl,
|
||||
item.DurationSeconds,
|
||||
item.IsExplicit);
|
||||
}
|
||||
int ListensCount);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
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
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (playList.UserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} is not the owner of playlist {PlayListId}", request.UserId, request.PlayListId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var albumExists = await database.Albums
|
||||
.AsNoTracking()
|
||||
.AnyAsync(album => album.Id == request.AlbumId, cancellationToken);
|
||||
if (!albumExists)
|
||||
{
|
||||
logger.LogInformation("Album {AlbumId} not found", request.AlbumId);
|
||||
return Error.NotFound(description: $"Album {request.AlbumId} not found");
|
||||
}
|
||||
|
||||
var albumTrackIds = await database.AlbumHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(albumTrack => albumTrack.AlbumId == request.AlbumId)
|
||||
.OrderBy(albumTrack => albumTrack.TrackNumber)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var playListTracksQuery = database.PlayListHasTracks
|
||||
.Where(plt => plt.PlayListId == request.PlayListId);
|
||||
|
||||
var existingTrackIds = (await playListTracksQuery
|
||||
.Select(plt => plt.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(plt => plt.Position, cancellationToken) + 1
|
||||
: 0;
|
||||
|
||||
await database.PlayListHasTracks.AddRangeAsync(
|
||||
newTrackIds.Select((trackId, index) => new PlayListHasTrack
|
||||
{
|
||||
PlayListId = request.PlayListId,
|
||||
TrackId = trackId,
|
||||
Position = nextPosition + index
|
||||
}),
|
||||
cancellationToken);
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Added {Count} tracks from album {AlbumId} to playlist {PlayListId}",
|
||||
newTrackIds.Count, request.AlbumId, request.PlayListId);
|
||||
|
||||
return new AddAlbumToPlayListResponse(newTrackIds.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ namespace Musify.Application.PlayLists
|
||||
{
|
||||
var playList = await database.PlayLists
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
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.Services;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record AddYouTubeTrackToPlayListCommand(
|
||||
long UserId,
|
||||
Guid PlayListId,
|
||||
string VideoId)
|
||||
: ICommand<ErrorOr<TrackApplicationResponse>>;
|
||||
|
||||
public class AddYouTubeTrackToPlayListCommandHandler(
|
||||
IDatabase database,
|
||||
IEventBus eventBus,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
YouTubeTrackProvisioner provisioner,
|
||||
ApplicationStorageConfiguration storageConfiguration,
|
||||
TrackConfiguration trackConfiguration,
|
||||
ILogger<AddYouTubeTrackToPlayListCommandHandler> logger)
|
||||
: ICommandHandler<AddYouTubeTrackToPlayListCommand, ErrorOr<TrackApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(AddYouTubeTrackToPlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playList = await database.PlayLists.AsNoTracking()
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (playList.UserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} is not the owner of playlist {PlayListId}", request.UserId, request.PlayListId);
|
||||
return Error.Unauthorized();
|
||||
}
|
||||
|
||||
var provisionResult = await provisioner.GetOrCreateAsync(request.VideoId, cancellationToken);
|
||||
if (provisionResult.IsError)
|
||||
return provisionResult.Errors;
|
||||
|
||||
var track = provisionResult.Value.Track;
|
||||
|
||||
var failed = track.Audio.IsFailed;
|
||||
var neverQueued = !track.Audio.DownloadRequested && !track.Audio.IsProcessed;
|
||||
if (failed || neverQueued)
|
||||
{
|
||||
if (failed)
|
||||
{
|
||||
track.Audio.TranscodeStatus = ProcessingStatus.Pending;
|
||||
track.Pictures.ProcessingStatus = ProcessingStatus.Pending;
|
||||
track.LifeCycleStatus = LifeCycleStatus.Active;
|
||||
track.Audio.RetryCount += 1;
|
||||
track.Audio.LastRetryAt = DateTime.UtcNow;
|
||||
}
|
||||
track.Audio.DownloadRequested = true;
|
||||
|
||||
var thumbnailUrl = await ResolveThumbnailUrlAsync(request.VideoId, provisionResult.Value.Song, cancellationToken);
|
||||
if (thumbnailUrl.IsError)
|
||||
return thumbnailUrl.Errors;
|
||||
|
||||
await PublishDownloadEventAsync(track.Id, request.VideoId, thumbnailUrl.Value, cancellationToken);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
logger.LogInformation("Queued YouTube track {VideoId} for download", request.VideoId);
|
||||
}
|
||||
|
||||
var alreadyAdded = await database.PlayListHasTracks.AsNoTracking()
|
||||
.AnyAsync(plt => plt.PlayListId == request.PlayListId && plt.TrackId == track.Id, cancellationToken);
|
||||
if (alreadyAdded)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} already in playlist {PlayListId}", track.Id, request.PlayListId);
|
||||
return Error.Conflict(description: "Track is already in the playlist.");
|
||||
}
|
||||
|
||||
var playListTracksQuery = database.PlayListHasTracks
|
||||
.Where(plt => plt.PlayListId == request.PlayListId);
|
||||
|
||||
var hasTracks = await playListTracksQuery.AnyAsync(cancellationToken);
|
||||
var nextPosition = hasTracks
|
||||
? await playListTracksQuery.MaxAsync(plt => plt.Position, cancellationToken) + 1
|
||||
: 0;
|
||||
|
||||
await database.PlayListHasTracks.AddAsync(new PlayListHasTrack
|
||||
{
|
||||
PlayListId = request.PlayListId,
|
||||
TrackId = track.Id,
|
||||
Position = nextPosition
|
||||
}, cancellationToken);
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Added YouTube track {VideoId} ({TrackId}) to playlist {PlayListId} at position {Position}",
|
||||
request.VideoId, track.Id, request.PlayListId, nextPosition);
|
||||
|
||||
var listensCount = await database.ListeningHistories.AsNoTracking()
|
||||
.CountAsync(lh => lh.TrackId == track.Id, cancellationToken);
|
||||
|
||||
return TrackApplicationResponse.FromEntity(track, listensCount);
|
||||
}
|
||||
|
||||
private async Task<ErrorOr<string>> ResolveThumbnailUrlAsync(string videoId, YouTubeSongResult? song, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(song?.ThumbnailUrl))
|
||||
return youTubeMusicService.ResolveArtworkUrl(song.ThumbnailUrl);
|
||||
|
||||
var songResult = await youTubeMusicService.GetSongAsync(videoId, cancellationToken);
|
||||
if (songResult.IsError)
|
||||
return songResult.Errors;
|
||||
|
||||
return youTubeMusicService.ResolveArtworkUrl(songResult.Value.ThumbnailUrl);
|
||||
}
|
||||
|
||||
private async Task PublishDownloadEventAsync(Guid trackId, string videoId, string thumbnailUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
var audioProcessedFolderKey = trackConfiguration.Routes.BuildProcessedAudioPath(Guid.NewGuid().ToString());
|
||||
|
||||
await eventBus.PublishAsync(
|
||||
new DownloadYouTubeTrackEvent(
|
||||
trackId,
|
||||
videoId,
|
||||
thumbnailUrl,
|
||||
storageConfiguration.Bucket,
|
||||
audioProcessedFolderKey,
|
||||
new ImageSize(
|
||||
trackConfiguration.Routes.SmallPicturesPath,
|
||||
trackConfiguration.PicturesSizes.SmallPictureWidth,
|
||||
trackConfiguration.PicturesSizes.SmallPictureHeight),
|
||||
new ImageSize(
|
||||
trackConfiguration.Routes.MediumPicturesPath,
|
||||
trackConfiguration.PicturesSizes.MediumPictureWidth,
|
||||
trackConfiguration.PicturesSizes.MediumPictureHeight),
|
||||
new ImageSize(
|
||||
trackConfiguration.Routes.LargePicturesPath,
|
||||
trackConfiguration.PicturesSizes.LargePictureWidth,
|
||||
trackConfiguration.PicturesSizes.LargePictureHeight)),
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ namespace Musify.Application.PlayLists
|
||||
long UserId,
|
||||
string Name,
|
||||
string? Description,
|
||||
Guid? PictureIntentId)
|
||||
Guid? PictureIntentId,
|
||||
PlaylistVisibility Visibility = PlaylistVisibility.Private)
|
||||
: ICommand<ErrorOr<PlayListApplicationResponse>>;
|
||||
|
||||
public class CreatePlayListCommandHandler(
|
||||
@@ -30,7 +31,7 @@ namespace Musify.Application.PlayLists
|
||||
UploadIntentConfiguration uploadIntentConfiguration)
|
||||
: ICommandHandler<CreatePlayListCommand, ErrorOr<PlayListApplicationResponse>>
|
||||
{
|
||||
private sealed record ResolvedPlayListPictures(PlayListPictures Pictures, UploadIntent? Intent);
|
||||
private sealed record ResolvedPlayListPictures(PlayListPictures? Pictures, UploadIntent? Intent);
|
||||
|
||||
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(CreatePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -55,13 +56,14 @@ namespace Musify.Application.PlayLists
|
||||
Name = request.Name,
|
||||
NormalizedName = request.Name.Trim().ToUpperInvariant(),
|
||||
Description = string.IsNullOrWhiteSpace(request.Description) ? null : request.Description.Trim(),
|
||||
Pictures = resolvedPictures.Pictures
|
||||
Pictures = resolvedPictures.Pictures,
|
||||
Visibility = request.Visibility
|
||||
};
|
||||
await database.PlayLists.AddAsync(playList, cancellationToken);
|
||||
|
||||
if (resolvedPictures.Intent != null)
|
||||
{
|
||||
var finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, resolvedPictures.Pictures.OriginalName);
|
||||
var finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, resolvedPictures.Pictures!.OriginalName);
|
||||
var publishResult = await PublishCreatePlayListEventAsync(playList.Id, resolvedPictures.Intent, finalPictureKey, cancellationToken);
|
||||
if (publishResult.IsError)
|
||||
return publishResult.Errors;
|
||||
@@ -86,13 +88,7 @@ namespace Musify.Application.PlayLists
|
||||
{
|
||||
if (!request.PictureIntentId.HasValue)
|
||||
{
|
||||
return new ResolvedPlayListPictures(new PlayListPictures
|
||||
{
|
||||
OriginalName = playListConfiguration.Routes.PresetOriginalPicture,
|
||||
SmallName = playListConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = playListConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = playListConfiguration.Routes.PresetLargePicture
|
||||
}, null);
|
||||
return new ResolvedPlayListPictures(null, null);
|
||||
}
|
||||
|
||||
var validation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
@@ -104,13 +100,13 @@ namespace Musify.Application.PlayLists
|
||||
return new ResolvedPlayListPictures(new PlayListPictures
|
||||
{
|
||||
OriginalName = validation.Value.ObjectName,
|
||||
SmallName = playListConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = playListConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = playListConfiguration.Routes.PresetLargePicture
|
||||
SmallName = validation.Value.ObjectName,
|
||||
MediumName = validation.Value.ObjectName,
|
||||
LargeName = validation.Value.ObjectName
|
||||
}, validation.Value);
|
||||
}
|
||||
|
||||
async Task<ErrorOr<Success>> PublishCreatePlayListEventAsync(
|
||||
private async Task<ErrorOr<Success>> PublishCreatePlayListEventAsync(
|
||||
Guid playListId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace Musify.Application.PlayLists
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeletePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playList = await database.PlayLists.SingleOrDefaultAsync(p => p.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogDebug("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
|
||||
@@ -3,10 +3,11 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.PlayLists.Responses;
|
||||
using Mediator;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.PlayLists
|
||||
{
|
||||
public record GetPlayListByIdQuery(Guid Id)
|
||||
public record GetPlayListByIdQuery(Guid Id, long? RequestingUserId = null)
|
||||
: IQuery<ErrorOr<PlayListApplicationResponse>>;
|
||||
|
||||
public class GetPlayListByIdQueryHandler(IDatabase database)
|
||||
@@ -20,6 +21,8 @@ namespace Musify.Application.PlayLists
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
TrackCount = p.PlayListTracks.Count,
|
||||
DurationSeconds = p.PlayListTracks.Sum(plt => (double?)plt.Track.DurationSeconds) ?? 0,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
@@ -28,10 +31,14 @@ namespace Musify.Application.PlayLists
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (entry is null)
|
||||
if (entry == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds);
|
||||
if (entry.PlayList.Visibility == PlaylistVisibility.Private
|
||||
&& entry.PlayList.UserId != request.RequestingUserId)
|
||||
return Error.NotFound();
|
||||
|
||||
return PlayListApplicationResponse.FromEntity(entry.PlayList, entry.TrackCount, entry.DurationSeconds, entry.CoverTrackIds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace Musify.Application.PlayLists
|
||||
.Select(p => p.Pictures)
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (pictures is null)
|
||||
if (pictures == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var routes = playListConfiguration.Routes;
|
||||
|
||||
@@ -4,7 +4,6 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
|
||||
@@ -29,16 +28,15 @@ namespace Musify.Application.PlayLists
|
||||
|
||||
var tracksQuery = database.PlayListHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(plt => ((ExternalTrack)plt.Track).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(plt => ((LocalTrack)plt.Track).Owner)
|
||||
.Include(plt => plt.Track.Owner)
|
||||
.Include(plt => plt.Track.Tags)
|
||||
.Where(plt => plt.PlayListId == request.PlayListId);
|
||||
|
||||
var totalCount = await tracksQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Select(plt => new { plt.Track, ListensCount = plt.Track.ListeningHistories.Count })
|
||||
.Select(plt => new { plt.Track, ListensCount = plt.Track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
|
||||
|
||||
@@ -25,6 +25,8 @@ namespace Musify.Application.PlayLists
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
TrackCount = p.PlayListTracks.Count,
|
||||
DurationSeconds = p.PlayListTracks.Sum(plt => (double?)plt.Track.DurationSeconds) ?? 0,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
@@ -34,7 +36,7 @@ namespace Musify.Application.PlayLists
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedPlayLists = new StaticPagedList<PlayListApplicationResponse>(
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds)),
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.TrackCount, entry.DurationSeconds, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<PlayListApplicationResponse>.FromPagedList(pagedPlayLists);
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Musify.Application.PlayLists
|
||||
long UserId,
|
||||
string? Name,
|
||||
int PageNumber,
|
||||
int PageSize)
|
||||
int PageSize,
|
||||
bool OnlyPublic = false)
|
||||
: IQuery<ErrorOr<PaginatedResponse<PlayListApplicationResponse>>>;
|
||||
|
||||
public class GetPlayListsByUserIdQueryHandler(IDatabase database)
|
||||
@@ -26,6 +27,11 @@ namespace Musify.Application.PlayLists
|
||||
.AsNoTracking()
|
||||
.Where(p => p.UserId == request.UserId);
|
||||
|
||||
if (request.OnlyPublic)
|
||||
{
|
||||
playListsQuery = playListsQuery.Where(p => p.Visibility == PlaylistVisibility.Public);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(request.Name))
|
||||
{
|
||||
var normalizedName = request.Name.Trim().ToUpperInvariant();
|
||||
@@ -40,6 +46,8 @@ namespace Musify.Application.PlayLists
|
||||
.Select(p => new
|
||||
{
|
||||
PlayList = p,
|
||||
TrackCount = p.PlayListTracks.Count,
|
||||
DurationSeconds = p.PlayListTracks.Sum(plt => (double?)plt.Track.DurationSeconds) ?? 0,
|
||||
CoverTrackIds = p.PlayListTracks
|
||||
.OrderBy(plt => plt.Position)
|
||||
.Take(PlayListApplicationResponse.CoverTrackCount)
|
||||
@@ -49,7 +57,7 @@ namespace Musify.Application.PlayLists
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedPlayLists = new StaticPagedList<PlayListApplicationResponse>(
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.CoverTrackIds)),
|
||||
pagedEntities.Select(entry => PlayListApplicationResponse.FromEntity(entry.PlayList, entry.TrackCount, entry.DurationSeconds, entry.CoverTrackIds)),
|
||||
pagedEntities.PageNumber, pagedEntities.PageSize, pagedEntities.TotalItemCount);
|
||||
|
||||
return PaginatedResponse<PlayListApplicationResponse>.FromPagedList(pagedPlayLists);
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace Musify.Application.PlayLists
|
||||
{
|
||||
var playList = await database.PlayLists
|
||||
.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playList is null)
|
||||
if (playList == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -32,7 +32,7 @@ namespace Musify.Application.PlayLists
|
||||
|
||||
var link = await database.PlayListHasTracks
|
||||
.SingleOrDefaultAsync(plt => plt.PlayListId == request.PlayListId && plt.TrackId == request.TrackId, cancellationToken);
|
||||
if (link is null)
|
||||
if (link == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not in playlist {PlayListId}", request.TrackId, request.PlayListId);
|
||||
return Error.NotFound(description: "Track is not in the playlist.");
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace Musify.Application.PlayLists.Responses
|
||||
{
|
||||
public record AddAlbumToPlayListResponse(int AddedCount);
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Application.Serialization;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.PlayLists.Responses
|
||||
{
|
||||
@@ -9,6 +12,10 @@ namespace Musify.Application.PlayLists.Responses
|
||||
string? SmallImageKeyName,
|
||||
string? MediumImageKeyName,
|
||||
string? LargeImageKeyName,
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId,
|
||||
PlaylistVisibility Visibility,
|
||||
int TrackCount,
|
||||
double DurationSeconds,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
IReadOnlyList<Guid> CoverTrackIds)
|
||||
@@ -17,6 +24,8 @@ namespace Musify.Application.PlayLists.Responses
|
||||
|
||||
public static PlayListApplicationResponse FromEntity(
|
||||
PlayList playList,
|
||||
int trackCount = 0,
|
||||
double durationSeconds = 0,
|
||||
IReadOnlyList<Guid>? coverTrackIds = null)
|
||||
{
|
||||
return new PlayListApplicationResponse(
|
||||
@@ -26,6 +35,10 @@ namespace Musify.Application.PlayLists.Responses
|
||||
playList.Pictures?.SmallName,
|
||||
playList.Pictures?.MediumName,
|
||||
playList.Pictures?.LargeName,
|
||||
playList.UserId,
|
||||
playList.Visibility,
|
||||
trackCount,
|
||||
durationSeconds,
|
||||
playList.CreatedAt,
|
||||
playList.UpdatedAt,
|
||||
coverTrackIds ?? []);
|
||||
|
||||
@@ -18,7 +18,8 @@ namespace Musify.Application.PlayLists
|
||||
Guid PlayListId,
|
||||
string? NewName,
|
||||
string? NewDescription,
|
||||
Guid? NewPictureIntentId)
|
||||
Guid? NewPictureIntentId,
|
||||
PlaylistVisibility? NewVisibility = null)
|
||||
: ICommand<ErrorOr<PlayListApplicationResponse>>;
|
||||
|
||||
public class UpdatePlayListCommandHandler(
|
||||
@@ -34,7 +35,7 @@ namespace Musify.Application.PlayLists
|
||||
public async ValueTask<ErrorOr<PlayListApplicationResponse>> Handle(UpdatePlayListCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var playListEntity = await database.PlayLists.SingleOrDefaultAsync(pl => pl.Id == request.PlayListId, cancellationToken);
|
||||
if (playListEntity is null)
|
||||
if (playListEntity == null)
|
||||
{
|
||||
logger.LogInformation("Playlist {PlayListId} not found", request.PlayListId);
|
||||
return Error.NotFound();
|
||||
@@ -57,6 +58,11 @@ namespace Musify.Application.PlayLists
|
||||
playListEntity.Description = request.NewDescription;
|
||||
}
|
||||
|
||||
if (request.NewVisibility.HasValue)
|
||||
{
|
||||
playListEntity.Visibility = request.NewVisibility.Value;
|
||||
}
|
||||
|
||||
UploadIntent? pictureIntent = null;
|
||||
string? finalPictureKey = null;
|
||||
|
||||
@@ -72,15 +78,13 @@ namespace Musify.Application.PlayLists
|
||||
playListEntity.Pictures = new PlayListPictures
|
||||
{
|
||||
OriginalName = pictureIntent.ObjectName,
|
||||
SmallName = playListConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = playListConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = playListConfiguration.Routes.PresetLargePicture
|
||||
SmallName = pictureIntent.ObjectName,
|
||||
MediumName = pictureIntent.ObjectName,
|
||||
LargeName = pictureIntent.ObjectName
|
||||
};
|
||||
finalPictureKey = playListConfiguration.Routes.BuildOriginalPicturePath(request.UserId, pictureIntent.ObjectName);
|
||||
}
|
||||
|
||||
database.PlayLists.Update(playListEntity);
|
||||
|
||||
if (pictureIntent != null && finalPictureKey != null)
|
||||
{
|
||||
var publishResult = await PublishUpdatePlayListPictureSourceEventAsync(
|
||||
@@ -108,10 +112,25 @@ namespace Musify.Application.PlayLists
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Updated playlist {PlayListId}", playListEntity.Id);
|
||||
return PlayListApplicationResponse.FromEntity(playListEntity, coverTrackIds);
|
||||
var totals = await database.PlayListHasTracks
|
||||
.AsNoTracking()
|
||||
.Where(plt => plt.PlayListId == playListEntity.Id)
|
||||
.GroupBy(plt => plt.PlayListId)
|
||||
.Select(group => new
|
||||
{
|
||||
TrackCount = group.Count(),
|
||||
DurationSeconds = group.Sum(plt => plt.Track.DurationSeconds)
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
return PlayListApplicationResponse.FromEntity(
|
||||
playListEntity,
|
||||
totals?.TrackCount ?? 0,
|
||||
totals?.DurationSeconds ?? 0,
|
||||
coverTrackIds);
|
||||
}
|
||||
|
||||
async Task<ErrorOr<Success>> PublishUpdatePlayListPictureSourceEventAsync(
|
||||
private async Task<ErrorOr<Success>> PublishUpdatePlayListPictureSourceEventAsync(
|
||||
Guid playListId,
|
||||
UploadIntent pictureIntent,
|
||||
string finalPictureKey,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Musify.Application.Serialization;
|
||||
|
||||
public sealed class LongAsStringConverter : JsonConverter<long>
|
||||
{
|
||||
public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
|
||||
reader.TokenType == JsonTokenType.String
|
||||
? long.Parse(reader.GetString()!, CultureInfo.InvariantCulture)
|
||||
: reader.GetInt64();
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) =>
|
||||
writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
public sealed class NullableLongAsStringConverter : JsonConverter<long?>
|
||||
{
|
||||
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Null)
|
||||
return null;
|
||||
|
||||
return reader.TokenType == JsonTokenType.String
|
||||
? string.IsNullOrEmpty(reader.GetString()) ? null : long.Parse(reader.GetString()!, CultureInfo.InvariantCulture)
|
||||
: reader.GetInt64();
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options)
|
||||
{
|
||||
if (value.HasValue)
|
||||
writer.WriteStringValue(value.Value.ToString(CultureInfo.InvariantCulture));
|
||||
else
|
||||
writer.WriteNullValue();
|
||||
}
|
||||
}
|
||||
@@ -30,9 +30,8 @@ public sealed class TrackStreamIssuer(
|
||||
folderPath,
|
||||
streamGatewayConfiguration.AudioFileName);
|
||||
|
||||
// Anonymous listeners have no User row to satisfy ListeningHistory's foreign key against, and
|
||||
// their plays aren't "history" anyone can look back on anyway, so there's nothing to record.
|
||||
if (userId is not null)
|
||||
Guid? listenId = null;
|
||||
if (userId != null)
|
||||
{
|
||||
var newListeningHistory = new ListeningHistory
|
||||
{
|
||||
@@ -41,14 +40,15 @@ public sealed class TrackStreamIssuer(
|
||||
};
|
||||
await database.ListeningHistories.AddAsync(newListeningHistory, cancellationToken);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
listenId = newListeningHistory.Id;
|
||||
}
|
||||
|
||||
return new TrackStreamResponse(manifestUrl, ticket.Token, ticket.ExpiresInSeconds);
|
||||
return new TrackStreamResponse(manifestUrl, ticket.Token, ticket.ExpiresInSeconds, listenId);
|
||||
}
|
||||
|
||||
private long? AnonymousFragmentBytes(long? userId)
|
||||
{
|
||||
if (userId is not null || playbackConfiguration.AnonymousFragmentSeconds <= 0)
|
||||
if (userId != null || playbackConfiguration.AnonymousFragmentSeconds <= 0)
|
||||
return null;
|
||||
|
||||
return (long)playbackConfiguration.AnonymousFragmentSeconds * playbackConfiguration.EstimatedAudioBytesPerSecond;
|
||||
|
||||
@@ -42,7 +42,7 @@ public sealed class UploadIntentValidator(
|
||||
var intent = await database.UploadIntents
|
||||
.FirstOrDefaultAsync(i => i.Id == intentId, cancellationToken);
|
||||
|
||||
if (intent is null || intent.UserId != userId)
|
||||
if (intent == null || intent.UserId != userId)
|
||||
return Error.NotFound(description: "Upload intent not found or not accessible.");
|
||||
|
||||
if (intent.IsConsumed)
|
||||
@@ -52,7 +52,7 @@ public sealed class UploadIntentValidator(
|
||||
return Error.Validation(description: "Upload intent has expired.");
|
||||
|
||||
var metadata = await storageService.HeadObjectAsync(intent.Bucket, intent.Key, cancellationToken);
|
||||
if (metadata is null)
|
||||
if (metadata == null)
|
||||
return Error.NotFound(description: "Uploaded object not found in storage. Upload the file first.");
|
||||
|
||||
if (metadata.ContentLength > config.MaxUploadBytes)
|
||||
|
||||
@@ -1,265 +0,0 @@
|
||||
using ErrorOr;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Services;
|
||||
|
||||
public sealed record YouTubeTrackProvision(ExternalTrack Track, YouTubeSongResult? Song);
|
||||
|
||||
public sealed class YouTubeTrackProvisioner(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
TrackConfiguration trackConfiguration,
|
||||
ILogger<YouTubeTrackProvisioner> logger)
|
||||
{
|
||||
public Task<ExternalTrack?> FindAsync(string videoId, CancellationToken cancellationToken) =>
|
||||
database.ExternalTracks
|
||||
.Include(track => track.TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.SingleOrDefaultAsync(t => t.Source == TrackSource.YouTube && t.ExternalId == videoId, cancellationToken);
|
||||
|
||||
public async Task<ErrorOr<YouTubeTrackProvision>> GetOrCreateAsync(string videoId, CancellationToken cancellationToken)
|
||||
{
|
||||
var existing = await FindAsync(videoId, cancellationToken);
|
||||
if (existing is not null)
|
||||
return new YouTubeTrackProvision(existing, Song: null);
|
||||
|
||||
var songResult = await youTubeMusicService.GetSongAsync(videoId, cancellationToken);
|
||||
if (songResult.IsError)
|
||||
return songResult.Errors;
|
||||
|
||||
var song = songResult.Value;
|
||||
|
||||
var artistRefs = song.Artists
|
||||
.GroupBy(artistRef => artistRef.Id ?? artistRef.Name.ToUpperInvariant())
|
||||
.Select(group => group.First())
|
||||
.ToList();
|
||||
|
||||
var artists = new List<Artist>();
|
||||
foreach (var artistRef in artistRefs)
|
||||
artists.Add(await GetOrCreateArtistAsync(artistRef, cancellationToken));
|
||||
|
||||
var title = Truncate(song.Title, 200);
|
||||
var track = new ExternalTrack
|
||||
{
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
Source = TrackSource.YouTube,
|
||||
ExternalId = videoId,
|
||||
DurationSeconds = song.DurationSeconds,
|
||||
Pictures = new TrackPictures
|
||||
{
|
||||
SmallName = trackConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = trackConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = trackConfiguration.Routes.PresetLargePicture,
|
||||
ProcessingStatus = ProcessingStatus.Pending
|
||||
},
|
||||
Audio = new TrackAudio
|
||||
{
|
||||
DownloadRequested = false,
|
||||
TranscodeStatus = ProcessingStatus.Pending
|
||||
}
|
||||
};
|
||||
|
||||
await database.ExternalTracks.AddAsync(track, cancellationToken);
|
||||
|
||||
for (var position = 0; position < artists.Count; position++)
|
||||
{
|
||||
await database.TrackArtists.AddAsync(new TrackArtist
|
||||
{
|
||||
TrackId = track.Id,
|
||||
ArtistId = artists[position].Id,
|
||||
Position = position
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
logger.LogInformation("Created YouTube track {VideoId} ({TrackId})", videoId, track.Id);
|
||||
return new YouTubeTrackProvision(track, Song: song);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
database.ExternalTracks.Remove(track);
|
||||
var refetched = await FindAsync(videoId, cancellationToken);
|
||||
if (refetched is null)
|
||||
{
|
||||
logger.LogWarning("YouTube track {VideoId} creation raced but could not be refetched", videoId);
|
||||
return Error.Conflict(description: "The track was just created by another request. Retry the operation.");
|
||||
}
|
||||
return new YouTubeTrackProvision(refetched, Song: null);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task MaterializeAlbumAsync(string albumExternalId, YouTubeAlbumDetail detail, CancellationToken cancellationToken)
|
||||
{
|
||||
var validTracks = detail.Tracks
|
||||
.Where(track => !string.IsNullOrEmpty(track.VideoId))
|
||||
.ToList();
|
||||
if (validTracks.Count == 0)
|
||||
return;
|
||||
|
||||
var album = await GetOrCreateExternalAlbumAsync(albumExternalId, detail.Album.Title, detail.Album.ThumbnailUrl, cancellationToken);
|
||||
|
||||
var videoIds = validTracks.Select(track => track.VideoId).ToList();
|
||||
|
||||
var tracksByVideoId = await database.ExternalTracks
|
||||
.Where(track => track.Source == TrackSource.YouTube && videoIds.Contains(track.ExternalId))
|
||||
.ToDictionaryAsync(track => track.ExternalId, cancellationToken);
|
||||
|
||||
var linkedTrackIds = (await database.AlbumHasTracks
|
||||
.Where(albumTrack => albumTrack.AlbumId == album.Id)
|
||||
.Select(albumTrack => albumTrack.TrackId)
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToHashSet();
|
||||
|
||||
if (tracksByVideoId.Count == validTracks.Count && linkedTrackIds.Count >= validTracks.Count)
|
||||
return;
|
||||
|
||||
var artistRefs = detail.Album.Artists
|
||||
.GroupBy(artistRef => artistRef.Id ?? artistRef.Name.ToUpperInvariant())
|
||||
.Select(group => group.First())
|
||||
.ToList();
|
||||
|
||||
var albumArtists = new List<Artist>();
|
||||
foreach (var artistRef in artistRefs)
|
||||
albumArtists.Add(await GetOrCreateArtistAsync(artistRef, cancellationToken));
|
||||
|
||||
foreach (var albumTrack in validTracks)
|
||||
{
|
||||
if (!tracksByVideoId.TryGetValue(albumTrack.VideoId, out var track))
|
||||
{
|
||||
track = BuildStubTrack(albumTrack);
|
||||
await database.ExternalTracks.AddAsync(track, cancellationToken);
|
||||
|
||||
for (var position = 0; position < albumArtists.Count; position++)
|
||||
{
|
||||
await database.TrackArtists.AddAsync(new TrackArtist
|
||||
{
|
||||
TrackId = track.Id,
|
||||
ArtistId = albumArtists[position].Id,
|
||||
Position = position
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
tracksByVideoId[albumTrack.VideoId] = track;
|
||||
}
|
||||
|
||||
if (linkedTrackIds.Contains(track.Id))
|
||||
continue;
|
||||
|
||||
await database.AlbumHasTracks.AddAsync(new AlbumHasTrack
|
||||
{
|
||||
AlbumId = album.Id,
|
||||
TrackId = track.Id,
|
||||
TrackNumber = albumTrack.TrackNumber
|
||||
}, cancellationToken);
|
||||
linkedTrackIds.Add(track.Id);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
logger.LogInformation("Materialized YouTube album {AlbumId} ({TrackCount} tracks)", albumExternalId, validTracks.Count);
|
||||
}
|
||||
catch (DbUpdateException exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Race while materializing YouTube album {AlbumId}", albumExternalId);
|
||||
}
|
||||
}
|
||||
|
||||
private ExternalTrack BuildStubTrack(YouTubeAlbumTrack albumTrack)
|
||||
{
|
||||
var title = Truncate(albumTrack.Title, 200);
|
||||
return new ExternalTrack
|
||||
{
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
Source = TrackSource.YouTube,
|
||||
ExternalId = albumTrack.VideoId,
|
||||
DurationSeconds = albumTrack.DurationSeconds,
|
||||
Pictures = new TrackPictures
|
||||
{
|
||||
SmallName = trackConfiguration.Routes.PresetSmallPicture,
|
||||
MediumName = trackConfiguration.Routes.PresetMediumPicture,
|
||||
LargeName = trackConfiguration.Routes.PresetLargePicture,
|
||||
ProcessingStatus = ProcessingStatus.Pending
|
||||
},
|
||||
Audio = new TrackAudio
|
||||
{
|
||||
DownloadRequested = false,
|
||||
TranscodeStatus = ProcessingStatus.Pending
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<Artist> GetOrCreateArtistAsync(YouTubeArtistRef reference, CancellationToken cancellationToken)
|
||||
{
|
||||
var name = Truncate(reference.Name, 200);
|
||||
var normalized = name.ToUpperInvariant();
|
||||
var externalId = reference.Id ?? $"name:{normalized}";
|
||||
|
||||
var existing = await database.Artists.SingleOrDefaultAsync(a => a.ExternalId == externalId, cancellationToken);
|
||||
if (existing is not null)
|
||||
return existing;
|
||||
|
||||
var artist = new Artist
|
||||
{
|
||||
Name = name,
|
||||
NormalizedName = normalized,
|
||||
ExternalId = externalId
|
||||
};
|
||||
|
||||
await database.Artists.AddAsync(artist, cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
return artist;
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
database.Artists.Remove(artist);
|
||||
return await database.Artists.SingleAsync(a => a.ExternalId == externalId, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ExternalAlbum> GetOrCreateExternalAlbumAsync(string externalId, string name, string? thumbnailUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
var existing = await database.ExternalAlbums
|
||||
.SingleOrDefaultAsync(album => album.Source == TrackSource.YouTube && album.ExternalId == externalId, cancellationToken);
|
||||
if (existing is not null)
|
||||
return existing;
|
||||
|
||||
var title = Truncate(name, 200);
|
||||
var album = new ExternalAlbum
|
||||
{
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
Source = TrackSource.YouTube,
|
||||
ExternalId = externalId,
|
||||
ThumbnailUrl = string.IsNullOrEmpty(thumbnailUrl) ? null : Truncate(thumbnailUrl, 512)
|
||||
};
|
||||
|
||||
await database.ExternalAlbums.AddAsync(album, cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
return album;
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
database.ExternalAlbums.Remove(album);
|
||||
return await database.ExternalAlbums.SingleAsync(a => a.Source == TrackSource.YouTube && a.ExternalId == externalId, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Truncate(string value, int maxLength) =>
|
||||
value.Length <= maxLength ? value : value[..maxLength];
|
||||
}
|
||||
@@ -17,7 +17,9 @@ namespace Musify.Application.Tracks
|
||||
long UserId,
|
||||
string Title,
|
||||
Guid PictureIntentId,
|
||||
Guid AudioIntentId)
|
||||
Guid AudioIntentId,
|
||||
IReadOnlyCollection<Genre> Tags,
|
||||
bool IsExplicit = false)
|
||||
: ICommand<ErrorOr<TrackApplicationResponse>>;
|
||||
|
||||
public class CreateTrackCommandHandler(
|
||||
@@ -34,12 +36,29 @@ namespace Musify.Application.Tracks
|
||||
{
|
||||
var user = await database.Users
|
||||
.SingleOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
|
||||
if (user is null)
|
||||
if (user == null)
|
||||
{
|
||||
logger.LogWarning("User {UserId} not found", request.UserId);
|
||||
return Error.NotFound(description: $"User {request.UserId} not found");
|
||||
}
|
||||
|
||||
var distinctTags = request.Tags.Distinct().ToList();
|
||||
if (distinctTags.Count == 0)
|
||||
{
|
||||
logger.LogWarning("Track {Title} was submitted without any tags", request.Title);
|
||||
return Error.Validation(description: "At least one tag is required.");
|
||||
}
|
||||
|
||||
var tagConflicts = GenreCompatibility.FindConflicts(distinctTags);
|
||||
if (tagConflicts.Count > 0)
|
||||
{
|
||||
var conflict = tagConflicts.First();
|
||||
logger.LogWarning(
|
||||
"Track {Title} was submitted with incompatible tags {First} and {Second}",
|
||||
request.Title, conflict.First, conflict.Second);
|
||||
return Error.Validation(description: $"Tags '{conflict.First}' and '{conflict.Second}' are not compatible.");
|
||||
}
|
||||
|
||||
var pictureValidation = await uploadIntentValidator.ValidateAndLoadAsync(
|
||||
uploadIntentConfiguration,
|
||||
request.PictureIntentId, request.UserId, cancellationToken);
|
||||
@@ -59,12 +78,13 @@ namespace Musify.Application.Tracks
|
||||
var finalAudioKey = trackConfiguration.Routes.BuildOriginalAudioPath(request.UserId, audioIntent.ObjectName);
|
||||
var audioProcessedFolderKey = trackConfiguration.Routes.BuildProcessedAudioPath(Guid.NewGuid().ToString());
|
||||
|
||||
var trackEntity = new LocalTrack
|
||||
var trackEntity = new Track
|
||||
{
|
||||
Title = request.Title,
|
||||
NormalizedTitle = request.Title.ToUpperInvariant(),
|
||||
OwnerUserId = user.Id,
|
||||
Owner = user,
|
||||
IsExplicit = request.IsExplicit,
|
||||
Pictures = new TrackPictures
|
||||
{
|
||||
OriginalName = pictureIntent.ObjectName,
|
||||
@@ -80,7 +100,11 @@ namespace Musify.Application.Tracks
|
||||
}
|
||||
};
|
||||
|
||||
await database.LocalTracks.AddAsync(trackEntity, cancellationToken);
|
||||
trackEntity.Tags = distinctTags
|
||||
.Select(tag => new TrackTag { TrackId = trackEntity.Id, Tag = tag })
|
||||
.ToList();
|
||||
|
||||
await database.Tracks.AddAsync(trackEntity, cancellationToken);
|
||||
|
||||
await database.UserHasTracks.AddAsync(new UserHasTrack
|
||||
{
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record DeleteStaleUncountedListensCommand : ICommand<int>;
|
||||
|
||||
public class DeleteStaleUncountedListensCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<DeleteStaleUncountedListensCommandHandler> logger)
|
||||
: ICommandHandler<DeleteStaleUncountedListensCommand, int>
|
||||
{
|
||||
public async ValueTask<int> Handle(DeleteStaleUncountedListensCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var cutoff = DateTime.UtcNow.AddDays(-ListeningRules.UncountedRetentionDays);
|
||||
|
||||
var stale = await database.ListeningHistories
|
||||
.Where(l => !l.IsCounted && l.ListenedAt < cutoff)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (stale.Count == 0)
|
||||
return 0;
|
||||
|
||||
database.ListeningHistories.RemoveRange(stale);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("Deleted {Count} uncounted listens older than {Days} days", stale.Count, ListeningRules.UncountedRetentionDays);
|
||||
return stale.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,13 +23,13 @@ namespace Musify.Application.Tracks
|
||||
public async ValueTask<ErrorOr<Success>> Handle(DeleteTrackCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var track = await database.Tracks.SingleOrDefaultAsync(t => t.Id == request.TrackId, cancellationToken);
|
||||
if (track is null)
|
||||
if (track == null)
|
||||
{
|
||||
logger.LogInformation("Track {TrackId} not found", request.TrackId);
|
||||
return Error.NotFound();
|
||||
}
|
||||
|
||||
if (track is not LocalTrack localTrack || localTrack.OwnerUserId != request.UserId)
|
||||
if (track.OwnerUserId != request.UserId)
|
||||
{
|
||||
logger.LogWarning("User {UserId} unauthorized to delete track {TrackId}", request.UserId, request.TrackId);
|
||||
return Error.Unauthorized();
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record GetLastTrackListenedByUserIdQuery(long UserId) : IQuery<ErrorOr<TrackApplicationResponse>>;
|
||||
|
||||
public class GetLastTrackListenedByUserIdQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetLastTrackListenedByUserIdQuery, ErrorOr<TrackApplicationResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(GetLastTrackListenedByUserIdQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var track = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Include(t => t.Track.Owner)
|
||||
.Include(t => t.Track.Tags)
|
||||
.Where(t => t.UserId == query.UserId)
|
||||
.OrderByDescending(t => t.ListenedAt)
|
||||
.Select(t => TrackApplicationResponse.FromEntity(t.Track, t.Track.ListeningHistories.Count(l => l.IsCounted)))
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
return track == null
|
||||
? Error.NotFound("Track.NotFound", "No track found for the given user ID.")
|
||||
: track;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
@@ -17,7 +16,8 @@ namespace Musify.Application.Tracks
|
||||
public async ValueTask<IEnumerable<TrackApplicationResponse>> Handle(GetListeningHistoryQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var recentTrackIds = await database.ListeningHistories
|
||||
.Where(l => l.UserId == query.UserId)
|
||||
.AsNoTracking()
|
||||
.Where(l => l.UserId == query.UserId && l.IsCounted)
|
||||
.GroupBy(l => l.TrackId)
|
||||
.OrderByDescending(g => g.Max(l => l.ListenedAt))
|
||||
.Select(g => g.Key)
|
||||
@@ -25,11 +25,11 @@ namespace Musify.Application.Tracks
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var tracksById = await database.Tracks
|
||||
.Include(t => ((ExternalTrack)t).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(t => ((LocalTrack)t).Owner)
|
||||
.AsNoTracking()
|
||||
.Include(t => t.Owner)
|
||||
.Include(t => t.Tags)
|
||||
.Where(t => recentTrackIds.Contains(t.Id))
|
||||
.Select(t => new { t.Id, Track = t, ListensCount = t.ListeningHistories.Count } )
|
||||
.Select(t => new { t.Id, Track = t, ListensCount = t.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToDictionaryAsync(t => t.Id, cancellationToken);
|
||||
|
||||
return recentTrackIds
|
||||
|
||||
@@ -3,7 +3,6 @@ using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
@@ -16,14 +15,13 @@ namespace Musify.Application.Tracks
|
||||
public async ValueTask<ErrorOr<TrackApplicationResponse>> Handle(GetTrackByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await database.Tracks.AsNoTracking()
|
||||
.Include(t => ((ExternalTrack)t).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(t => ((LocalTrack)t).Owner)
|
||||
.Include(t => t.Owner)
|
||||
.Include(t => t.Tags)
|
||||
.Where(t => t.Id == request.TrackId)
|
||||
.Select(t => new { Track = t, ListensCount = t.ListeningHistories.Count })
|
||||
.Select(t => new { Track = t, ListensCount = t.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (entity is null)
|
||||
if (entity == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return TrackApplicationResponse.FromEntity(entity.Track, entity.ListensCount);
|
||||
|
||||
@@ -9,8 +9,7 @@ using Musify.Application.Tracks.Responses;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
/// <param name="UserId">Null for an anonymous request — allowed only when
|
||||
/// <see cref="PlaybackConfiguration.AllowAnonymousListening"/> is enabled.</param>
|
||||
|
||||
public record GetTrackStreamQuery(Guid TrackId, long? UserId)
|
||||
: IQuery<ErrorOr<TrackStreamResponse>>;
|
||||
|
||||
@@ -23,7 +22,7 @@ namespace Musify.Application.Tracks
|
||||
{
|
||||
public async ValueTask<ErrorOr<TrackStreamResponse>> Handle(GetTrackStreamQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.UserId is null && !playbackConfiguration.AllowAnonymousListening)
|
||||
if (request.UserId == null && !playbackConfiguration.AllowAnonymousListening)
|
||||
return Error.Unauthorized(description: "Sign in to stream music, or ask an administrator to enable anonymous listening.");
|
||||
|
||||
var track = await database.Tracks.AsNoTracking()
|
||||
|
||||
@@ -1,37 +1,26 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Tracks.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record GetTracksQuery(string? Name, int PageNumber, int PageSize, string? YoutubeContinuationToken = null)
|
||||
public record GetTracksQuery(string? Name, int PageNumber, int PageSize, Genre? Genre = null)
|
||||
: IQuery<ErrorOr<TracksSearchResponse>>;
|
||||
|
||||
public class GetTracksQueryHandler(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
ILogger<GetTracksQueryHandler> logger)
|
||||
public class GetTracksQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetTracksQuery, ErrorOr<TracksSearchResponse>>
|
||||
{
|
||||
// Mirrors the web client's search-box debounce threshold: a query shorter than this is too
|
||||
// likely to still be mid-keystroke to justify a live call to the YouTube Music API for every
|
||||
// client that hits this endpoint.
|
||||
private const int MinNameLengthForYouTubeSearch = 2;
|
||||
|
||||
public async ValueTask<ErrorOr<TracksSearchResponse>> Handle(GetTracksQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tracksQuery = database.UserHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(ut => ((ExternalTrack)ut.Track).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(ut => ((LocalTrack)ut.Track).Owner)
|
||||
.Include(ut => ut.Track.Owner)
|
||||
.Include(ut => ut.Track.Tags)
|
||||
.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrEmpty(request.Name))
|
||||
@@ -40,69 +29,29 @@ namespace Musify.Application.Tracks
|
||||
tracksQuery = tracksQuery.Where(t => t.Track.NormalizedTitle.Contains(normalizedName));
|
||||
}
|
||||
|
||||
if (request.Genre is { } genre)
|
||||
tracksQuery = tracksQuery.Where(t => t.Track.Tags.Any(tag => tag.Tag == genre));
|
||||
|
||||
var totalCount = await tracksQuery.CountAsync(cancellationToken);
|
||||
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderByDescending(t => t.Track.CreatedAt)
|
||||
.ThenBy(t => t.Id)
|
||||
.Select(t => new { t.Track, ListensCount = t.Track.ListeningHistories.Count })
|
||||
.Select(t => new { t.Track, ListensCount = t.Track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
var localItems = pagedEntities
|
||||
var items = pagedEntities
|
||||
.Select(x => TrackSearchItemResponse.FromTrack(TrackApplicationResponse.FromEntity(x.Track, x.ListensCount)))
|
||||
.ToList();
|
||||
|
||||
var knownVideoIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in pagedEntities)
|
||||
{
|
||||
if (entry.Track is ExternalTrack { Source: TrackSource.YouTube } external)
|
||||
knownVideoIds.Add(external.ExternalId);
|
||||
}
|
||||
|
||||
var youtubeItems = new List<TrackSearchItemResponse>();
|
||||
string? nextContinuationToken = null;
|
||||
var youtubeUnavailable = false;
|
||||
|
||||
if (request.Name?.Trim().Length >= MinNameLengthForYouTubeSearch)
|
||||
(youtubeItems, nextContinuationToken, youtubeUnavailable) =
|
||||
await SearchYouTubeAsync(request.Name, request.YoutubeContinuationToken, knownVideoIds, cancellationToken);
|
||||
|
||||
return TracksSearchResponse.Create(
|
||||
[.. localItems, .. youtubeItems],
|
||||
return new TracksSearchResponse(
|
||||
items,
|
||||
pagedEntities.PageNumber,
|
||||
pagedEntities.PageSize,
|
||||
pagedEntities.PageCount,
|
||||
pagedEntities.TotalItemCount,
|
||||
pagedEntities.HasPreviousPage,
|
||||
pagedEntities.HasNextPage,
|
||||
nextContinuationToken,
|
||||
youtubeUnavailable);
|
||||
}
|
||||
|
||||
private async Task<(List<TrackSearchItemResponse> Items, string? NextContinuationToken, bool Unavailable)> SearchYouTubeAsync(
|
||||
string name,
|
||||
string? continuationToken,
|
||||
HashSet<string> knownVideoIds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var searchResult = await youTubeMusicService.SearchSongsAsync(name, continuationToken ?? string.Empty, cancellationToken);
|
||||
if (searchResult.IsError)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"YouTube search unavailable while combining track results: {Error}", searchResult.FirstError.Description);
|
||||
return ([], null, true);
|
||||
}
|
||||
|
||||
var items = searchResult.Value.Items
|
||||
.Where(song => knownVideoIds.Add(song.VideoId))
|
||||
.Select(TrackSearchItemResponse.FromYouTubeSong)
|
||||
.ToList();
|
||||
|
||||
var nextToken = string.IsNullOrEmpty(searchResult.Value.ContinuationToken)
|
||||
? null
|
||||
: searchResult.Value.ContinuationToken;
|
||||
|
||||
return (items, nextToken, false);
|
||||
pagedEntities.HasNextPage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ using Musify.Application.Tracks.Responses;
|
||||
using X.PagedList;
|
||||
using X.PagedList.EF;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
@@ -27,9 +26,8 @@ namespace Musify.Application.Tracks
|
||||
|
||||
var tracksQuery = database.UserHasTracks
|
||||
.AsNoTracking()
|
||||
.Include(ut => ((ExternalTrack)ut.Track).TrackArtists)
|
||||
.ThenInclude(trackArtist => trackArtist.Artist)
|
||||
.Include(ut => ((LocalTrack)ut.Track).Owner)
|
||||
.Include(ut => ut.Track.Owner)
|
||||
.Include(ut => ut.Track.Tags)
|
||||
.Where(p => p.UserId == request.UserId);
|
||||
|
||||
if (!string.IsNullOrEmpty(request.Name))
|
||||
@@ -42,7 +40,7 @@ namespace Musify.Application.Tracks
|
||||
|
||||
var pagedEntities = await tracksQuery
|
||||
.OrderBy(t => t.Track.CreatedAt)
|
||||
.Select(t => new { t.Track, ListensCount = t.Track.ListeningHistories.Count })
|
||||
.Select(t => new { t.Track, ListensCount = t.Track.ListeningHistories.Count(l => l.IsCounted) })
|
||||
.ToPagedListAsync(pageNumber, pageSize, totalCount, cancellationToken);
|
||||
|
||||
var pagedTracks = new StaticPagedList<TrackApplicationResponse>(
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public static class ListeningRules
|
||||
{
|
||||
public const double CountedThresholdSeconds = 30;
|
||||
public const double CountedThresholdFraction = 0.5;
|
||||
public const double DurationToleranceSeconds = 2;
|
||||
public const double ClockToleranceSeconds = 5;
|
||||
public const int UncountedRetentionDays = 8;
|
||||
|
||||
public static double CountedThreshold(double durationSeconds) =>
|
||||
Math.Min(CountedThresholdSeconds, durationSeconds * CountedThresholdFraction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Tracks
|
||||
{
|
||||
public record RecordListeningProgressCommand(
|
||||
long UserId,
|
||||
Guid ListenId,
|
||||
double PlayedSeconds)
|
||||
: ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class RecordListeningProgressCommandHandler(IDatabase database)
|
||||
: ICommandHandler<RecordListeningProgressCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(RecordListeningProgressCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!double.IsFinite(request.PlayedSeconds) || request.PlayedSeconds < 0)
|
||||
return Error.Validation(description: "playedSeconds must be a non-negative number.");
|
||||
|
||||
var listen = await database.ListeningHistories
|
||||
.Include(l => l.Track)
|
||||
.SingleOrDefaultAsync(l => l.Id == request.ListenId && l.UserId == request.UserId, cancellationToken);
|
||||
|
||||
if (listen == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var durationCap = listen.Track.DurationSeconds + ListeningRules.DurationToleranceSeconds;
|
||||
var clockCap = (now - listen.ListenedAt).TotalSeconds + ListeningRules.ClockToleranceSeconds;
|
||||
var accepted = Math.Min(request.PlayedSeconds, Math.Min(durationCap, clockCap));
|
||||
|
||||
listen.PlayedSeconds = Math.Max(listen.PlayedSeconds ?? 0, accepted);
|
||||
listen.LastProgressAt = now;
|
||||
listen.IsCounted = listen.IsCounted
|
||||
|| listen.PlayedSeconds >= ListeningRules.CountedThreshold(listen.Track.DurationSeconds);
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Tracks.Responses
|
||||
{
|
||||
public record ExternalTrackApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Artist,
|
||||
ProcessingStatus AudioStatus,
|
||||
double Duration,
|
||||
int ListensCount,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
string ExternalId)
|
||||
: TrackApplicationResponse(Id, Title, Artist, AudioStatus, Duration, ListensCount, CreatedAt, UpdatedAt)
|
||||
{
|
||||
public static ExternalTrackApplicationResponse FromEntity(ExternalTrack track, int listensCount) =>
|
||||
new(
|
||||
track.Id,
|
||||
track.Title,
|
||||
FormatArtist(track),
|
||||
track.Audio.TranscodeStatus,
|
||||
track.DurationSeconds,
|
||||
listensCount,
|
||||
track.CreatedAt,
|
||||
track.UpdatedAt,
|
||||
track.ExternalId);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Tracks.Responses
|
||||
{
|
||||
public record LocalTrackApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Artist,
|
||||
ProcessingStatus AudioStatus,
|
||||
double Duration,
|
||||
int ListensCount,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt,
|
||||
long OwnerUserId)
|
||||
: TrackApplicationResponse(Id, Title, Artist, AudioStatus, Duration, ListensCount, CreatedAt, UpdatedAt)
|
||||
{
|
||||
public static LocalTrackApplicationResponse FromEntity(LocalTrack track, int listensCount) =>
|
||||
new(
|
||||
track.Id,
|
||||
track.Title,
|
||||
FormatArtist(track),
|
||||
track.Audio.TranscodeStatus,
|
||||
track.DurationSeconds,
|
||||
listensCount,
|
||||
track.CreatedAt,
|
||||
track.UpdatedAt,
|
||||
track.OwnerUserId);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,11 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Application.Serialization;
|
||||
using Musify.Domain.Entities;
|
||||
using Musify.Domain.ValueObjects;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Musify.Application.Tracks.Responses
|
||||
{
|
||||
// See AlbumApplicationResponse for why [JsonPolymorphic]/[JsonDerivedType] are required
|
||||
// (not optional) whenever a base type carries subtype-only data across the wire. Track is a
|
||||
// cleaner case than Album: both OwnerUserId (local-only) and ExternalId (external-only) are
|
||||
// genuinely exclusive to one side, so the base has no "meaningless sentinel" field at all —
|
||||
// every real value is one of the two derived types, hence base is abstract.
|
||||
//
|
||||
// No explicit Source property here (unlike the domain entities): STJ's polymorphism support
|
||||
// already injects a "source" discriminator property with the same "Local"/"YouTube" values a
|
||||
// hand-written TrackSource field would have, and a real property with that exact name would
|
||||
// collide with it ("contains property 'source' that conflicts with an existing metadata
|
||||
// property name"). Use the discriminator (or a type check) instead of a Source field.
|
||||
[JsonPolymorphic(TypeDiscriminatorPropertyName = "source")]
|
||||
[JsonDerivedType(typeof(LocalTrackApplicationResponse), typeDiscriminator: "Local")]
|
||||
[JsonDerivedType(typeof(ExternalTrackApplicationResponse), typeDiscriminator: "YouTube")]
|
||||
public abstract record TrackApplicationResponse(
|
||||
public record TrackApplicationResponse(
|
||||
Guid Id,
|
||||
string Title,
|
||||
string? Artist,
|
||||
@@ -26,24 +13,23 @@ namespace Musify.Application.Tracks.Responses
|
||||
double Duration,
|
||||
int ListensCount,
|
||||
DateTime CreatedAt,
|
||||
DateTime UpdatedAt)
|
||||
DateTime UpdatedAt,
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long OwnerUserId,
|
||||
IReadOnlyCollection<Genre> Tags,
|
||||
bool IsExplicit)
|
||||
{
|
||||
public static TrackApplicationResponse FromEntity(Track track, int listensCount) =>
|
||||
track switch
|
||||
{
|
||||
LocalTrack local => LocalTrackApplicationResponse.FromEntity(local, listensCount),
|
||||
ExternalTrack external => ExternalTrackApplicationResponse.FromEntity(external, listensCount),
|
||||
_ => throw new NotSupportedException($"Unsupported track entity type '{track.GetType().Name}'.")
|
||||
};
|
||||
|
||||
protected static string? FormatArtist(Track track) => track switch
|
||||
{
|
||||
LocalTrack local => local.Owner.Name,
|
||||
ExternalTrack { TrackArtists.Count: > 0 } external =>
|
||||
string.Join(", ", external.TrackArtists
|
||||
.OrderBy(trackArtist => trackArtist.Position)
|
||||
.Select(trackArtist => trackArtist.Artist.Name)),
|
||||
_ => null
|
||||
};
|
||||
new(
|
||||
track.Id,
|
||||
track.Title,
|
||||
track.Owner.Name,
|
||||
track.Audio.TranscodeStatus,
|
||||
track.DurationSeconds,
|
||||
listensCount,
|
||||
track.CreatedAt,
|
||||
track.UpdatedAt,
|
||||
track.OwnerUserId,
|
||||
track.Tags.Select(tag => tag.Tag).ToList(),
|
||||
track.IsExplicit);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Application.Tracks.Responses
|
||||
{
|
||||
/// <summary>One item of a combined local/YouTube track listing. Exactly one of
|
||||
/// <see cref="Track"/> or <see cref="YouTubeSong"/> is populated: <see cref="Track"/> for
|
||||
/// anything already in the catalog (local uploads and YouTube tracks provisioned earlier),
|
||||
/// <see cref="YouTubeSong"/> for a live YouTube Music search hit that has not been
|
||||
/// provisioned yet, so it has no track id.</summary>
|
||||
public record TrackSearchItemResponse(
|
||||
TrackSource Source,
|
||||
TrackApplicationResponse? Track,
|
||||
YouTubeSongResult? YouTubeSong)
|
||||
public record TrackSearchItemResponse(TrackApplicationResponse Track)
|
||||
{
|
||||
public static TrackSearchItemResponse FromTrack(TrackApplicationResponse track) =>
|
||||
new(track is ExternalTrackApplicationResponse ? TrackSource.YouTube : TrackSource.Local, track, null);
|
||||
|
||||
public static TrackSearchItemResponse FromYouTubeSong(YouTubeSongResult song) =>
|
||||
new(TrackSource.YouTube, null, song);
|
||||
public static TrackSearchItemResponse FromTrack(TrackApplicationResponse track) => new(track);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,5 +3,6 @@ namespace Musify.Application.Tracks.Responses
|
||||
public record TrackStreamResponse(
|
||||
string ManifestUrl,
|
||||
string Ticket,
|
||||
int ExpiresInSeconds);
|
||||
int ExpiresInSeconds,
|
||||
Guid? ListenId = null);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
namespace Musify.Application.Tracks.Responses
|
||||
{
|
||||
/// <summary>Result of a combined tracks listing/search: a page of local catalog tracks
|
||||
/// (uploads and previously provisioned YouTube tracks), plus, when a search term was given,
|
||||
/// live YouTube Music hits appended after them. Pagination metadata (<see cref="PageNumber"/>,
|
||||
/// <see cref="PageSize"/>, <see cref="PageCount"/>, <see cref="TotalItemCount"/>) describes only
|
||||
/// the local page — YouTube has no stable total, so its continuation is tracked separately via
|
||||
/// <see cref="NextYoutubeContinuationToken"/>.</summary>
|
||||
|
||||
public record TracksSearchResponse(
|
||||
IReadOnlyList<TrackSearchItemResponse> Items,
|
||||
int PageNumber,
|
||||
@@ -13,26 +8,5 @@ namespace Musify.Application.Tracks.Responses
|
||||
int PageCount,
|
||||
int TotalItemCount,
|
||||
bool HasPreviousPage,
|
||||
bool HasNextLocalPage,
|
||||
string? NextYoutubeContinuationToken,
|
||||
bool YoutubeUnavailable,
|
||||
bool HasNextPage)
|
||||
{
|
||||
// HasNextPage is a real field (not a computed property) so it shows up as a required member
|
||||
// of the generated OpenAPI schema, same as every other field here — a get-only property added
|
||||
// outside the primary constructor gets reflected as optional instead, which is never true here.
|
||||
public static TracksSearchResponse Create(
|
||||
IReadOnlyList<TrackSearchItemResponse> items,
|
||||
int pageNumber,
|
||||
int pageSize,
|
||||
int pageCount,
|
||||
int totalItemCount,
|
||||
bool hasPreviousPage,
|
||||
bool hasNextLocalPage,
|
||||
string? nextYoutubeContinuationToken,
|
||||
bool youtubeUnavailable) =>
|
||||
new(items, pageNumber, pageSize, pageCount, totalItemCount, hasPreviousPage, hasNextLocalPage,
|
||||
nextYoutubeContinuationToken, youtubeUnavailable,
|
||||
HasNextPage: hasNextLocalPage || !string.IsNullOrEmpty(nextYoutubeContinuationToken));
|
||||
}
|
||||
bool HasNextPage);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record FollowUserCommand(long FollowerId, long FollowedId) : ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class FollowUserCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<FollowUserCommandHandler> logger)
|
||||
: ICommandHandler<FollowUserCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(FollowUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.FollowerId == request.FollowedId)
|
||||
return Error.Validation(description: "A user cannot follow themselves.");
|
||||
|
||||
var followedExists = await database.Users
|
||||
.AsNoTracking()
|
||||
.AnyAsync(u => u.Id == request.FollowedId, cancellationToken);
|
||||
if (!followedExists)
|
||||
{
|
||||
logger.LogInformation("User {FollowedId} not found", request.FollowedId);
|
||||
return Error.NotFound(description: $"User {request.FollowedId} not found");
|
||||
}
|
||||
|
||||
var alreadyFollowing = await database.UserFollows
|
||||
.AsNoTracking()
|
||||
.AnyAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken);
|
||||
if (alreadyFollowing)
|
||||
return new Success();
|
||||
|
||||
await database.UserFollows.AddAsync(new UserFollow
|
||||
{
|
||||
FollowerId = request.FollowerId,
|
||||
FollowedId = request.FollowedId
|
||||
}, cancellationToken);
|
||||
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("User {FollowerId} followed user {FollowedId}", request.FollowerId, request.FollowedId);
|
||||
|
||||
return new Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public static class FollowVisibility
|
||||
{
|
||||
public static async Task<bool> CanViewFollowersAsync(
|
||||
IDatabase database,
|
||||
long? viewerId,
|
||||
long userId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (viewerId is not { } viewer)
|
||||
return false;
|
||||
|
||||
if (viewer == userId)
|
||||
return true;
|
||||
|
||||
var mutualRows = await database.UserFollows
|
||||
.AsNoTracking()
|
||||
.CountAsync(f =>
|
||||
(f.FollowerId == viewer && f.FollowedId == userId) ||
|
||||
(f.FollowerId == userId && f.FollowedId == viewer),
|
||||
cancellationToken);
|
||||
|
||||
return mutualRows == 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record GetListeningStatsQuery(long UserId) : IQuery<ListeningStatsResponse>;
|
||||
|
||||
public record ListeningStatsResponse(int TracksThisWeek, int SecondsThisWeek, int StreakDays);
|
||||
|
||||
public class GetListeningStatsQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetListeningStatsQuery, ListeningStatsResponse>
|
||||
{
|
||||
public async ValueTask<ListeningStatsResponse> Handle(GetListeningStatsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var weekAgo = DateTime.UtcNow.AddDays(-7);
|
||||
|
||||
var thisWeekHistory = database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(l => l.UserId == request.UserId && l.ListenedAt >= weekAgo);
|
||||
|
||||
var tracksThisWeek = await thisWeekHistory
|
||||
.Where(l => l.IsCounted)
|
||||
.Select(l => l.TrackId)
|
||||
.Distinct()
|
||||
.CountAsync(cancellationToken);
|
||||
|
||||
var secondsThisWeek = await thisWeekHistory
|
||||
.Join(database.Tracks.AsNoTracking(), l => l.TrackId, t => t.Id, (l, t) => l.PlayedSeconds ?? (l.IsCounted ? t.DurationSeconds : 0))
|
||||
.SumAsync(cancellationToken);
|
||||
|
||||
var listenedDates = await database.ListeningHistories
|
||||
.AsNoTracking()
|
||||
.Where(l => l.UserId == request.UserId && l.IsCounted)
|
||||
.Select(l => l.ListenedAt.Date)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var listenedDateSet = listenedDates.ToHashSet();
|
||||
var streakDays = 0;
|
||||
var day = DateTime.UtcNow.Date;
|
||||
while (listenedDateSet.Contains(day))
|
||||
{
|
||||
streakDays++;
|
||||
day = day.AddDays(-1);
|
||||
}
|
||||
|
||||
return new ListeningStatsResponse(tracksThisWeek, (int)Math.Round(secondsThisWeek), streakDays);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ namespace Musify.Application.Users
|
||||
.Select(u => UserApplicationResponse.FromEntity(u))
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (user is null)
|
||||
if (user == null)
|
||||
return Error.NotFound();
|
||||
|
||||
return user;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Users.Responses;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record GetUserFollowersQuery(long? ViewerId, long UserId, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<UserSummaryResponse>>>;
|
||||
|
||||
public class GetUserFollowersQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetUserFollowersQuery, ErrorOr<PaginatedResponse<UserSummaryResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<UserSummaryResponse>>> Handle(GetUserFollowersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await database.Users.AnyAsync(u => u.Id == request.UserId, cancellationToken))
|
||||
return Error.NotFound();
|
||||
|
||||
if (!await FollowVisibility.CanViewFollowersAsync(database, request.ViewerId, request.UserId, cancellationToken))
|
||||
return Error.Forbidden();
|
||||
|
||||
var followsQuery = database.UserFollows
|
||||
.AsNoTracking()
|
||||
.Where(f => f.FollowedId == request.UserId);
|
||||
|
||||
var totalCount = await followsQuery.CountAsync(cancellationToken);
|
||||
var viewerId = request.ViewerId;
|
||||
|
||||
var page = await followsQuery
|
||||
.OrderByDescending(f => f.CreatedAt)
|
||||
.Select(f => new UserSummaryResponse(
|
||||
f.Follower.Id,
|
||||
f.Follower.Name,
|
||||
f.Follower.FirstName,
|
||||
f.Follower.SecondName,
|
||||
f.Follower.ProfilePictureUrl,
|
||||
viewerId != null && database.UserFollows.Any(v => v.FollowerId == viewerId && v.FollowedId == f.FollowerId)))
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
return PaginatedResponse<UserSummaryResponse>.FromPagedList(page);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Shared;
|
||||
using Musify.Application.Users.Responses;
|
||||
using X.PagedList.EF;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record GetUserFollowingQuery(long? ViewerId, long UserId, int PageNumber, int PageSize)
|
||||
: IQuery<ErrorOr<PaginatedResponse<UserSummaryResponse>>>;
|
||||
|
||||
public class GetUserFollowingQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetUserFollowingQuery, ErrorOr<PaginatedResponse<UserSummaryResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<UserSummaryResponse>>> Handle(GetUserFollowingQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await database.Users.AnyAsync(u => u.Id == request.UserId, cancellationToken))
|
||||
return Error.NotFound();
|
||||
|
||||
var followsQuery = database.UserFollows
|
||||
.AsNoTracking()
|
||||
.Where(f => f.FollowerId == request.UserId);
|
||||
|
||||
var totalCount = await followsQuery.CountAsync(cancellationToken);
|
||||
var viewerId = request.ViewerId;
|
||||
|
||||
var page = await followsQuery
|
||||
.OrderByDescending(f => f.CreatedAt)
|
||||
.Select(f => new UserSummaryResponse(
|
||||
f.Followed.Id,
|
||||
f.Followed.Name,
|
||||
f.Followed.FirstName,
|
||||
f.Followed.SecondName,
|
||||
f.Followed.ProfilePictureUrl,
|
||||
viewerId != null && database.UserFollows.Any(v => v.FollowerId == viewerId && v.FollowedId == f.FollowedId)))
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
return PaginatedResponse<UserSummaryResponse>.FromPagedList(page);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Serialization;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record GetUserProfileQuery(long UserId, long? ViewerId = null) : IQuery<ErrorOr<UserProfileResponse>>;
|
||||
|
||||
public record UserProfileResponse(
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long Id,
|
||||
string Name,
|
||||
string? FirstName,
|
||||
string? SecondName,
|
||||
string? ProfilePictureUrl,
|
||||
DateTime CreatedAt,
|
||||
int FollowersCount,
|
||||
int FollowingCount,
|
||||
bool IsFollowing,
|
||||
bool CanViewFollowers);
|
||||
|
||||
public class GetUserProfileQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetUserProfileQuery, ErrorOr<UserProfileResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<UserProfileResponse>> Handle(GetUserProfileQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await database.Users
|
||||
.AsNoTracking()
|
||||
.Where(u => u.Id == request.UserId)
|
||||
.Select(u => new
|
||||
{
|
||||
u.Id,
|
||||
u.Name,
|
||||
u.FirstName,
|
||||
u.SecondName,
|
||||
u.ProfilePictureUrl,
|
||||
u.CreatedAt
|
||||
})
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (user == null)
|
||||
return Error.NotFound();
|
||||
|
||||
var followersCount = await database.UserFollows
|
||||
.AsNoTracking()
|
||||
.CountAsync(f => f.FollowedId == request.UserId, cancellationToken);
|
||||
|
||||
var followingCount = await database.UserFollows
|
||||
.AsNoTracking()
|
||||
.CountAsync(f => f.FollowerId == request.UserId, cancellationToken);
|
||||
|
||||
var isFollowing = request.ViewerId is { } viewerId && viewerId != request.UserId &&
|
||||
await database.UserFollows
|
||||
.AsNoTracking()
|
||||
.AnyAsync(f => f.FollowerId == viewerId && f.FollowedId == request.UserId, cancellationToken);
|
||||
|
||||
var canViewFollowers = await FollowVisibility.CanViewFollowersAsync(
|
||||
database, request.ViewerId, request.UserId, cancellationToken);
|
||||
|
||||
return new UserProfileResponse(
|
||||
user.Id,
|
||||
user.Name,
|
||||
user.FirstName,
|
||||
user.SecondName,
|
||||
user.ProfilePictureUrl,
|
||||
user.CreatedAt,
|
||||
followersCount,
|
||||
followingCount,
|
||||
isFollowing,
|
||||
canViewFollowers);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,30 +8,38 @@ using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record GetUsersQuery(int PageNumber, int PageSize, string? UsernameSearch)
|
||||
: IQuery<ErrorOr<PaginatedResponse<UserApplicationResponse> >>;
|
||||
public record GetUsersQuery(int PageNumber, int PageSize, string? UsernameSearch, long? ViewerId = null)
|
||||
: IQuery<ErrorOr<PaginatedResponse<UserSummaryResponse>>>;
|
||||
|
||||
public class GetUsersQueryHandler(IDatabase database)
|
||||
: IQueryHandler<GetUsersQuery, ErrorOr<PaginatedResponse<UserApplicationResponse> > >
|
||||
: IQueryHandler<GetUsersQuery, ErrorOr<PaginatedResponse<UserSummaryResponse>>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<UserApplicationResponse> >> Handle(GetUsersQuery request, CancellationToken cancellationToken)
|
||||
public async ValueTask<ErrorOr<PaginatedResponse<UserSummaryResponse>>> Handle(GetUsersQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = database.Users
|
||||
var usersQuery = database.Users
|
||||
.AsNoTracking()
|
||||
.AsQueryable();
|
||||
|
||||
if (!string.IsNullOrEmpty(request.UsernameSearch))
|
||||
{
|
||||
var normalizedUsername = request.UsernameSearch.Trim().ToUpperInvariant();
|
||||
user = user.Where(u => u.NormalizedName.Contains(normalizedUsername));
|
||||
usersQuery = usersQuery.Where(u => u.NormalizedName.Contains(normalizedUsername));
|
||||
}
|
||||
|
||||
var totalCount = await user.CountAsync(cancellationToken);
|
||||
var pagedUser = await user
|
||||
.Select(u => UserApplicationResponse.FromEntity(u))
|
||||
var totalCount = await usersQuery.CountAsync(cancellationToken);
|
||||
var viewerId = request.ViewerId;
|
||||
var pagedUsers = await usersQuery
|
||||
.OrderBy(u => u.Name)
|
||||
.Select(u => new UserSummaryResponse(
|
||||
u.Id,
|
||||
u.Name,
|
||||
u.FirstName,
|
||||
u.SecondName,
|
||||
u.ProfilePictureUrl,
|
||||
viewerId != null && database.UserFollows.Any(f => f.FollowerId == viewerId && f.FollowedId == u.Id)))
|
||||
.ToPagedListAsync(request.PageNumber, request.PageSize, totalCount, cancellationToken);
|
||||
|
||||
return PaginatedResponse<UserApplicationResponse>.FromPagedList(pagedUser);
|
||||
return PaginatedResponse<UserSummaryResponse>.FromPagedList(pagedUsers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record IsFollowingUserQuery(long FollowerId, long FollowedId) : IQuery<bool>;
|
||||
|
||||
public class IsFollowingUserQueryHandler(IDatabase database)
|
||||
: IQueryHandler<IsFollowingUserQuery, bool>
|
||||
{
|
||||
public ValueTask<bool> Handle(IsFollowingUserQuery request, CancellationToken cancellationToken) =>
|
||||
new(database.UserFollows
|
||||
.AsNoTracking()
|
||||
.AnyAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using Musify.Domain.Entities;
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Application.Serialization;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.Users.Responses
|
||||
{
|
||||
public record UserApplicationResponse(
|
||||
long Id,
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long Id,
|
||||
string Name,
|
||||
string? FirstName,
|
||||
string? SecondName,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Musify.Application.Serialization;
|
||||
|
||||
namespace Musify.Application.Users.Responses
|
||||
{
|
||||
public record UserSummaryResponse(
|
||||
[property: JsonConverter(typeof(LongAsStringConverter))] long Id,
|
||||
string Name,
|
||||
string? FirstName,
|
||||
string? SecondName,
|
||||
string? ProfilePictureUrl,
|
||||
bool IsFollowedByViewer);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ namespace Musify.Application.Users
|
||||
var user = await database.Users
|
||||
.SingleOrDefaultAsync(u => u.Id == request.Id, cancellationToken);
|
||||
|
||||
if (user is null)
|
||||
if (user == null)
|
||||
{
|
||||
await database.Users.AddAsync(new User
|
||||
{
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
|
||||
namespace Musify.Application.Users
|
||||
{
|
||||
public record UnfollowUserCommand(long FollowerId, long FollowedId) : ICommand<ErrorOr<Success>>;
|
||||
|
||||
public class UnfollowUserCommandHandler(
|
||||
IDatabase database,
|
||||
ILogger<UnfollowUserCommandHandler> logger)
|
||||
: ICommandHandler<UnfollowUserCommand, ErrorOr<Success>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<Success>> Handle(UnfollowUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var follow = await database.UserFollows
|
||||
.SingleOrDefaultAsync(f => f.FollowerId == request.FollowerId && f.FollowedId == request.FollowedId, cancellationToken);
|
||||
|
||||
if (follow == null)
|
||||
return new Success();
|
||||
|
||||
database.UserFollows.Remove(follow);
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogInformation("User {FollowerId} unfollowed user {FollowedId}", request.FollowerId, request.FollowedId);
|
||||
|
||||
return new Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Services;
|
||||
|
||||
namespace Musify.Application.YouTube
|
||||
{
|
||||
public record GetYouTubeAlbumQuery(string AlbumId)
|
||||
: IQuery<ErrorOr<YouTubeAlbumDetail>>;
|
||||
|
||||
public class GetYouTubeAlbumQueryHandler(
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
YouTubeTrackProvisioner provisioner,
|
||||
ILogger<GetYouTubeAlbumQueryHandler> logger)
|
||||
: IQueryHandler<GetYouTubeAlbumQuery, ErrorOr<YouTubeAlbumDetail>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<YouTubeAlbumDetail>> Handle(GetYouTubeAlbumQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.AlbumId))
|
||||
return Error.Validation(description: "The album id must not be empty.");
|
||||
|
||||
var result = await youTubeMusicService.GetAlbumAsync(request.AlbumId, cancellationToken);
|
||||
if (result.IsError)
|
||||
return result;
|
||||
|
||||
try
|
||||
{
|
||||
await provisioner.MaterializeAlbumAsync(request.AlbumId, result.Value, cancellationToken);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Failed to materialize YouTube album {AlbumId}", request.AlbumId);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Musify.Application.Configuration;
|
||||
using Musify.Application.Contracts;
|
||||
using Musify.Application.Services;
|
||||
using Musify.Application.YouTube.Responses;
|
||||
using Musify.Domain.Entities;
|
||||
|
||||
namespace Musify.Application.YouTube
|
||||
{
|
||||
/// <param name="UserId">Null for an anonymous request — allowed only when
|
||||
/// <see cref="PlaybackConfiguration.AllowAnonymousListening"/> is enabled.</param>
|
||||
public record ResolveYouTubeTrackStreamCommand(string VideoId, long? UserId)
|
||||
: ICommand<ErrorOr<YouTubeStreamResponse>>;
|
||||
|
||||
public class ResolveYouTubeTrackStreamCommandHandler(
|
||||
IDatabase database,
|
||||
IYouTubeMusicService youTubeMusicService,
|
||||
YouTubeTrackProvisioner provisioner,
|
||||
TrackStreamIssuer streamIssuer,
|
||||
PlaybackConfiguration playbackConfiguration,
|
||||
ILogger<ResolveYouTubeTrackStreamCommandHandler> logger)
|
||||
: ICommandHandler<ResolveYouTubeTrackStreamCommand, ErrorOr<YouTubeStreamResponse>>
|
||||
{
|
||||
public async ValueTask<ErrorOr<YouTubeStreamResponse>> Handle(ResolveYouTubeTrackStreamCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isAnonymous = request.UserId is null;
|
||||
if (isAnonymous && !playbackConfiguration.AllowAnonymousListening)
|
||||
return Error.Unauthorized(description: "Sign in to stream music, or ask an administrator to enable anonymous listening.");
|
||||
|
||||
var track = await provisioner.FindAsync(request.VideoId, cancellationToken);
|
||||
|
||||
if (track != null && track.Audio.IsProcessed)
|
||||
{
|
||||
var serverStream = await streamIssuer.IssueAsync(track.Id, track.Audio.FolderName, request.UserId, cancellationToken);
|
||||
return new YouTubeStreamResponse(
|
||||
track.Id,
|
||||
YouTubeStreamMode.Server,
|
||||
serverStream.ManifestUrl,
|
||||
serverStream.Ticket,
|
||||
serverStream.ExpiresInSeconds);
|
||||
}
|
||||
|
||||
// Below this point the only option left is streaming straight from YouTube's own CDN,
|
||||
// which bypasses our Gateway (and its stream tickets) entirely — there's no way to cap that
|
||||
// to the configured anonymous fragment, so an anonymous listener simply doesn't get it: they
|
||||
// can retry once the track has been provisioned server-side, where the cap above applies.
|
||||
if (isAnonymous && playbackConfiguration.AnonymousFragmentSeconds > 0)
|
||||
return Error.Conflict(description: "This track isn't available for anonymous preview yet. Try again in a moment.");
|
||||
|
||||
var streamInfo = await youTubeMusicService.GetAudioStreamAsync(request.VideoId, cancellationToken);
|
||||
if (streamInfo.IsError)
|
||||
return streamInfo.Errors;
|
||||
|
||||
if (track == null)
|
||||
{
|
||||
var provisionResult = await provisioner.GetOrCreateAsync(request.VideoId, cancellationToken);
|
||||
if (!provisionResult.IsError)
|
||||
track = provisionResult.Value.Track;
|
||||
else
|
||||
logger.LogWarning("Could not provision YouTube track {VideoId}: {Error}", request.VideoId, provisionResult.FirstError.Description);
|
||||
}
|
||||
|
||||
if (track != null && request.UserId is not null)
|
||||
{
|
||||
await database.ListeningHistories.AddAsync(new ListeningHistory
|
||||
{
|
||||
UserId = request.UserId.Value,
|
||||
TrackId = track.Id,
|
||||
}, cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await database.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateException exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Failed to record listening history for YouTube video {VideoId}", request.VideoId);
|
||||
}
|
||||
}
|
||||
|
||||
return new YouTubeStreamResponse(
|
||||
track?.Id,
|
||||
YouTubeStreamMode.YouTube,
|
||||
streamInfo.Value.Url, null,
|
||||
streamInfo.Value.ExpiresInSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
namespace Musify.Application.YouTube.Responses
|
||||
{
|
||||
public enum YouTubeStreamMode
|
||||
{
|
||||
Server = 0,
|
||||
YouTube = 1
|
||||
}
|
||||
|
||||
public record YouTubeStreamResponse(
|
||||
Guid? TrackId,
|
||||
YouTubeStreamMode Mode,
|
||||
string StreamUrl,
|
||||
string? Ticket,
|
||||
int ExpiresInSeconds);
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Musify.Domain.Abstractions;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
#pragma warning disable CS8618
|
||||
public abstract class Album : IAuditable
|
||||
public class Album : IAuditable
|
||||
{
|
||||
[Key]
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
@@ -25,6 +26,12 @@ namespace Musify.Domain.Entities
|
||||
|
||||
public AlbumPictures? Pictures { get; set; }
|
||||
|
||||
[Required]
|
||||
public required long OwnerUserId { get; set; }
|
||||
|
||||
[ForeignKey(nameof(OwnerUserId))]
|
||||
public User Owner { get; set; }
|
||||
|
||||
[Required]
|
||||
public LifeCycleStatus LifeCycleStatus { get; set; } = LifeCycleStatus.Active;
|
||||
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Musify.Domain.Abstractions;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
#pragma warning disable CS8618
|
||||
public class Artist : IAuditable
|
||||
{
|
||||
[Key]
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
[Required]
|
||||
[MaxLength(200)]
|
||||
public required string Name { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(200)]
|
||||
public required string NormalizedName { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(64)]
|
||||
public required string ExternalId { get; set; }
|
||||
|
||||
[Required]
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
[Required]
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
public ICollection<TrackArtist> TrackArtists { get; set; } = new List<TrackArtist>();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
public class ExternalAlbum : Album
|
||||
{
|
||||
[Required]
|
||||
public required TrackSource Source { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(64)]
|
||||
public required string ExternalId { get; set; }
|
||||
|
||||
[MaxLength(512)]
|
||||
public string? ThumbnailUrl { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
public class ExternalTrack : Track
|
||||
{
|
||||
[Required]
|
||||
public required TrackSource Source { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(64)]
|
||||
public required string ExternalId { get; set; }
|
||||
|
||||
public ICollection<TrackArtist> TrackArtists { get; set; } = new List<TrackArtist>();
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@ namespace Musify.Domain.Entities
|
||||
[Required]
|
||||
public DateTime ListenedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
public double? PlayedSeconds { get; set; }
|
||||
|
||||
public DateTime? LastProgressAt { get; set; }
|
||||
|
||||
public bool IsCounted { get; set; }
|
||||
|
||||
[ForeignKey(nameof(UserId) )]
|
||||
public User User { get; set; }
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
public class LocalTrack : Track
|
||||
{
|
||||
[Required]
|
||||
public required long OwnerUserId { get; set; }
|
||||
|
||||
[ForeignKey(nameof(OwnerUserId)) ]
|
||||
public required User Owner { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
#pragma warning disable CS8618
|
||||
@@ -19,32 +17,12 @@ namespace Musify.Domain.Entities
|
||||
public int Position { get; set; } = 0;
|
||||
|
||||
[Required]
|
||||
public required MixItemSource Source { get; set; }
|
||||
|
||||
public Guid? TrackId { get; set; }
|
||||
|
||||
[MaxLength(64)]
|
||||
public string? VideoId { get; set; }
|
||||
|
||||
[MaxLength(300)]
|
||||
public string? Title { get; set; }
|
||||
|
||||
[MaxLength(300)]
|
||||
public string? Artist { get; set; }
|
||||
|
||||
[MaxLength(512)]
|
||||
public string? ThumbnailUrl { get; set; }
|
||||
|
||||
[Required]
|
||||
public double DurationSeconds { get; set; }
|
||||
|
||||
[Required]
|
||||
public bool IsExplicit { get; set; }
|
||||
public required Guid TrackId { get; set; }
|
||||
|
||||
[ForeignKey(nameof(MixId))]
|
||||
public Mix Mix { get; set; }
|
||||
|
||||
[ForeignKey(nameof(TrackId))]
|
||||
public Track? Track { get; set; }
|
||||
public Track Track { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,14 @@ namespace Musify.Domain.Entities
|
||||
[MaxLength(256)]
|
||||
public string? Description { get; set; }
|
||||
|
||||
[Required]
|
||||
public required PlayListPictures Pictures { get; set; }
|
||||
public PlayListPictures? Pictures { get; set; }
|
||||
|
||||
[Required]
|
||||
public LifeCycleStatus LifeCycleStatus { get; set; } = LifeCycleStatus.Active;
|
||||
|
||||
[Required]
|
||||
public PlaylistVisibility Visibility { get; set; } = PlaylistVisibility.Private;
|
||||
|
||||
[Required]
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using Musify.Domain.Abstractions;
|
||||
using Musify.Domain.ValueObjects;
|
||||
|
||||
namespace Musify.Domain.Entities
|
||||
{
|
||||
#pragma warning disable CS8618
|
||||
public abstract class Track : IAuditable
|
||||
public class Track : IAuditable
|
||||
{
|
||||
[Key]
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
@@ -21,9 +22,18 @@ namespace Musify.Domain.Entities
|
||||
[Required]
|
||||
public double DurationSeconds { get; set; }
|
||||
|
||||
[Required]
|
||||
public required long OwnerUserId { get; set; }
|
||||
|
||||
[ForeignKey(nameof(OwnerUserId))]
|
||||
public required User Owner { get; set; }
|
||||
|
||||
[Required]
|
||||
public LifeCycleStatus LifeCycleStatus { get; set; } = LifeCycleStatus.Active;
|
||||
|
||||
[Required]
|
||||
public bool IsExplicit { get; set; }
|
||||
|
||||
[Required]
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
@@ -41,5 +51,7 @@ namespace Musify.Domain.Entities
|
||||
public ICollection<AlbumHasTrack> AlbumTracks { get; set; } = new List<AlbumHasTrack>();
|
||||
|
||||
public ICollection<ListeningHistory> ListeningHistories { get; set; } = new List<ListeningHistory>();
|
||||
|
||||
public ICollection<TrackTag> Tags { get; set; } = new List<TrackTag>();
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user