Adds persistence for plugins and library metadata provider configurations

This commit is contained in:
BinaryAlley committed 2026-08-12 11:03:14 -07:00
1 parent f33817f2d2
commit f71e72a948
16 files changed
+3381

No files matched your search

@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Repository entity for the configuration of a metadata provider of a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets or sets the Id of the configuration.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the media library the configuration belongs to.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the Id of the plugin providing the metadata.
/// </summary>
public required Guid PluginId { get; set; }
/// <summary>
/// Gets or sets whether the metadata provider is enabled for the media library.
/// </summary>
public required bool IsEnabled { get; set; }
/// <summary>
/// Gets or sets the rank of the metadata provider, determining the order in which providers are tried.
/// </summary>
public required int Rank { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Repository entity for a plugin.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class PluginEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the plugin.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the display name of the plugin.
/// </summary>
public required string Name { get; set; }
/// <summary>
/// Gets or sets the author of the plugin.
/// </summary>
public required string Author { get; set; }
/// <summary>
/// Gets or sets the version of the plugin.
/// </summary>
public required string Version { get; set; }
/// <summary>
/// Gets or sets the description of the plugin.
/// </summary>
public required string Description { get; set; }
/// <summary>
/// Gets or sets the load status of the plugin.
/// </summary>
public PluginLoadStatus LoadStatus { get; set; }
/// <summary>
/// Gets or sets the error message when the plugin failed to load.
/// </summary>
public string? LoadError { get; set; }
/// <summary>
/// Gets or sets the serialized settings of the plugin.
/// </summary>
public string? SettingsJson { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// <summary>
/// Interface for the repository for the metadata provider configurations of media libraries.
/// </summary>
public interface ILibraryMetadataProviderConfigurationRepository : IRepository<LibraryMetadataProviderConfigurationEntity>
{
/// <summary>
/// Gets all the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
Task<ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the metadata provider configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configuration is retrieved.</param>
/// <param name="pluginId">The Id of the plugin whose metadata provider configuration is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
Task<ErrorOr<LibraryMetadataProviderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
/// <summary>
/// Inserts the provided <paramref name="configuration"/> into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="configuration">The metadata provider configuration to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken);
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// <summary>
/// Interface for the repository for plugins.
/// </summary>
public interface IPluginRepository : IRepository<PluginEntity>,
IGetByIdRepositoryAction<PluginEntity, Guid>,
IGetAllRepositoryAction<PluginEntity>
{
/// <summary>
/// Inserts the provided <paramref name="plugin"/> into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="plugin">The plugin to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken);
/// <summary>
/// Updates the settings of the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose settings are updated.</param>
/// <param name="settingsJson">The serialized settings of the plugin.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken);
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="LibraryMetadataProviderConfigurationEntity"/> entity.
/// </summary>
public class LibraryMetadataProviderConfigurationConfiguration : IEntityTypeConfiguration<LibraryMetadataProviderConfigurationEntity>
{
/// <summary>
/// Configures the <see cref="LibraryMetadataProviderConfigurationEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<LibraryMetadataProviderConfigurationEntity> builder)
{
builder.ToTable("LibraryMetadataProviderConfigurations");
builder.HasKey(configuration => configuration.Id);
builder.Property(configuration => configuration.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(configuration => configuration.LibraryId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(configuration => configuration.PluginId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(configuration => configuration.IsEnabled)
.IsRequired()
.HasColumnOrder(3);
builder.Property(configuration => configuration.Rank)
.IsRequired()
.HasColumnOrder(4);
// audit
builder.Property(configuration => configuration.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(5);
builder.Property(configuration => configuration.CreatedBy)
.IsRequired()
.HasColumnOrder(6);
builder.Property(configuration => configuration.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(7);
builder.Property(configuration => configuration.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(8);
builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId });
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="PluginEntity"/> entity.
/// </summary>
public class PluginConfiguration : IEntityTypeConfiguration<PluginEntity>
{
/// <summary>
/// Configures the <see cref="PluginEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<PluginEntity> builder)
{
builder.ToTable("Plugins");
builder.HasKey(plugin => plugin.Id);
builder.Property(plugin => plugin.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
builder.Property(plugin => plugin.Name)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(1);
builder.Property(plugin => plugin.Author)
.IsRequired()
.HasMaxLength(255)
.HasColumnOrder(2);
builder.Property(plugin => plugin.Version)
.IsRequired()
.HasMaxLength(50)
.HasColumnOrder(3);
builder.Property(plugin => plugin.Description)
.HasMaxLength(2000)
.HasColumnOrder(4);
builder.Property(plugin => plugin.LoadStatus)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired()
.HasColumnOrder(5);
builder.Property(plugin => plugin.LoadError)
.HasMaxLength(2000)
.HasColumnOrder(6);
builder.Property(plugin => plugin.SettingsJson)
.HasColumnOrder(7);
builder.Property(plugin => plugin.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(8);
// audit
builder.Property(plugin => plugin.CreatedBy)
.IsRequired()
.HasColumnOrder(9);
builder.Property(plugin => plugin.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(10);
builder.Property(plugin => plugin.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(11);
}
}
@@ -0,0 +1,65 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsPluginsAndLibraryMetadataProviderConfigurations : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "LibraryMetadataProviderConfigurations",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
PluginId = table.Column<Guid>(type: "TEXT", nullable: false),
IsEnabled = table.Column<bool>(type: "INTEGER", nullable: false),
Rank = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LibraryMetadataProviderConfigurations", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Plugins",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
Author = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),
Version = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: false),
LoadStatus = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
LoadError = table.Column<string>(type: "TEXT", maxLength: 2000, nullable: true),
SettingsJson = table.Column<string>(type: "TEXT", nullable: true),
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Plugins", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LibraryMetadataProviderConfigurations_LibraryId_PluginId",
table: "LibraryMetadataProviderConfigurations",
columns: new[] { "LibraryId", "PluginId" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LibraryMetadataProviderConfigurations");
migrationBuilder.DropTable(
name: "Plugins");
}
}
}
@@ -0,0 +1,110 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Lumina.DataAccess.Common.Migrations
{
/// <inheritdoc />
public partial class AddsAuditableFieldsToPluginEntities : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Plugins",
type: "TEXT",
nullable: true,
oldClrType: typeof(DateTime),
oldType: "TEXT")
.Annotation("Relational:ColumnOrder", 10)
.OldAnnotation("Relational:ColumnOrder", 9);
migrationBuilder.AddColumn<Guid>(
name: "CreatedBy",
table: "Plugins",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"))
.Annotation("Relational:ColumnOrder", 9);
migrationBuilder.AddColumn<Guid>(
name: "UpdatedBy",
table: "Plugins",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 11);
migrationBuilder.AddColumn<Guid>(
name: "CreatedBy",
table: "LibraryMetadataProviderConfigurations",
type: "TEXT",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"))
.Annotation("Relational:ColumnOrder", 6);
migrationBuilder.AddColumn<DateTime>(
name: "CreatedOnUtc",
table: "LibraryMetadataProviderConfigurations",
type: "TEXT",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified))
.Annotation("Relational:ColumnOrder", 5);
migrationBuilder.AddColumn<Guid>(
name: "UpdatedBy",
table: "LibraryMetadataProviderConfigurations",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 8);
migrationBuilder.AddColumn<DateTime>(
name: "UpdatedOnUtc",
table: "LibraryMetadataProviderConfigurations",
type: "TEXT",
nullable: true)
.Annotation("Relational:ColumnOrder", 7);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "Plugins");
migrationBuilder.DropColumn(
name: "UpdatedBy",
table: "Plugins");
migrationBuilder.DropColumn(
name: "CreatedBy",
table: "LibraryMetadataProviderConfigurations");
migrationBuilder.DropColumn(
name: "CreatedOnUtc",
table: "LibraryMetadataProviderConfigurations");
migrationBuilder.DropColumn(
name: "UpdatedBy",
table: "LibraryMetadataProviderConfigurations");
migrationBuilder.DropColumn(
name: "UpdatedOnUtc",
table: "LibraryMetadataProviderConfigurations");
migrationBuilder.AlterColumn<DateTime>(
name: "UpdatedOnUtc",
table: "Plugins",
type: "TEXT",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified),
oldClrType: typeof(DateTime),
oldType: "TEXT",
oldNullable: true)
.Annotation("Relational:ColumnOrder", 9)
.OldAnnotation("Relational:ColumnOrder", 10);
}
}
}
@@ -582,11 +582,30 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("TEXT")
.HasColumnOrder(12);
b.Property<DateTime?>("LastMetadataUpdateUtc")
.HasColumnType("TEXT")
.HasColumnOrder(39);
b.Property<Guid>("LibraryId")
.HasColumnType("TEXT")
.HasColumnOrder(36);
b.Property<string>("LibraryThingId")
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(26);
b.Property<string>("MetadataProvider")
.HasMaxLength(100)
.HasColumnType("TEXT")
.HasColumnOrder(40);
b.Property<string>("MetadataStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(38);
b.Property<string>("OCLCNumber")
.HasColumnType("TEXT")
.HasColumnOrder(24);
@@ -625,6 +644,12 @@ namespace Lumina.DataAccess.Common.Migrations
.HasColumnType("INTEGER")
.HasColumnOrder(17);
b.Property<string>("Path")
.IsRequired()
.HasMaxLength(2048)
.HasColumnType("TEXT")
.HasColumnOrder(37);
b.Property<string>("Publisher")
.HasMaxLength(100)
.HasColumnType("TEXT")
@@ -666,9 +691,124 @@ namespace Lumina.DataAccess.Common.Migrations
b.HasKey("Id");
b.HasIndex("LibraryId", "MetadataStatus");
b.HasIndex("LibraryId", "Path");
b.ToTable("Books", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<bool>("IsEnabled")
.HasColumnType("INTEGER")
.HasColumnOrder(3);
b.Property<Guid>("LibraryId")
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<Guid>("PluginId")
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<int>("Rank")
.HasColumnType("INTEGER")
.HasColumnOrder(4);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.HasKey("Id");
b.HasIndex("LibraryId", "PluginId");
b.ToTable("LibraryMetadataProviderConfigurations", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b =>
{
b.Property<Guid>("Id")
.HasColumnType("TEXT")
.HasColumnOrder(0);
b.Property<string>("Author")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(2);
b.Property<Guid>("CreatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(9);
b.Property<DateTime>("CreatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(8);
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(4);
b.Property<string>("LoadError")
.HasMaxLength(2000)
.HasColumnType("TEXT")
.HasColumnOrder(6);
b.Property<string>("LoadStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("TEXT")
.HasColumnOrder(5);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("TEXT")
.HasColumnOrder(1);
b.Property<string>("SettingsJson")
.HasColumnType("TEXT")
.HasColumnOrder(7);
b.Property<Guid?>("UpdatedBy")
.HasColumnType("TEXT")
.HasColumnOrder(11);
b.Property<DateTime?>("UpdatedOnUtc")
.HasColumnType("TEXT")
.HasColumnOrder(10);
b.Property<string>("Version")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("TEXT")
.HasColumnOrder(3);
b.HasKey("Id");
b.ToTable("Plugins", (string)null);
});
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
{
b.Property<Guid>("Id")
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Plugins;
/// <summary>
/// Repository for the metadata provider configurations of media libraries.
/// </summary>
internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryMetadataProviderConfigurationRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMetadataProviderConfigurationRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public LibraryMetadataProviderConfigurationRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets all the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
public async Task<ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
{
return await _luminaDbContext.LibraryMetadataProviderConfigurations
.Where(configuration => configuration.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the metadata provider configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configuration is retrieved.</param>
/// <param name="pluginId">The Id of the plugin whose metadata provider configuration is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
public async Task<ErrorOr<LibraryMetadataProviderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken)
{
return await _luminaDbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Inserts a metadata provider configuration into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="configuration">The metadata provider configuration to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken)
{
LibraryMetadataProviderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryMetadataProviderConfigurations
.FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false);
if (existingConfiguration is null)
{
_luminaDbContext.LibraryMetadataProviderConfigurations.Add(configuration);
}
else
{
// update only the mutable fields, preserving the Id of the existing configuration
existingConfiguration.LibraryId = configuration.LibraryId;
existingConfiguration.PluginId = configuration.PluginId;
existingConfiguration.IsEnabled = configuration.IsEnabled;
existingConfiguration.Rank = configuration.Rank;
}
return Result.Updated;
}
}
@@ -0,0 +1,98 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.Plugins;
/// <summary>
/// Repository for plugins.
/// </summary>
internal sealed class PluginRepository : IPluginRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="PluginRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public PluginRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets a plugin by its Id.
/// </summary>
/// <param name="id">The Id of the plugin to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a <see cref="PluginEntity"/>, or an error.</returns>
public async Task<ErrorOr<PluginEntity?>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
return await _luminaDbContext.Plugins
.FirstOrDefaultAsync(plugin => plugin.Id == id, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the detected plugins.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PluginEntity"/>, or an error.</returns>
public async Task<ErrorOr<IEnumerable<PluginEntity>>> GetAllAsync(CancellationToken cancellationToken)
{
return await _luminaDbContext.Plugins
.ToListAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Inserts a plugin into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="plugin">The plugin to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken)
{
PluginEntity? existingPlugin = await _luminaDbContext.Plugins
.FirstOrDefaultAsync(repositoryPlugin => repositoryPlugin.Id == plugin.Id, cancellationToken).ConfigureAwait(false);
if (existingPlugin is null)
{
_luminaDbContext.Plugins.Add(plugin);
}
else
{
// update only the detection fields, preserving the stored settings and creation date
existingPlugin.Name = plugin.Name;
existingPlugin.Author = plugin.Author;
existingPlugin.Version = plugin.Version;
existingPlugin.Description = plugin.Description;
existingPlugin.LoadStatus = plugin.LoadStatus;
existingPlugin.LoadError = plugin.LoadError;
}
return Result.Updated;
}
/// <summary>
/// Updates the settings of the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose settings are updated.</param>
/// <param name="settingsJson">The serialized settings of the plugin.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<ErrorOr<Updated>> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken)
{
PluginEntity? existingPlugin = await _luminaDbContext.Plugins
.FirstOrDefaultAsync(repositoryPlugin => repositoryPlugin.Id == pluginId, cancellationToken).ConfigureAwait(false);
if (existingPlugin is null)
return Errors.Plugins.PluginNotFound;
existingPlugin.SettingsJson = settingsJson;
return Result.Updated;
}
}
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
#endregion
@@ -28,6 +29,8 @@ public class LuminaDbContext : DbContext
public virtual DbSet<PermissionEntity> Permissions { get; set; } = null!;
public virtual DbSet<UserPermissionEntity> UserPermissions { get; set; } = null!;
public virtual DbSet<RolePermissionEntity> RolePermissions { get; set; } = null!;
public virtual DbSet<PluginEntity> Plugins { get; set; } = null!;
public virtual DbSet<LibraryMetadataProviderConfigurationEntity> LibraryMetadataProviderConfigurations { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="LibraryMetadataProviderConfigurationRepository"/> class.
/// </summary>
public class LibraryMetadataProviderConfigurationRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly LibraryMetadataProviderConfigurationRepository _sut;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMetadataProviderConfigurationRepositoryTests"/> class.
/// </summary>
public LibraryMetadataProviderConfigurationRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new LibraryMetadataProviderConfigurationRepository(_mockContext);
}
[Fact]
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntity configurationOfLibrary = CreateConfiguration(libraryId, Guid.NewGuid(), 1);
LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<System.Collections.Generic.IReadOnlyList<LibraryMetadataProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsError);
LibraryMetadataProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
}
[Fact]
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
{
// Arrange
LibraryMetadataProviderConfigurationEntity configuration = CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryMetadataProviderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<LibraryMetadataProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Equal(configuration.Id, result.Value!.Id);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
{
// Arrange
LibraryMetadataProviderConfigurationEntity configuration = CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1);
// Act
ErrorOr<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsError);
Assert.Single(_mockContext.LibraryMetadataProviderConfigurations);
}
[Fact]
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
{
// Arrange
LibraryMetadataProviderConfigurationEntity configuration = CreateConfiguration(Guid.NewGuid(), Guid.NewGuid(), 1);
_mockContext.LibraryMetadataProviderConfigurations.Add(configuration);
await _mockContext.SaveChangesAsync();
LibraryMetadataProviderConfigurationEntity updatedConfiguration = CreateConfiguration(configuration.LibraryId, configuration.PluginId, 5);
updatedConfiguration.IsEnabled = true;
// Act
ErrorOr<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsError);
LibraryMetadataProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryMetadataProviderConfigurations.Single();
Assert.Equal(5, retrievedConfiguration.Rank);
Assert.True(retrievedConfiguration.IsEnabled);
}
private static LibraryMetadataProviderConfigurationEntity CreateConfiguration(Guid libraryId, Guid pluginId, int rank)
{
return new LibraryMetadataProviderConfigurationEntity
{
Id = Guid.NewGuid(),
LibraryId = libraryId,
PluginId = pluginId,
IsEnabled = false,
Rank = rank,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
}
}
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using EntityFrameworkCore.Testing.NSubstitute;
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.Repositories.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Domain.SharedKernel.Common.Errors;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginRepository"/> class.
/// </summary>
public class PluginRepositoryTests
{
private readonly LuminaDbContext _mockContext;
private readonly PluginRepository _sut;
/// <summary>
/// Initializes a new instance of the <see cref="PluginRepositoryTests"/> class.
/// </summary>
public PluginRepositoryTests()
{
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
_sut = new PluginRepository(_mockContext);
}
[Fact]
public async Task GetByIdAsync_WhenPluginExists_ShouldReturnIt()
{
// Arrange
PluginEntity plugin = CreatePluginEntity();
_mockContext.Plugins.Add(plugin);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<PluginEntity?> result = await _sut.GetByIdAsync(plugin.Id, CancellationToken.None);
// Assert
Assert.False(result.IsError);
Assert.Equal(plugin.Id, result.Value!.Id);
}
[Fact]
public async Task UpsertAsync_WhenPluginDoesNotExist_ShouldInsertIt()
{
// Arrange
PluginEntity plugin = CreatePluginEntity();
// Act
ErrorOr<Updated> result = await _sut.UpsertAsync(plugin, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsError);
Assert.Single(_mockContext.Plugins);
}
[Fact]
public async Task UpsertAsync_WhenPluginExists_ShouldUpdateDetectionFieldsAndPreserveSettings()
{
// Arrange
PluginEntity plugin = CreatePluginEntity();
plugin.SettingsJson = """{"preferredLanguage":"en"}""";
_mockContext.Plugins.Add(plugin);
await _mockContext.SaveChangesAsync();
PluginEntity updatedPlugin = CreatePluginEntity(plugin.Id);
updatedPlugin.Name = "Updated Name";
updatedPlugin.SettingsJson = null; // the stored settings must be preserved
// Act
ErrorOr<Updated> result = await _sut.UpsertAsync(updatedPlugin, CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsError);
PluginEntity retrievedPlugin = _mockContext.Plugins.Single();
Assert.Equal("Updated Name", retrievedPlugin.Name);
Assert.Equal("""{"preferredLanguage":"en"}""", retrievedPlugin.SettingsJson);
}
[Fact]
public async Task UpdateSettingsAsync_WhenPluginExists_ShouldUpdateItsSettings()
{
// Arrange
PluginEntity plugin = CreatePluginEntity();
_mockContext.Plugins.Add(plugin);
await _mockContext.SaveChangesAsync();
// Act
ErrorOr<Updated> result = await _sut.UpdateSettingsAsync(plugin.Id, """{"preferredLanguage":"fr"}""", CancellationToken.None);
await _mockContext.SaveChangesAsync();
// Assert
Assert.False(result.IsError);
Assert.Equal("""{"preferredLanguage":"fr"}""", _mockContext.Plugins.Single().SettingsJson);
}
[Fact]
public async Task UpdateSettingsAsync_WhenPluginDoesNotExist_ShouldReturnError()
{
// Act
ErrorOr<Updated> result = await _sut.UpdateSettingsAsync(Guid.NewGuid(), null, CancellationToken.None);
// Assert
Assert.True(result.IsError);
Assert.Equal(Errors.Plugins.PluginNotFound, result.FirstError);
}
private static PluginEntity CreatePluginEntity(Guid? id = null)
{
return new PluginEntity
{
Id = id ?? Guid.NewGuid(),
Name = "Test Plugin",
Author = "Lumina",
Version = "1.0.0",
Description = "A test plugin.",
LoadStatus = PluginLoadStatus.Loaded,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedOnUtc = DateTime.UtcNow,
UpdatedBy = default
};
}
}