diff --git a/src/Infrastructure/Data/ApplicationDbContextInitializer.cs b/src/Infrastructure/Data/ApplicationDbContextInitializer.cs index 233b97a..ef35783 100644 --- a/src/Infrastructure/Data/ApplicationDbContextInitializer.cs +++ b/src/Infrastructure/Data/ApplicationDbContextInitializer.cs @@ -1,9 +1,4 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Hutopy.Domain.Constants; -using Hutopy.Infrastructure.Identity; -using Hutopy.Infrastructure.Identity.OwnedEntities; +using Hutopy.Domain.Constants; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; @@ -29,7 +24,6 @@ public static class InitializerExtensions public class ApplicationDbContextInitializer( ILogger logger, ApplicationDbContext context, - ApplicationUserManager userManager, RoleManager roleManager) { public async Task InitialiseAsync() @@ -60,7 +54,6 @@ public class ApplicationDbContextInitializer( private async Task TrySeedAsync() { - // Default roles var administratorRole = new IdentityRole(Roles.Administrator); if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) { @@ -72,47 +65,5 @@ public class ApplicationDbContextInitializer( { await roleManager.CreateAsync(roleCreator); } - - // Default users - var administrator = - new ApplicationUser { UserName = "administrator@localhost", Email = "administrator@localhost" }; - if (userManager.Users.All(u => u.UserName != administrator.UserName)) - { - await userManager.CreateAsync(administrator, "Administrator1!"); - await userManager.AddToRolesAsync(administrator, new[] { Roles.Administrator }); - } - - // ADD CREATORS - await AddDefaultCreator(new ApplicationUser - { - UserName = "hutopy@localhost", - Email = "hutopy@localhost", - CreatorAlias = "hutopy", - About = "Page officielle", - Description = "Site officiel pour Hutopy. Venez-nous-y retrouver avec tous vos fans!", - EmailConfirmed = true, - ProfileColors = new ProfileColors { BannerTop = "A30E79", BannerBottom = "6B0065", Accent = "23393B", Menu = "53B93B", }, - SocialNetworks = - new SocialNetworks - { - XUrl = "https://twitter.com/Hutopyinc", - FacebookUrl = "https://www.facebook.com/Hutopy", - InstagramUrl = "https://www.instagram.com/hutopy.inc/" - }, - StoredDataUrls = new StoredDataUrls - { - BannerPictureUrl = "/images/usersmedia/HutopyProfile/banners/banner01.png", - ProfilePictureUrl = "/images/usersmedia/HutopyProfile/profilepictures/profileHutopyProfile01.png" - } - }); - } - - private async Task AddDefaultCreator(ApplicationUser hutopy) - { - if (userManager.Users.All(u => u.UserName != hutopy.UserName)) - { - await userManager.CreateAsync(hutopy, "Test123!"); - await userManager.AddToRolesAsync(hutopy, new[] { Roles.Creator }); - } } } diff --git a/src/Web/Contents/Data/ContentDbContextInitializer.cs b/src/Web/Contents/Data/ContentDbContextInitializer.cs deleted file mode 100644 index b5726ff..0000000 --- a/src/Web/Contents/Data/ContentDbContextInitializer.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Hutopy.Infrastructure.Identity; -using Hutopy.Web.Common; -using Microsoft.EntityFrameworkCore; - -namespace Hutopy.Web.Contents.Data; - -public static class InitializerExtensions -{ - public static async Task InitialiseContentDatabaseAsync(this WebApplication app, CancellationToken ct = default) - { - using var scope = app.Services.CreateScope(); - - var initializer = scope.ServiceProvider.GetRequiredService(); - - await initializer.InitialiseAsync(ct); - - await initializer.SeedAsync(ct); - } -} - -internal class ContentDbContextInitializer( - ILogger logger, - ApplicationUserManager userManager, - ContentDbContext context) -{ - public async Task InitialiseAsync(CancellationToken ct = default) - { - try - { - await context.Database.MigrateAsync(ct); - } - catch (Exception ex) - { - logger.LogError(ex, "An error occurred while initialising the database."); - throw; - } - } - - public async Task SeedAsync(CancellationToken ct = default) - { - try - { - var administratorUser = await userManager.FindByNameAsync("administrator@localhost"); - var administratorId= Guid.Parse(administratorUser!.Id); - await TrySeedAsync(administratorId, 100, ct); - - await context.SaveChangesAsync(ct); - } - catch (Exception ex) - { - logger.LogError(ex, "An error occurred while seeding the database."); - throw; - } - } - - private async Task TrySeedAsync(Guid creatorId, int contentCount, CancellationToken ct = default) - { - for (var c = 0; c < contentCount; c++) - { - await context.Contents.AddAsync( - new Content - { - Id = GuidHelper.GenerateUuidV7(), - CreatedBy = creatorId, - Title = $"Title {c}", - Description = $"Description {c}" - }, - ct); - } - } -} diff --git a/src/Web/Contents/DependencyInjection.cs b/src/Web/Contents/DependencyInjection.cs index 7946338..a62df6c 100644 --- a/src/Web/Contents/DependencyInjection.cs +++ b/src/Web/Contents/DependencyInjection.cs @@ -11,8 +11,6 @@ public static class DependencyInjection { services.AddDbContext(configureAction); - services.AddScoped(); - return services; } } diff --git a/src/Web/Program.cs b/src/Web/Program.cs index 3698029..bef36d9 100644 --- a/src/Web/Program.cs +++ b/src/Web/Program.cs @@ -6,7 +6,6 @@ using Hutopy.Infrastructure.Data; using Hutopy.Infrastructure.Identity; using Hutopy.Web; using Hutopy.Web.Contents; -using Hutopy.Web.Contents.Data; using Hutopy.Web.Messages; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.EntityFrameworkCore; @@ -103,7 +102,7 @@ app.UseAuthorization(); // Initialize and seed the db. await app.InitialiseApplicationDatabaseAsync(); -await app.InitialiseContentDatabaseAsync(); +await app.SeedDatabaseWithTestDataOnlyIfNoDataIsPresentAsync(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) diff --git a/src/Web/TestDataSeeder.cs b/src/Web/TestDataSeeder.cs new file mode 100644 index 0000000..4e1e7f9 --- /dev/null +++ b/src/Web/TestDataSeeder.cs @@ -0,0 +1,201 @@ +using Hutopy.Domain.Constants; +using Hutopy.Infrastructure.Identity; +using Hutopy.Infrastructure.Identity.OwnedEntities; +using Hutopy.Web.Common; +using Hutopy.Web.Contents.Data; +using Hutopy.Web.Messages.Data; + +namespace Hutopy.Web; + +public static class WebApplicationExtensions +{ + public static async Task SeedDatabaseWithTestDataOnlyIfNoDataIsPresentAsync( + this WebApplication app, + CancellationToken ct = default) + { + using var scope = app.Services.CreateScope(); + + var seeder = new TestDataSeeder( + scope.ServiceProvider.GetRequiredService(), + scope.ServiceProvider.GetRequiredService(), + scope.ServiceProvider.GetRequiredService()); + + await seeder.SeedAsync(); + } +} + +internal class TestDataSeeder( + ApplicationUserManager userManager, + ContentDbContext contentContext, + MessagingDbContext messagingContext) +{ + private const string DefaultPassword = "Test123#"; + + public async Task SeedAsync() + { + if (contentContext.Contents.Any()) return; + + _ = await CreateAdministratorAsync("admin"); + _ = await CreateUserAsync("userA"); + _ = await CreateUserAsync("userB"); + + foreach (var creator in _creators) + { + _ = await CreateCreatorAsync(creator); + + var contents = GenerateContent(creator, 100); + foreach (var content in contents) + { + var messages = GenerateMessages(content, 100); + var parentMessages = messages.Where((_, index) => index % 2 == 0).ToList(); + + foreach (var parentMessage in parentMessages) + { + _ = GenerateReplies(content, parentMessage, 10); + } + + await messagingContext.SaveChangesAsync(); + } + } + } + + private List GenerateContent(ApplicationUser user, int contentCount) + { + var contents = new List(); + + for (var c = 0; c < contentCount; c++) + { + var content = new Content + { + Id = GuidHelper.GenerateUuidV7(), + CreatedBy = Guid.Parse(user.Id), + Title = $"Title {user.UserName}-{c}", + Description = $"Description {user.UserName}-{c}" + }; + + contentContext.Contents.Add(content); + + contents.Add(content); + } + + contentContext.SaveChanges(); + + return contents; + } + + private List GenerateMessages(Content content, int messageCount) + { + var messages = new List(); + + for (var m = 0; m < messageCount; m++) + { + var author = Random.Shared.GetItems(_creators, 1)[0]; + + var message = new Message + { + Id = GuidHelper.GenerateUuidV7(), + SubjectId = content.Id, + CreatedBy = Guid.Parse(author.Id), + Value = $"Message #{m} from {author.UserName} on {content.Title}" + }; + + messagingContext.Messages.Add(message); + + messages.Add(message); + } + + return messages; + } + + private List GenerateReplies(Content content, Message parent, int replyCount) + { + var replies = new List(); + + for (var r = 0; r < replyCount; r++) + { + var author = Random.Shared.GetItems(_creators, 1)[0]; + + var message = new Message + { + Id = GuidHelper.GenerateUuidV7(), + SubjectId = content.Id, + ParentId = parent.Id, + CreatedBy = Guid.Parse(author.Id), + Value = $"Reply {r} to {parent.Value}" + }; + + messagingContext.Messages.Add(message); + + replies.Add(message); + } + + return replies; + } + + private async Task CreateAdministratorAsync(string name) + { + ArgumentException.ThrowIfNullOrWhiteSpace(name); + + var administrator = new ApplicationUser { UserName = $"{name}@test", Email = $"{name}@test" }; + + await userManager.CreateAsync(administrator, DefaultPassword); + await userManager.AddToRolesAsync(administrator, new[] { Roles.Administrator }); + + return administrator; + } + + private async Task CreateUserAsync(string name) + { + var user = new ApplicationUser + { + UserName = $"{name}@test", + Email = $"{name}@test", + EmailConfirmed = true, + FirstName = $"FirstName of {name}", + LastName = $"LastName of {name}" + }; + + await userManager.CreateAsync(user, DefaultPassword); + + return user; + } + + private async Task CreateCreatorAsync(ApplicationUser creator) + { + await userManager.CreateAsync(creator, DefaultPassword); + await userManager.AddToRolesAsync(creator, new[] { Roles.Creator }); + return creator; + } + + + private readonly static ApplicationUser Hutopy = new() + { + UserName = "hutopy@test", + Email = "hutopy@test", + EmailConfirmed = true, + CreatorAlias = "hutopy", + About = "Page officielle", + Description = "Site officiel pour Hutopy. Venez-nous-y retrouver avec tous vos fans!", + ProfileColors = new ProfileColors + { + BannerTop = "A30E79", BannerBottom = "6B0065", Accent = "23393B", Menu = "53B93B", + }, + SocialNetworks = + new SocialNetworks + { + XUrl = "https://twitter.com/Hutopyinc", + FacebookUrl = "https://www.facebook.com/Hutopy", + InstagramUrl = "https://www.instagram.com/hutopy.inc/" + }, + StoredDataUrls = new StoredDataUrls + { + BannerPictureUrl = "/images/usersmedia/HutopyProfile/banners/banner01.png", + ProfilePictureUrl = "/images/usersmedia/HutopyProfile/profilepictures/profileHutopyProfile01.png" + } + }; + + private readonly ApplicationUser[] _creators = + [ + Hutopy + ]; +}