feat: recommend server-generated mixes from Musify and YouTube Music

Mixes are their own concept, not playlists: they live in their own
Mixes/MixItems tables, cannot be edited and never show up among the
user's playlists. Each item is either a Musify track or a YouTube Music
reference, so YouTube songs stream directly instead of being downloaded.

A daily Hangfire job seeds the mixes from the listening history: one
discovery mix, one daily mix and one per top artist.

The per-user YouTube filler query was already in the working tree and
rides along here because it shares files with this change.
This commit is contained in:
2026-07-21 18:13:07 +02:00
parent 2cb51f540e
commit 90e842d084
36 changed files with 2667 additions and 13 deletions
+2
View File
@@ -9,6 +9,8 @@
<PackageVersion Include="DispatchR.Mediator" Version="2.2.0" />
<PackageVersion Include="ErrorOr" Version="2.1.1" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
<PackageVersion Include="Hangfire.NetCore" Version="1.8.24" />
<PackageVersion Include="Hangfire.PostgreSql" Version="1.21.1" />
<PackageVersion Include="MassTransit" Version="8.5.9" />
<PackageVersion Include="MassTransit.EntityFrameworkCore" Version="8.5.9" />
<PackageVersion Include="MassTransit.RabbitMQ" Version="8.5.9" />
+6
View File
@@ -57,6 +57,12 @@
"ThumbnailSize": 240,
"ArtworkSize": 544
},
"Mix": {
"ArtistMixCount": 3,
"ItemsPerMix": 12,
"SeedArtistCount": 3,
"YouTubeResultsPerSeed": 12
},
"PlayList": {
"Routes": {
"UploadsFolder": "uploads",
@@ -0,0 +1,51 @@
using Mediator;
using Musify.Api.Authentication;
using Musify.Api.Extensions;
using Musify.Application.Mixes;
using Musify.Application.Mixes.Responses;
namespace Musify.Api.Endpoints;
public static class MixEndpoints
{
public static IEndpointRouteBuilder MapMixEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/mixes")
.WithTags("Mixes")
.RequireAuthorization();
group.MapGet("/", GetMixes)
.WithName("GetMixes")
.WithSummary("Get The Server-Generated Mixes Of The Current User.")
.Produces<IReadOnlyList<MixApplicationResponse>>()
.Produces(StatusCodes.Status401Unauthorized);
group.MapGet("/{id}", GetMixById)
.WithName("GetMixById")
.WithSummary("Get A Mix With All Of Its Songs.")
.Produces<MixApplicationResponse>()
.Produces(StatusCodes.Status401Unauthorized)
.Produces(StatusCodes.Status404NotFound);
return app;
}
private static async Task<IResult> GetMixes(
IMediator mediator,
CurrentUser currentUser,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new GetMixesByUserIdQuery(currentUser.RequiredId), cancellationToken);
return result.ToHttpResult();
}
private static async Task<IResult> GetMixById(
IMediator mediator,
CurrentUser currentUser,
Guid id,
CancellationToken cancellationToken)
{
var result = await mediator.Send(new GetMixByIdQuery(currentUser.RequiredId, id), cancellationToken);
return result.ToHttpResult();
}
}
+1
View File
@@ -39,6 +39,7 @@ app.UseAuthorization();
app
.MapAlbumEndpoints()
.MapMixEndpoints()
.MapPlayListEndpoints()
.MapTrackEndpoints()
.MapUserEndpoints()
@@ -18,6 +18,7 @@ public static class ApplicationDependencyInjection
services.AddValidatedOptions<ApplicationStorageConfiguration>(configuration, ApplicationStorageConfiguration.SectionName);
services.AddValidatedOptions<PlayListConfiguration>(configuration, PlayListConfiguration.SectionName);
services.AddValidatedOptions<TrackConfiguration>(configuration, TrackConfiguration.SectionName);
services.AddValidatedOptions<MixConfiguration>(configuration, MixConfiguration.SectionName);
services.AddValidatedOptions<StreamGatewayConfiguration>(configuration, StreamGatewayConfiguration.SectionName);
services.AddValidatedOptions<UploadIntentConfiguration>(configuration, UploadIntentConfiguration.SectionName);
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
namespace Musify.Application.Configuration
{
public class MixConfiguration
{
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;
}
}
@@ -29,6 +29,10 @@ namespace Musify.Application.Contracts
DbSet<PlayListHasTrack> PlayListHasTracks { get; }
DbSet<Mix> Mixes { get; }
DbSet<MixItem> MixItems { get; }
DbSet<Upload> Uploads { get; }
DbSet<UploadIntent> UploadIntents { get; }
@@ -0,0 +1,343 @@
using ErrorOr;
using Mediator;
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;
namespace Musify.Application.Mixes
{
public record GenerateMixesForUserCommand(long UserId)
: ICommand<ErrorOr<Success>>;
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, int 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;
public async ValueTask<ErrorOr<Success>> Handle(GenerateMixesForUserCommand request, CancellationToken cancellationToken)
{
var userId = request.UserId;
var historyTrackIds = await database.ListeningHistories
.AsNoTracking()
.Where(history => history.UserId == userId)
.Select(history => history.TrackId)
.Distinct()
.ToListAsync(cancellationToken);
if (historyTrackIds.Count == 0)
{
logger.LogInformation("User {UserId} has no listening history yet, skipping mix generation", userId);
return new Success();
}
var seedArtists = await GetSeedArtistsAsync(historyTrackIds, cancellationToken);
if (seedArtists.Count == 0)
{
logger.LogInformation("User {UserId} has no artists to seed mixes from, skipping mix generation", userId);
return new Success();
}
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);
return new Success();
}
await ReplaceMixesAsync(userId, drafts, cancellationToken);
try
{
await database.SaveChangesAsync(cancellationToken);
}
catch (Exception exception)
{
logger.LogError(exception, "Failed to generate mixes for user {UserId}", userId);
return Error.Failure(description: $"Failed to generate mixes for user {userId}");
}
logger.LogInformation("Generated {Count} mixes for user {UserId}", drafts.Count, userId);
return new Success();
}
private async Task<List<SeedArtist>> GetSeedArtistsAsync(
IReadOnlyList<Guid> historyTrackIds,
CancellationToken cancellationToken)
{
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 de YouTube Music 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($"Mezcla: {seed.Name}", MixTitleLength),
$"Canciones de {seed.Name} en Musify y en YouTube Music.",
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);
for (var index = 0; index < Math.Max(first.Count, second.Count); index++)
{
if (index < first.Count)
merged.Add(first[index]);
if (index < second.Count)
merged.Add(second[index]);
}
return merged;
}
private async Task ReplaceMixesAsync(long userId, IReadOnlyList<MixDraft> drafts, CancellationToken cancellationToken)
{
var previousMixes = await database.Mixes
.Where(mix => mix.UserId == userId)
.ToListAsync(cancellationToken);
if (previousMixes.Count > 0)
{
var previousIds = previousMixes.Select(mix => mix.Id).ToList();
var previousItems = await database.MixItems
.Where(item => previousIds.Contains(item.MixId))
.ToListAsync(cancellationToken);
database.MixItems.RemoveRange(previousItems);
database.Mixes.RemoveRange(previousMixes);
}
var today = DateOnly.FromDateTime(DateTime.UtcNow);
for (var position = 0; position < drafts.Count; position++)
{
var draft = drafts[position];
var mix = new Mix
{
UserId = userId,
Title = draft.Title,
Subtitle = draft.Subtitle,
GeneratedOn = today,
Position = position
};
await database.Mixes.AddAsync(mix, cancellationToken);
for (var itemPosition = 0; itemPosition < draft.Items.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
}, cancellationToken);
}
}
}
}
}
@@ -0,0 +1,30 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Mixes.Responses;
namespace Musify.Application.Mixes
{
public record GetMixByIdQuery(long UserId, Guid MixId)
: IQuery<ErrorOr<MixApplicationResponse>>;
public class GetMixByIdQueryHandler(IDatabase database)
: IQueryHandler<GetMixByIdQuery, ErrorOr<MixApplicationResponse>>
{
public async ValueTask<ErrorOr<MixApplicationResponse>> Handle(GetMixByIdQuery request, CancellationToken cancellationToken)
{
var mix = await database.Mixes
.AsNoTracking()
.Include(mix => mix.Items)
.SingleOrDefaultAsync(mix => mix.Id == request.MixId && mix.UserId == request.UserId, cancellationToken);
if (mix is null)
return Error.NotFound(description: $"Mix {request.MixId} was not found");
var items = mix.Items.OrderBy(item => item.Position).ToList();
return MixApplicationResponse.FromEntity(mix, items.Count, items);
}
}
}
@@ -0,0 +1,37 @@
using ErrorOr;
using Mediator;
using Microsoft.EntityFrameworkCore;
using Musify.Application.Contracts;
using Musify.Application.Mixes.Responses;
namespace Musify.Application.Mixes
{
public record GetMixesByUserIdQuery(long UserId)
: IQuery<ErrorOr<IReadOnlyList<MixApplicationResponse>>>;
public class GetMixesByUserIdQueryHandler(IDatabase database)
: IQueryHandler<GetMixesByUserIdQuery, ErrorOr<IReadOnlyList<MixApplicationResponse>>>
{
public async ValueTask<ErrorOr<IReadOnlyList<MixApplicationResponse>>> Handle(GetMixesByUserIdQuery request, CancellationToken cancellationToken)
{
var entries = await database.Mixes
.AsNoTracking()
.Where(mix => mix.UserId == request.UserId)
.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();
}
}
}
@@ -0,0 +1,27 @@
using Musify.Domain.Entities;
namespace Musify.Application.Mixes.Responses
{
public record MixApplicationResponse(
Guid Id,
string Title,
string? Subtitle,
DateOnly GeneratedOn,
int ItemCount,
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,
mix.GeneratedOn,
itemCount,
[.. items.Select(MixItemApplicationResponse.FromEntity)]);
}
}
@@ -0,0 +1,27 @@
using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
namespace Musify.Application.Mixes.Responses
{
public record MixItemApplicationResponse(
MixItemSource Source,
Guid? TrackId,
string? VideoId,
string Title,
string? Artist,
string? ThumbnailUrl,
int 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);
}
}
+42
View File
@@ -0,0 +1,42 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Musify.Domain.Abstractions;
namespace Musify.Domain.Entities
{
#pragma warning disable CS8618
[Table("Mixes")]
public class Mix : IAuditable
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
public required long UserId { get; set; }
[Required]
[MaxLength(100)]
public required string Title { get; set; }
[MaxLength(256)]
public string? Subtitle { get; set; }
[Required]
public required DateOnly GeneratedOn { get; set; }
[Required]
public int Position { get; set; } = 0;
[Required]
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
[Required]
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
[ForeignKey(nameof(UserId))]
public User User { get; set; }
public ICollection<MixItem> Items { get; set; } = new List<MixItem>();
}
}
+50
View File
@@ -0,0 +1,50 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Musify.Domain.ValueObjects;
namespace Musify.Domain.Entities
{
#pragma warning disable CS8618
[Table("MixItems")]
public class MixItem
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
public required Guid MixId { get; set; }
[Required]
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 int DurationSeconds { get; set; } = 0;
[Required]
public bool IsExplicit { get; set; } = false;
[ForeignKey(nameof(MixId))]
public Mix Mix { get; set; }
[ForeignKey(nameof(TrackId))]
public Track? Track { get; set; }
}
}
@@ -0,0 +1,8 @@
namespace Musify.Domain.ValueObjects
{
public enum MixItemSource
{
Musify = 0,
YouTube = 1
}
}
@@ -0,0 +1,37 @@
using Mediator;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Musify.Application.Contracts;
using Musify.Application.Mixes;
namespace Musify.Infrastructure.Jobs
{
public class DailyMixGenerationJob(
IDatabase database,
IMediator mediator,
ILogger<DailyMixGenerationJob> logger)
{
public async Task RunAsync(CancellationToken cancellationToken)
{
var userIds = await database.ListeningHistories
.AsNoTracking()
.Select(history => history.UserId)
.Distinct()
.ToListAsync(cancellationToken);
logger.LogInformation("Starting daily mix generation for {Count} users", userIds.Count);
foreach (var userId in userIds)
{
var result = await mediator.Send(new GenerateMixesForUserCommand(userId), cancellationToken);
if (result.IsError)
{
logger.LogWarning("Failed to generate mixes for user {UserId}: {Error}",
userId, result.FirstError.Description);
}
}
logger.LogInformation("Finished daily mix generation");
}
}
}
@@ -6,6 +6,8 @@
<ItemGroup>
<PackageReference Include="AWSSDK.S3" />
<PackageReference Include="Hangfire.NetCore" />
<PackageReference Include="Hangfire.PostgreSql" />
<PackageReference Include="MassTransit" />
<PackageReference Include="MassTransit.EntityFrameworkCore" />
<PackageReference Include="MassTransit.RabbitMQ" />
@@ -137,6 +137,25 @@ namespace Musify.Infrastructure.Persistence
.HasIndex(albumTrack => new { albumTrack.AlbumId, albumTrack.TrackId })
.IsUnique();
modelBuilder.Entity<Mix>()
.HasIndex(mix => new { mix.UserId, mix.Position });
modelBuilder.Entity<MixItem>()
.HasOne(item => item.Mix)
.WithMany(mix => mix.Items)
.HasForeignKey(item => item.MixId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<MixItem>()
.HasOne(item => item.Track)
.WithMany()
.HasForeignKey(item => item.TrackId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<MixItem>()
.HasIndex(item => new { item.MixId, item.Position });
var playListProcessing = modelBuilder.Entity<PlayListProcessingState>();
playListProcessing.HasKey(state => state.CorrelationId);
playListProcessing.Property(state => state.CorrelationId).ValueGeneratedNever();
@@ -167,6 +186,10 @@ namespace Musify.Infrastructure.Persistence
public DbSet<PlayListHasTrack> PlayListHasTracks => Set<PlayListHasTrack>();
public DbSet<Mix> Mixes => Set<Mix>();
public DbSet<MixItem> MixItems => Set<MixItem>();
public DbSet<Upload> Uploads => Set<Upload>();
public DbSet<UploadIntent> UploadIntents => Set<UploadIntent>();
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,97 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Musify.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddMixes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Mixes",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
UserId = table.Column<long>(type: "bigint", nullable: false),
Title = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
Subtitle = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
GeneratedOn = table.Column<DateOnly>(type: "date", nullable: false),
Position = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Mixes", x => x.Id);
table.ForeignKey(
name: "FK_Mixes_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "MixItems",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
MixId = table.Column<Guid>(type: "uuid", nullable: false),
Position = table.Column<int>(type: "integer", nullable: false),
Source = table.Column<int>(type: "integer", nullable: false),
TrackId = table.Column<Guid>(type: "uuid", nullable: true),
VideoId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
Title = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
Artist = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
ThumbnailUrl = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true),
DurationSeconds = table.Column<int>(type: "integer", nullable: false),
IsExplicit = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MixItems", x => x.Id);
table.ForeignKey(
name: "FK_MixItems_Mixes_MixId",
column: x => x.MixId,
principalTable: "Mixes",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_MixItems_Tracks_TrackId",
column: x => x.TrackId,
principalTable: "Tracks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Mixes_UserId_Position",
table: "Mixes",
columns: new[] { "UserId", "Position" });
migrationBuilder.CreateIndex(
name: "IX_MixItems_MixId_Position",
table: "MixItems",
columns: new[] { "MixId", "Position" });
migrationBuilder.CreateIndex(
name: "IX_MixItems_TrackId",
table: "MixItems",
column: "TrackId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MixItems");
migrationBuilder.DropTable(
name: "Mixes");
}
}
}
@@ -316,6 +316,92 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.ToTable("ListeningHistory");
});
modelBuilder.Entity("Musify.Domain.Entities.Mix", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateOnly>("GeneratedOn")
.HasColumnType("date");
b.Property<int>("Position")
.HasColumnType("integer");
b.Property<string>("Subtitle")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<long>("UserId")
.HasColumnType("bigint");
b.HasKey("Id");
b.HasIndex("UserId", "Position");
b.ToTable("Mixes");
});
modelBuilder.Entity("Musify.Domain.Entities.MixItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Artist")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<int>("DurationSeconds")
.HasColumnType("integer");
b.Property<bool>("IsExplicit")
.HasColumnType("boolean");
b.Property<Guid>("MixId")
.HasColumnType("uuid");
b.Property<int>("Position")
.HasColumnType("integer");
b.Property<int>("Source")
.HasColumnType("integer");
b.Property<string>("ThumbnailUrl")
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<string>("Title")
.HasMaxLength(300)
.HasColumnType("character varying(300)");
b.Property<Guid?>("TrackId")
.HasColumnType("uuid");
b.Property<string>("VideoId")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.HasKey("Id");
b.HasIndex("TrackId");
b.HasIndex("MixId", "Position");
b.ToTable("MixItems");
});
modelBuilder.Entity("Musify.Domain.Entities.PlayList", b =>
{
b.Property<Guid>("Id")
@@ -773,6 +859,35 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Navigation("User");
});
modelBuilder.Entity("Musify.Domain.Entities.Mix", b =>
{
b.HasOne("Musify.Domain.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Musify.Domain.Entities.MixItem", b =>
{
b.HasOne("Musify.Domain.Entities.Mix", "Mix")
.WithMany("Items")
.HasForeignKey("MixId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Musify.Domain.Entities.Track", "Track")
.WithMany()
.HasForeignKey("TrackId")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("Mix");
b.Navigation("Track");
});
modelBuilder.Entity("Musify.Domain.Entities.PlayList", b =>
{
b.HasOne("Musify.Domain.Entities.User", "User")
@@ -1025,6 +1140,11 @@ namespace Musify.Infrastructure.Persistence.Migrations
b.Navigation("TrackArtists");
});
modelBuilder.Entity("Musify.Domain.Entities.Mix", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("Musify.Domain.Entities.PlayList", b =>
{
b.Navigation("PlayListTracks");
@@ -1,4 +1,6 @@
using Amazon.S3;
using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
@@ -60,6 +62,21 @@ namespace Musify.Infrastructure.Services
return serviceDescriptors;
}
public static IServiceCollection AddDailyMixGenerationJob(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors.AddHangfire((serviceProvider, hangfireConfiguration) =>
{
var databaseConfiguration = serviceProvider.GetRequiredService<DatabaseConfiguration>();
hangfireConfiguration.UsePostgreSqlStorage(options =>
options.UseNpgsqlConnection(databaseConfiguration.ConnectionString));
});
serviceDescriptors.AddHangfireServer();
serviceDescriptors.AddScoped<DailyMixGenerationJob>();
return serviceDescriptors;
}
public static IServiceCollection AddStreamTicketService(this IServiceCollection serviceDescriptors, IConfiguration configuration)
{
serviceDescriptors
+6
View File
@@ -26,6 +26,12 @@
"ApplicationStorage": {
"Bucket": ""
},
"Mix": {
"ArtistMixCount": 3,
"ItemsPerMix": 12,
"SeedArtistCount": 3,
"YouTubeResultsPerSeed": 12
},
"PlayList": {
"Routes": {
"ParentFolders": "PlayLists",
+32 -1
View File
@@ -1,10 +1,26 @@
using Hangfire;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using Musify.Application.Configuration;
using Musify.Application.Services;
using Musify.Infrastructure.Jobs;
using Musify.Infrastructure.MassTransit;
using Musify.Infrastructure.Persistence;
using Musify.Infrastructure.Services;
var builder = Host.CreateApplicationBuilder();
// Registering Mediator pulls in every handler in Musify.Application, including ones
// (e.g. CreatePlayList, CreateTrack) that depend on IEventBus, which the Worker never
// registers because it only consumes events, it never publishes them. Only the handlers
// this process actually dispatches (GenerateMixesForUserCommand) are ever constructed,
// so the default eager validate-on-build check is too strict for this host.
builder.ConfigureContainer(new DefaultServiceProviderFactory(new ServiceProviderOptions
{
ValidateOnBuild = false,
ValidateScopes = true
}));
var configuration = builder.Configuration;
var services = builder.Services;
@@ -12,6 +28,7 @@ var services = builder.Services;
services.AddValidatedOptions<ApplicationStorageConfiguration>(configuration, ApplicationStorageConfiguration.SectionName);
services.AddValidatedOptions<PlayListConfiguration>(configuration, PlayListConfiguration.SectionName);
services.AddValidatedOptions<TrackConfiguration>(configuration, TrackConfiguration.SectionName);
services.AddValidatedOptions<MixConfiguration>(configuration, MixConfiguration.SectionName);
services.AddStorageService(configuration);
services.AddAudioTranscoder(configuration);
services.AddYouTubeDownloader(configuration);
@@ -20,7 +37,21 @@ services.AddPictureService(configuration);
services.AddDatabase(configuration);
services.AddMassTransitConsumers(configuration);
services.AddUploadIntentJobs(configuration);
services.AddMediator();
services.AddScoped<YouTubeTrackProvisioner>();
services.AddYouTubeMusicService(configuration);
services.AddDailyMixGenerationJob(configuration);
var host = builder.Build();
host.Run();
using (var scope = host.Services.CreateScope())
{
var recurringJobManager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
recurringJobManager.AddOrUpdate<DailyMixGenerationJob>(
"daily-mix-generation",
job => job.RunAsync(CancellationToken.None),
Cron.Daily(),
new RecurringJobOptions { TimeZone = TimeZoneInfo.Utc });
}
host.Run();