mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #135 from BinaryAlley/feature/improved-media-library-scanning
Feature/improved media library scanning
This commit is contained in:
123 files changed
+9863
-1233
No files matched your search
@@ -76,6 +76,7 @@ dotnet_style_readonly_field = true:error
|
||||
|
||||
# Parameter preferences
|
||||
dotnet_code_quality_unused_parameters = all:suggestion
|
||||
dotnet_diagnostic.CA1859.severity = none
|
||||
|
||||
# Strings
|
||||
csharp_style_prefer_string_interpolation = true:suggestion
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# AGENTS.md
|
||||
|
||||
Lumina is a self-hosted media server: an API server (FastEndpoints + EF Core/SQLite) and a
|
||||
web client (ASP.NET Core MVC + SignalR), written in Clean Architecture / DDD, targeting .NET 9.
|
||||
|
||||
## Build / test / lint
|
||||
- Solution is `src/Lumina.sln` (run all dotnet commands from the repo root with that path).
|
||||
- There is NO separate lint/format step. `dotnet build` IS the linter: `.editorconfig` marks
|
||||
style rules as `error` and every project sets `TreatWarningsAsErrors=true` (NU1901-1904 excluded).
|
||||
- CI order (`run-tests.yml`): `dotnet restore src/Lumina.sln` -> `dotnet build src/Lumina.sln --no-restore`
|
||||
-> `dotnet test src/Lumina.sln --no-build`, on Ubuntu/Windows/macOS for PRs to `master`.
|
||||
- Focused test: `dotnet test tests/UnitTests/Lumina.Domain.UnitTests` or add
|
||||
`--filter FullyQualifiedName~...` to the solution-wide run. Some file-system suites have
|
||||
historically flaky tests (parallelization is disabled in several projects).
|
||||
|
||||
## C# conventions (enforced by .editorconfig as errors, build FAILURES if violated)
|
||||
- Never use `var` (error); use explicit types + target-typed `new()`.
|
||||
- File-scoped namespaces, one type per file, no primary constructors, no top-level statements.
|
||||
- No expression-bodied methods/constructors (error); single-line property getters only.
|
||||
- No braces around single-statement `if`/`for` (error); braces always on a new line.
|
||||
- Use collection expression (`[]`) syntax for collections.
|
||||
- Explicit `using (…) {}` blocks only, no `using` declarations (error).
|
||||
- `is null` for null checks; `_camelCase` private readonly fields, `s_` static fields,
|
||||
ALL_CAPS constants, `I`-prefixed interfaces. Names must be explicit, even if they become long. Domain names must match the Ubiquitous Language. Lambda expression parameters must be named plainly, do not use "x" or any single letter shortcuts. Domain must *never* use nullable values, it should make use of the `Optional<T>` and `ErrorOr<T>` types that are available.
|
||||
- Method parameters go on a single line, unless they substantially go off screen edge on a 1920px wide monitor, when they should be wrapped.
|
||||
- Records should ALWAYS wrap their parameters, and the opening parenthesis should be on the same line as the
|
||||
record name, while the closing parenthesis should be on its own line, unindented
|
||||
- Comments should be added for relevant blocks of code and they shouldn't explain the "what" (the code already does that),
|
||||
they should explain the "why". They should be wrapped only when they substantially go off screen edge on a 1920px wide monitor.
|
||||
- XML doc comments on every public (and also private properties and methods) construct; usings wrapped in a
|
||||
`#region ========= USING =========` block; 4-space indent, LF endings.
|
||||
- Enum members have documentation, and an empty line between them. Enums have summaries that start with `Enumeration for `.
|
||||
- Commit messages in third person singular.
|
||||
- In all the generated text, no em-dashes, en-dashes, or emojis. Use `-`, `,`, `:`, or split the sentence.
|
||||
- Lambda expressions parameters should be named properly and descriptive, do not use names shortened to a single letter, or other common anti patterns.
|
||||
- Rule violations return `ErrorOr<T>` - never throw exceptions unless explicitly needed, for example, in startup configuration files.
|
||||
- In XML documentation, use `<see langword="etc"/>` for language specific references, don't use the generic `<c>etc</c>`. Documentation for methods should
|
||||
NOT expose internal implementation (don't explain how a method does things in its summary, unless it is really relevant, and if it is, put it in <remarks> blocks).
|
||||
- prefer avoiding `/// <inheritdoc/>` on classes implementing interface members, usually users work in the implementing class and they should
|
||||
see the documentation without having to dig to the interface all the time.
|
||||
- Boolean members (fields, properties, methods returning boolean values) should always start with a verb indicating a true or false output: is, are, should, has, was, can, etc.
|
||||
- Classes should *always* have fields at the top, then read-only fields underneath, then properties, then constructors, then methods.
|
||||
|
||||
## Branching (CI-enforced)
|
||||
- Branch names MUST start with `feature/`, `bugfix/`, `hotfix/`, `documentation/`, `refactor/`, or `other/`.
|
||||
- PRs target `master`; the validate workflows reject other branch names.
|
||||
|
||||
## Architecture / wiring
|
||||
- Layers: Domain (bounded contexts/aggregates under `Core`), Application (Mediator commands/queries/
|
||||
handlers/validators + domain event handlers), Infrastructure (library scan jobs, services),
|
||||
DataAccess (EF Core DbContext, repositories/UoW, migrations), Presentation.Api (FastEndpoints under
|
||||
`Core/Endpoints/...` mirroring Application queries), Presentation.Web (MVC, localized
|
||||
`{culture}/{*catchall}` routes, resx localization across ~10 cultures), Contracts (shared DTOs).
|
||||
- Each project has ALWAYS two top level directories: `Common`, where things common to that project go (ie: DI, Models, Errors, etc), and `Core`,
|
||||
where things that make up the central part of that project reside.
|
||||
- API contracts have their own dedicated project.
|
||||
- As specified by DDD, objects should not be directly referenced cross-bounded contexts, instead, only Id objects placed in `ExternalIdentifiers`
|
||||
directories should be used. This loose coupling will greatly help a possible future migration to a micro services architecture.
|
||||
- Composition root: each app's `Program.cs` registers all layers via `Add<Layer>LayerServices()`
|
||||
DI extensions in each project's `Common/DependencyInjection/`.
|
||||
- Request flow: FastEndpoints endpoint -> Mediator handler -> repository/UoW -> EF Core SQLite.
|
||||
Domain events fire via `EventualConsistencyMiddleware` (excluded for the `/scanProgressHub` SignalR hub).
|
||||
- Mediator is source-generated (`Mediator.SourceGenerator`).
|
||||
- Requests and Responses API contracts should immediately be decoupled by internal workings via manual mappings done as extension methods (located in `Lumina.Application\Common\Mapping`
|
||||
- API contracts should be as much as possible records. Database entities should have as many properties as `required` and `init`. Domain properties should all be `private set`.
|
||||
|
||||
## Data / EF Core
|
||||
- SQLite `Lumina.db` is created next to the API output binary; `MigrateAsync()` runs on API startup.
|
||||
- Schema changes require a new migration in `src/Lumina.DataAccess/Common/Migrations`
|
||||
(`dotnet ef migrations add ...`; EF Design is referenced in the API csproj).
|
||||
- Entity/configs live in `src/Lumina.DataAccess/Common/Configuration`.
|
||||
|
||||
## Running locally
|
||||
- API: `dotnet run --project src/Lumina.Presentation.Api` -> http://localhost:5214 (Scalar/OpenAPI UI).
|
||||
- Web: `dotnet run --project src/Lumina.Presentation.Web` -> http://localhost:5012.
|
||||
- API `CorsSettings:AllowedOrigins` must include the Web app's Kestrel URL or SignalR fails
|
||||
(docs/INSTALL.md); `ServerConfiguration:BaseAddress/Port` in Web appsettings points at the API.
|
||||
- `appsettings.development.json` / `appsettings.test.json` are GITIGNORED (`*.[Dd]evelopment.json`,
|
||||
`*.[Tt]est.json`) and hold JWT/encryption dev secrets. Never commit them. Shared config lives in
|
||||
`src/Lumina.Infrastructure/appsettings.shared*.json`.
|
||||
- Serilog `LOG_PATH` env var (defaults to `/logs` in containers, `bin/.../logs` locally).
|
||||
- Stale: both `Dockerfile`s still use .NET 8 base images while projects target net9.0 — docker
|
||||
builds are likely broken until updated.
|
||||
- Manual API testing: `docs/technical/requests/**/*.http` (REST Client; dev host http://localhost:5214).
|
||||
- Behind a reverse proxy, forward `X-Forwarded-For` or IP-based rate limiting becomes global (docs/INSTALL.md).
|
||||
|
||||
## Tests
|
||||
- Each tested class has an identically named test class (ie: `AddBookCommandHandler` - `AddBookCommandHandlerTests`),
|
||||
and the paths must match precisely (the test class should follow the same directory structure inside the test project
|
||||
as the tested class has in its project. Fixture classes go in the same directory structure as the members they are
|
||||
mocking, with an additional `Fixtures/` subdirectory, and they have the same name as the class they mock, plus the `Fixture` suffix.
|
||||
- `tests/UnitTests/<Project>.UnitTests`: xUnit + NSubstitute + AutoFixture + Bogus; fixtures in
|
||||
`Fixtures/` dirs; xUnit `Assert.*` only (FluentAssertions was removed); naming
|
||||
`MethodToTest_WhenCondition_ShouldAssertion`; allowed test libraries are a fixed list (docs/CONTRIBUTING.md).
|
||||
- `tests/IntegrationTests/...`: `WebApplicationFactory` + in-memory SQLite (`LuminaApiFactory`,
|
||||
`AuthenticatedLuminaApiFactory`), require `appsettings.test.json` + shared configs.
|
||||
- CI runs on 3 OSes: keep file-system tests platform-agnostic.
|
||||
- Reference docs: docs/CONTRIBUTING.md (style/tests), docs/INSTALL.md, docs/technical/ (domain, ADRs, .http requests).
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a directory scan fingerprint, holding the last write time of a directory of a media library, used to skip the scanning of directories that have not changed since the last scan.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; Path: {Path}")]
|
||||
public class DirectoryScanFingerprintEntity : IStorageEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the directory scan fingerprint.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library to which this directory scan fingerprint belongs.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the directory to which this directory scan fingerprint belongs.
|
||||
/// </summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last write time of the directory, in UTC, at the moment when the directory was scanned.
|
||||
/// </summary>
|
||||
public required DateTime LastWriteTimeUtc { get; init; }
|
||||
}
|
||||
+7
-2
@@ -63,12 +63,17 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity
|
||||
/// <summary>
|
||||
/// Gets whether this media library should update the metadata of its elements from the web, or not.
|
||||
/// </summary>
|
||||
public bool DownloadMedatadaFromWeb { get; init; }
|
||||
public bool DownloadMetadataFromWeb { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// </summary>
|
||||
public bool SaveMetadataInMediaDirectories { get; init; }
|
||||
public bool ShouldSaveMetadataInMediaDirectories { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library should skip the directories whose contents have not changed since the last scan, during the scan.
|
||||
/// </summary>
|
||||
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user that owns the media library.
|
||||
|
||||
+7
-2
@@ -23,6 +23,11 @@ public class LibraryScanResultEntity : IStorageEntity
|
||||
/// </summary>
|
||||
public required Guid LibraryScanId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the status of the media library scan file.
|
||||
/// </summary>
|
||||
public required LibraryScanFileStatus Status { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the media library scan file.
|
||||
/// </summary>
|
||||
@@ -39,9 +44,9 @@ public class LibraryScanResultEntity : IStorageEntity
|
||||
public required long FileSize { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the modification date of the media library scan file.
|
||||
/// Gets the time and date when the file system file was last modified, stored in ticks.
|
||||
/// </summary>
|
||||
public required DateTime LastModified { get; init; }
|
||||
public required long Ticks { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scan that this scan result belongs to.
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a media library item, representing the current state of a previously scanned media item, as a snapshot.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; Path: {Path}")]
|
||||
public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library scan snapshot item.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library to which this media library scan snapshot item belongs.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the media library scan snapshot item.
|
||||
/// </summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hash calculated for the media library scan snapshot item.
|
||||
/// </summary>
|
||||
public required ulong ContentHash { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size of the media library scan snapshot item, in bytes.
|
||||
/// </summary>
|
||||
public required long FileSize { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the time and date when the media library scan snapshot item was last modified, stored in ticks.
|
||||
/// </summary>
|
||||
public required long Ticks { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library to which this media library scan snapshot item belongs.
|
||||
/// </summary>
|
||||
public required LibraryEntity Library { get; init; } = null!;
|
||||
|
||||
/// <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; }
|
||||
}
|
||||
+59
@@ -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.MediaLibrary.Management;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a media library scan staging result, holding the file system items discovered during a scan, before they are compared against the media library scan snapshot of the previous scan.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; Path: {Path}")]
|
||||
public class LibraryScanStagingResultsEntity : IStorageEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library scan staging result.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media library scan that this staging result belongs to.
|
||||
/// </summary>
|
||||
public required Guid LibraryScanId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the path of the media library scan staging result.
|
||||
/// </summary>
|
||||
public required string Path { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the size of the media library scan staging result, in bytes.
|
||||
/// </summary>
|
||||
public required long Size { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the time and date when the file system item was last modified, stored in ticks.
|
||||
/// </summary>
|
||||
public required long Ticks { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hash calculated for the media library scan staging result.
|
||||
/// </summary>
|
||||
public required ulong ContentHash { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hash of the same file system item, as stored in the media library scan snapshot of a previous scan, or 0 if the file system item is new.
|
||||
/// </summary>
|
||||
public required ulong PreviousContentHash { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library scan staging result represents a file system item that needs its content to be hashed, because it is either new, or it has changed since the previous scan.
|
||||
/// </summary>
|
||||
public required bool NeedsRehash { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library scan staging result represents a file system item that was not present in the media library scan snapshot of a previous scan.
|
||||
/// </summary>
|
||||
public required bool IsNew { get; init; }
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
|
||||
/// <summary>
|
||||
/// Interface defining the "insert range" action for interacting with a generic persistance medium.
|
||||
/// </summary>
|
||||
/// <typeparam name="TModel">The type used for the insert range action. It should implement <see cref="IStorageEntity"/>.</typeparam>
|
||||
public interface IInsertRangeRepositoryAction<TModel> where TModel : IStorageEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Saves a collection of elements of type <typeparamref name="TModel"/> in the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="entities">The elements to be saved.</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<Created>> InsertRangeAsync(IReadOnlyCollection<TModel> entities, CancellationToken cancellationToken);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.MediaLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for directory scan fingerprints.
|
||||
/// </summary>
|
||||
public interface IDirectoryScanFingerprintRepository : IRepository<DirectoryScanFingerprintEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the directory scan fingerprints of a media library, mapped by the directory path.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the directory scan fingerprints.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of directory scan fingerprints, or an error.</returns>
|
||||
Task<ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Inserts or updates the provided directory scan fingerprints in the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="entities">The directory scan fingerprints 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>> UpsertRangeAsync(IReadOnlyCollection<DirectoryScanFingerprintEntity> entities, CancellationToken cancellationToken);
|
||||
}
|
||||
-12
@@ -1,12 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
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.MediaLibrary;
|
||||
@@ -17,11 +12,4 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
public interface ILibraryScanResultRepository : IRepository<LibraryScanResultEntity>,
|
||||
IInsertRepositoryAction<LibraryScanResultEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all media library scan results that belong to the last scan of a library identified by <paramref name="libraryId"/>, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the results of the last scans.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of <see cref="LibraryScanResultEntity"/>, or an error.</returns>
|
||||
Task<ErrorOr<Dictionary<string, LibraryScanResultEntity>>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
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.MediaLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for media library scan snapshots.
|
||||
/// </summary>
|
||||
public interface ILibraryScanSnapshotRepository : IRepository<LibraryScanSnapshotEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the paths of the media library scan snapshot items that are no longer present in the current scan, meaning they were deleted from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the deleted media library scan snapshot item paths.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths.</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 deleted media library scan snapshot item paths, or an error.</returns>
|
||||
Task<ErrorOr<IReadOnlyList<string>>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
|
||||
/// The operation updates the changed media library scan snapshot items, deletes the ones that are no longer present on disk, adds audit entries for all changed, new and deleted items,
|
||||
/// and clears the staging results of the current scan.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to apply the scan results.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose results are applied.</param>
|
||||
/// <param name="userId">The unique identifier of the user that initiated the media library scan, used for audit purposes.</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>> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for media library scan staging results.
|
||||
/// </summary>
|
||||
public interface ILibraryScanStagingResultsRepository : IRepository<LibraryScanStagingResultsEntity>,
|
||||
IInsertRangeRepositoryAction<LibraryScanStagingResultsEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Marks the media library scan staging results of the current scan by comparing them against the media library scan snapshot of a previous scan, determining which file system items
|
||||
/// are new, which ones changed and need their content hashed, and which ones are unchanged.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are marked.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot is compared against.</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>> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of media library scan staging results of the current scan that need their content hashed.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are counted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the number of staging results that need hashing, or an error.</returns>
|
||||
Task<ErrorOr<int>> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a page of the media library scan staging results that need their content hashed, ordered by path, using keyset pagination.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are retrieved.</param>
|
||||
/// <param name="lastPath">The path of the last retrieved file system item, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
|
||||
/// <param name="pageSize">The maximum number of staging results to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of staging results that need hashing, or an error.</returns>
|
||||
Task<ErrorOr<IReadOnlyList<HashedFileSystemFile>>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the content hashes of the provided media library scan staging results.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are updated.</param>
|
||||
/// <param name="hashedFiles">The file system items whose content hashes are updated.</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>> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection<HashedFileSystemFile> hashedFiles, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Clears all the media library scan staging results of the provided media library scan from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are cleared.</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<Success>> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken);
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
namespace Lumina.Application.Common.Infrastructure.Models.FileSystem;
|
||||
|
||||
/// <summary>
|
||||
/// Generic file system node.
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an item for the payload of the file hashing media library scan job.
|
||||
/// </summary>
|
||||
/// <param name="File">The file to whom <paramref name="FileHash"/> belongs.</param>
|
||||
/// <param name="FileHash">The hash of <paramref name="File"/>.</param>
|
||||
[DebuggerDisplay("File: {File}; FileHash: {FileHash}")]
|
||||
public record ChangedFileSystemFile(FileInfo File, ulong FileHash);
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an item for the payload of the file hashing media library scan job.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Path = {Path}, CurrentHash = {CurrentHash}, OldHash = {OldHash}, Ticks = {Ticks}, Size = {Size}")]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct HashedFileSystemFile : IEquatable<HashedFileSystemFile>
|
||||
{
|
||||
/// <summary>
|
||||
/// The path of the file system file.
|
||||
/// </summary>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The size of the file system file.
|
||||
/// </summary>
|
||||
public long Size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The current hash obtained by sampling the file system file contents.
|
||||
/// </summary>
|
||||
public ulong CurrentHash { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The old hash of the file system file, stored at the previous scan.
|
||||
/// </summary>
|
||||
public ulong OldHash { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The time and date when the file system file was last modified, stored in ticks.
|
||||
/// </summary>
|
||||
public long Ticks { get; set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public readonly bool Equals(HashedFileSystemFile other)
|
||||
{
|
||||
return Size == other.Size && CurrentHash == other.CurrentHash && OldHash == other.OldHash && Ticks == other.Ticks && Path == other.Path;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override readonly bool Equals(object? obj)
|
||||
{
|
||||
return obj is HashedFileSystemFile item && Equals(item);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static bool operator ==(HashedFileSystemFile left, HashedFileSystemFile right)
|
||||
{
|
||||
return left.Equals(right);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public static bool operator !=(HashedFileSystemFile left, HashedFileSystemFile right)
|
||||
{
|
||||
return !(left == right);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override readonly int GetHashCode()
|
||||
{
|
||||
return HashCode.Combine(Size, CurrentHash, OldHash, Ticks, Path);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -19,13 +17,8 @@ public interface IFileHashService
|
||||
/// Hashes <paramref name="files"/> by sampling chunks from them.
|
||||
/// </summary>
|
||||
/// <param name="files">The collection of files to hash.</param>
|
||||
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
|
||||
/// <param name="callback">Callback to invoke during processing of elements.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
|
||||
Task<List<ChangedFileSystemFile>> HashFilesAsync(
|
||||
List<FileInfo> files,
|
||||
Dictionary<string, LibraryScanResultEntity> previousScanResults,
|
||||
Func<Task> callback,
|
||||
CancellationToken cancellationToken);
|
||||
/// <returns>A collection of the hashed files, along with their hashes.</returns>
|
||||
Task<List<HashedFileSystemFile>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFile> files, Func<Task> callback, CancellationToken cancellationToken);
|
||||
}
|
||||
+3
-2
@@ -27,8 +27,9 @@ public static class AddMediaLibraryRequestMapping
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -33,8 +33,9 @@ public static class LibraryEntityMapping
|
||||
repositoryEntity.CoverImage,
|
||||
repositoryEntity.IsEnabled,
|
||||
repositoryEntity.IsLocked,
|
||||
repositoryEntity.DownloadMedatadaFromWeb,
|
||||
repositoryEntity.SaveMetadataInMediaDirectories,
|
||||
repositoryEntity.DownloadMetadataFromWeb,
|
||||
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
repositoryEntity.UpdatedOnUtc
|
||||
);
|
||||
@@ -45,7 +46,7 @@ public static class LibraryEntityMapping
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly converted <see cref="Library"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully converted <see cref="Library"/>, or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<Library> ToDomainEntity(this LibraryEntity repositoryEntity)
|
||||
{
|
||||
@@ -58,8 +59,9 @@ public static class LibraryEntityMapping
|
||||
repositoryEntity.CoverImage,
|
||||
repositoryEntity.IsEnabled,
|
||||
repositoryEntity.IsLocked,
|
||||
repositoryEntity.DownloadMedatadaFromWeb,
|
||||
repositoryEntity.SaveMetadataInMediaDirectories,
|
||||
repositoryEntity.DownloadMetadataFromWeb,
|
||||
repositoryEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -29,8 +29,9 @@ public static class LibraryMapping
|
||||
CoverImage = domainEntity.CoverImage,
|
||||
IsEnabled = domainEntity.IsEnabled,
|
||||
IsLocked = domainEntity.IsLocked,
|
||||
DownloadMedatadaFromWeb = domainEntity.DownloadMedatadaFromWeb,
|
||||
SaveMetadataInMediaDirectories = domainEntity.SaveMetadataInMediaDirectories,
|
||||
DownloadMetadataFromWeb = domainEntity.DownloadMetadataFromWeb,
|
||||
ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity()
|
||||
{
|
||||
Id = scanId.Value,
|
||||
|
||||
+3
-2
@@ -27,8 +27,9 @@ public static class UpdateLibraryRequestMapping
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -17,8 +17,9 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="DownloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="SaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public record AddLibraryCommand(
|
||||
string? Title,
|
||||
@@ -27,6 +28,7 @@ public record AddLibraryCommand(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMedatadaFromWeb,
|
||||
bool SaveMetadataInMediaDirectories
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
) : IRequest<ErrorOr<LibraryResponse>>;
|
||||
+4
-3
@@ -65,7 +65,7 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LibraryResponse"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -98,8 +98,9 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories,
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
[]
|
||||
);
|
||||
|
||||
|
||||
+6
-4
@@ -19,8 +19,9 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="DownloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="SaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public record UpdateLibraryCommand(
|
||||
Guid Id,
|
||||
@@ -31,6 +32,7 @@ public record UpdateLibraryCommand(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMedatadaFromWeb,
|
||||
bool SaveMetadataInMediaDirectories
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
) : IRequest<ErrorOr<LibraryResponse>>;
|
||||
+4
-3
@@ -68,7 +68,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly updated <see cref="LibraryResponse"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="LibraryResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -110,8 +110,9 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
request.CoverImage,
|
||||
request.IsEnabled,
|
||||
request.IsLocked,
|
||||
request.DownloadMedatadaFromWeb,
|
||||
request.SaveMetadataInMediaDirectories,
|
||||
request.DownloadMetadataFromWeb,
|
||||
request.ShouldSaveMetadataInMediaDirectories,
|
||||
request.ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
|
||||
);
|
||||
if (createLibraryResult.IsError)
|
||||
|
||||
+26
-1
@@ -9,6 +9,10 @@ using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -22,17 +26,29 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
public class LibraryScanCancelledDomainEventHandler : INotificationHandler<LibraryScanCancelledDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanningService _mediaLibraryScanningService;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly ILibraryScanRepository _libraryScanRepository;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaLibraryScanningService">Injected service for scanning media libraries.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryScanCancelledDomainEventHandler(IMediaLibraryScanningService mediaLibraryScanningService, IUnitOfWork unitOfWork)
|
||||
public LibraryScanCancelledDomainEventHandler(
|
||||
IMediaLibraryScanningService mediaLibraryScanningService,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_mediaLibraryScanningService = mediaLibraryScanningService;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
_libraryScanRepository = unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -58,5 +74,14 @@ public class LibraryScanCancelledDomainEventHandler : INotificationHandler<Libra
|
||||
ErrorOr<Success> cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value);
|
||||
if (cancelScanResult.IsError)
|
||||
throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors);
|
||||
|
||||
// release the scan processing resources
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId));
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(compositeId);
|
||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId);
|
||||
ErrorOr<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (clearStagingResult.IsError)
|
||||
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
||||
}
|
||||
}
|
||||
+25
-4
@@ -9,6 +9,8 @@ using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -22,16 +24,26 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Events;
|
||||
public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryScanFailedDomainEvent>
|
||||
{
|
||||
private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier;
|
||||
private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker;
|
||||
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanCancelledDomainEventHandler"/> class.
|
||||
/// Initializes a new instance of the <see cref="LibraryScanFailedDomainEventHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="mediaLibrariesScanCancellationTracker">Injected tracker used for canceling media library scans.</param>
|
||||
/// <param name="mediaLibrariesScanProgressTracker">Injected tracker used for media library scans progress.</param>
|
||||
/// <param name="debouncedLibraryScanProgressNotifier">Injected service for notifying media libraries scan progress changes to third parties.</param>
|
||||
public LibraryScanFailedDomainEventHandler(IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier, IUnitOfWork unitOfWork)
|
||||
public LibraryScanFailedDomainEventHandler(
|
||||
IMediaLibraryScanProgressNotifier debouncedLibraryScanProgressNotifier,
|
||||
IMediaLibrariesScanCancellationTracker mediaLibrariesScanCancellationTracker,
|
||||
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
|
||||
IUnitOfWork unitOfWork)
|
||||
{
|
||||
_debouncedLibraryScanProgressNotifier = debouncedLibraryScanProgressNotifier;
|
||||
_mediaLibrariesScanCancellationTracker = mediaLibrariesScanCancellationTracker;
|
||||
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
@@ -43,6 +55,7 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryS
|
||||
public async ValueTask Handle(LibraryScanFailedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
// get the library scan from the repository
|
||||
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(
|
||||
@@ -69,8 +82,16 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler<LibraryS
|
||||
throw new EventualConsistencyException(updateLibraryScanResult.FirstError, updateLibraryScanResult.Errors);
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// notify SignalR clients that the library scan failed
|
||||
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// release the scan processing resources, regardless of whether the scan was already marked as failed by a concurrent job
|
||||
_mediaLibrariesScanCancellationTracker.RemoveScan(domainEvent.MediaLibraryScanCompositeId);
|
||||
_mediaLibrariesScanProgressTracker.RemoveScanProgress(domainEvent.MediaLibraryScanCompositeId);
|
||||
ErrorOr<Success> clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (clearStagingResult.IsError)
|
||||
throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors);
|
||||
|
||||
// notify SignalR clients that the library scan failed
|
||||
await _debouncedLibraryScanProgressNotifier.SendLibraryScanFailedEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -63,7 +63,7 @@ public class LibraryScanQueuedDomainEventHandler : INotificationHandler<LibraryS
|
||||
|
||||
// start the media library scan
|
||||
ErrorOr<Success> startScanResult = await _mediaLibraryScanningService.StartScanAsync(
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMedatadaFromWeb, cancellationToken).ConfigureAwait(false);
|
||||
libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false);
|
||||
if (startScanResult.IsError)
|
||||
throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors);
|
||||
|
||||
|
||||
@@ -13,8 +13,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library. Optional.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.</param>
|
||||
/// <param name="DownloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="SaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.</param>
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.</param>
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public record AddLibraryRequest(
|
||||
string? Title,
|
||||
@@ -23,6 +24,7 @@ public record AddLibraryRequest(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMedatadaFromWeb,
|
||||
bool SaveMetadataInMediaDirectories
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
@@ -18,8 +18,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management;
|
||||
/// <param name="CoverImage">The path of the image file used as the cover for the library. Optional.</param>
|
||||
/// <param name="IsEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.</param>
|
||||
/// <param name="IsLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.</param>
|
||||
/// <param name="DownloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="SaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// <param name="DownloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not. Optional.</param>
|
||||
/// <param name="ShouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// <param name="ShouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.</param>
|
||||
[DebuggerDisplay("Title: {Title}")]
|
||||
public record class UpdateLibraryRequest(
|
||||
Guid Id,
|
||||
@@ -30,6 +31,7 @@ public record class UpdateLibraryRequest(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMedatadaFromWeb,
|
||||
bool SaveMetadataInMediaDirectories
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan
|
||||
);
|
||||
@@ -28,8 +28,9 @@ public record LibraryResponse(
|
||||
string? CoverImage,
|
||||
bool IsEnabled,
|
||||
bool IsLocked,
|
||||
bool DownloadMedatadaFromWeb,
|
||||
bool SaveMetadataInMediaDirectories,
|
||||
bool DownloadMetadataFromWeb,
|
||||
bool ShouldSaveMetadataInMediaDirectories,
|
||||
bool ShouldSkipUnchangedDirectoriesDuringScan,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="DirectoryScanFingerprintEntity"/> entity.
|
||||
/// </summary>
|
||||
public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration<DirectoryScanFingerprintEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="DirectoryScanFingerprintEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<DirectoryScanFingerprintEntity> builder)
|
||||
{
|
||||
builder.ToTable("DirectoryScanFingerprints");
|
||||
// composite key, so that each directory scan fingerprint is uniquely identified within its library by its path
|
||||
builder.HasKey(directoryScanFingerprint => new { directoryScanFingerprint.LibraryId, directoryScanFingerprint.Path });
|
||||
|
||||
// one library with many directory scan fingerprints
|
||||
builder.HasOne<LibraryEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(directoryScanFingerprint => directoryScanFingerprint.LibraryId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(directoryScanFingerprint => directoryScanFingerprint.Id)
|
||||
.ValueGeneratedNever()
|
||||
.HasColumnOrder(0);
|
||||
|
||||
builder.Property(directoryScanFingerprint => directoryScanFingerprint.Path)
|
||||
.HasMaxLength(1024)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(directoryScanFingerprint => directoryScanFingerprint.LastWriteTimeUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
// enables fast lookups of the directory scan fingerprints of a library
|
||||
builder.HasIndex(directoryScanFingerprint => directoryScanFingerprint.LibraryId);
|
||||
}
|
||||
}
|
||||
@@ -46,13 +46,16 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
builder.Property(library => library.IsLocked)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(library => library.DownloadMedatadaFromWeb)
|
||||
builder.Property(library => library.DownloadMetadataFromWeb)
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(library => library.SaveMetadataInMediaDirectories)
|
||||
builder.Property(library => library.ShouldSaveMetadataInMediaDirectories)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(library => library.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// one user with many libraries
|
||||
builder.HasOne(library => library.User)
|
||||
.WithMany(user => user.Libraries)
|
||||
@@ -85,18 +88,18 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
// audit
|
||||
builder.Property(library => library.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(8);
|
||||
.HasColumnOrder(9);
|
||||
|
||||
builder.Property(library => library.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(9);
|
||||
.HasColumnOrder(10);
|
||||
|
||||
builder.Property(library => library.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(10);
|
||||
.HasColumnOrder(11);
|
||||
|
||||
builder.Property(library => library.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(11);
|
||||
.HasColumnOrder(12);
|
||||
}
|
||||
}
|
||||
@@ -57,5 +57,11 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
||||
builder.Property(libraryScan => libraryScan.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
// Indexes
|
||||
|
||||
// enables fast lookup of latest non-running scans per library
|
||||
builder.HasIndex(libraryScan => new { libraryScan.LibraryId, libraryScan.Status, libraryScan.CreatedOnUtc })
|
||||
.IsDescending(true, false, true); // CreatedOnUtc DESC
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,12 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
||||
public void Configure(EntityTypeBuilder<LibraryScanResultEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryScanResults");
|
||||
// composite key for efficient scan-specific lookups
|
||||
// composite key for efficient scan-specific lookups (paths are enforced as UNIQUE within the same scan)
|
||||
builder.HasKey(libraryScanResult => new { libraryScanResult.LibraryScanId, libraryScanResult.Path });
|
||||
|
||||
// one library scan with many library scan results
|
||||
builder.HasOne(libraryScanResult => libraryScanResult.LibraryScan)
|
||||
.WithMany()
|
||||
.WithMany(libraryScan => libraryScan.LibraryScanResults)
|
||||
.HasForeignKey(libraryScanResult => libraryScanResult.LibraryScanId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
@@ -46,15 +46,19 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(libraryScanResult => libraryScanResult.LastModified)
|
||||
builder.Property(libraryScanResult => libraryScanResult.Ticks)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// Indexes
|
||||
builder.HasIndex(libraryScanResult => new { libraryScanResult.ContentHash, libraryScanResult.FileSize, libraryScanResult.Path })
|
||||
.IsUnique();
|
||||
builder.Property(libraryScanResult => libraryScanResult.Status)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.HasIndex(libraryScanResult => libraryScanResult.Path)
|
||||
.IsUnique();
|
||||
// Indexes
|
||||
builder.HasIndex(libraryScanResult => new { libraryScanResult.ContentHash, libraryScanResult.FileSize, libraryScanResult.Path });
|
||||
|
||||
builder.HasIndex(libraryScanResult => libraryScanResult.Path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="LibraryScanSnapshotEntity"/> entity.
|
||||
/// </summary>
|
||||
public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<LibraryScanSnapshotEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="LibraryScanSnapshotEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<LibraryScanSnapshotEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryScanSnapshots");
|
||||
// composite key, so that each media library scan snapshot item is uniquely identified within its library by its path
|
||||
builder.HasKey(libraryScanSnapshot => new { libraryScanSnapshot.LibraryId, libraryScanSnapshot.Path });
|
||||
|
||||
// one library with many media library scan snapshot items
|
||||
builder.HasOne(libraryScanSnapshot => libraryScanSnapshot.Library)
|
||||
.WithMany()
|
||||
.HasForeignKey(libraryScanSnapshot => libraryScanSnapshot.LibraryId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.Id)
|
||||
.ValueGeneratedNever()
|
||||
.HasColumnOrder(0);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.Path)
|
||||
.HasMaxLength(1024)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.ContentHash)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.FileSize)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.Ticks)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// audit
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// enables fast lookups of the media library scan snapshot items of a library
|
||||
builder.HasIndex(libraryScanSnapshot => libraryScanSnapshot.LibraryId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="LibraryScanStagingResultsEntity"/> entity.
|
||||
/// </summary>
|
||||
public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration<LibraryScanStagingResultsEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="LibraryScanStagingResultsEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<LibraryScanStagingResultsEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryScanStagingResults");
|
||||
// composite key, so that each media library scan staging result is uniquely identified within its scan by its path
|
||||
builder.HasKey(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.Path });
|
||||
|
||||
// one media library scan with many media library scan staging results
|
||||
builder.HasOne<LibraryScanEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(libraryScanStagingResult => libraryScanStagingResult.LibraryScanId)
|
||||
.IsRequired()
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.Id)
|
||||
.ValueGeneratedNever()
|
||||
.HasColumnOrder(0);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.Path)
|
||||
.HasMaxLength(1024)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.Size)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.Ticks)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.ContentHash)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.PreviousContentHash)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.NeedsRehash)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(libraryScanStagingResult => libraryScanStagingResult.IsNew)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(7);
|
||||
|
||||
// enables fast lookups of the staging results of a scan that need their content hashed
|
||||
builder.HasIndex(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.NeedsRehash });
|
||||
}
|
||||
}
|
||||
Generated
+877
@@ -0,0 +1,877 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
[DbContext(typeof(LuminaDbContext))]
|
||||
[Migration("20250302132630_AddsLibraryScanFileStatusColumn")]
|
||||
partial class AddsLibraryScanFileStatusColumn
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("GenreId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "GenreId");
|
||||
|
||||
b.HasIndex("GenreId");
|
||||
|
||||
b.ToTable("BookGenres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TagId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "TagId");
|
||||
|
||||
b.HasIndex("TagId");
|
||||
|
||||
b.ToTable("BookTags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("PermissionName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Permissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("RoleName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("RoleId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("RoleId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RolePermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("UserId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserPermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.HasIndex("UserId", "RoleId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Genres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("CoverImage")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<bool>("DownloadMedatadaFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsLocked")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("LibraryType")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<bool>("SaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("Libraries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("LibraryScans", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryScanId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasMaxLength(24)
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<long>("FileSize")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<DateTime>("LastModified")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("LibraryScanEntityId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanEntityId");
|
||||
|
||||
b.HasIndex("Path")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ContentHash", "FileSize", "Path")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("LibraryScanResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ASIN")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(21);
|
||||
|
||||
b.Property<string>("AppleBooksId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(29);
|
||||
|
||||
b.Property<string>("BarnesAndNobleId")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(33);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(32);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("Edition")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(19);
|
||||
|
||||
b.Property<string>("Format")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(18);
|
||||
|
||||
b.Property<string>("GoodreadsId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(22);
|
||||
|
||||
b.Property<string>("GoogleBooksId")
|
||||
.HasMaxLength(12)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(27);
|
||||
|
||||
b.Property<string>("LCCN")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(23);
|
||||
|
||||
b.Property<string>("LanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("LanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<string>("LanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<string>("LibraryThingId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(26);
|
||||
|
||||
b.Property<string>("OCLCNumber")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(24);
|
||||
|
||||
b.Property<string>("OpenLibraryId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(25);
|
||||
|
||||
b.Property<string>("OriginalLanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<string>("OriginalLanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<string>("OriginalLanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(15);
|
||||
|
||||
b.Property<DateOnly?>("OriginalReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<int?>("OriginalReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("OriginalTitle")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int?>("PageCount")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(17);
|
||||
|
||||
b.Property<string>("Publisher")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(16);
|
||||
|
||||
b.Property<DateOnly?>("ReReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<int?>("ReReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("ReleaseCountry")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("ReleaseVersion")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(35);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(34);
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(20);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("TempPassword")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime?>("TempPasswordCreated")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("TotpSecret")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("GenreId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("TagId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("Role");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("UserRoles")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithOne("UserRole")
|
||||
.HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Role");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("Libraries")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(260)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("Path");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("LibraryId");
|
||||
|
||||
b1.ToTable("LibraryContentLocations", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("LibraryId");
|
||||
});
|
||||
|
||||
b.Navigation("ContentLocations");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanEntityId");
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("LibraryScan");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("MaxValue")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("Value")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<int?>("VoteCount")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookRatings", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Format")
|
||||
.IsRequired()
|
||||
.HasMaxLength(6)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasMaxLength(13)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("ISBN");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookISBNs", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.Navigation("ISBNs");
|
||||
|
||||
b.Navigation("Ratings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserRoles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScans");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScanResults");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Navigation("Libraries");
|
||||
|
||||
b.Navigation("LibraryScans");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
|
||||
b.Navigation("UserRole");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations;
|
||||
|
||||
/// <inheritdoc />
|
||||
public partial class AddsLibraryScanFileStatusColumn : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Status",
|
||||
table: "LibraryScanResults",
|
||||
type: "TEXT",
|
||||
maxLength: 10,
|
||||
nullable: false,
|
||||
defaultValue: "")
|
||||
.Annotation("Relational:ColumnOrder", 5);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Status",
|
||||
table: "LibraryScanResults");
|
||||
}
|
||||
}
|
||||
Generated
+877
@@ -0,0 +1,877 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
[DbContext(typeof(LuminaDbContext))]
|
||||
[Migration("20250317192401_AddsLibraryScanResultTickColumn")]
|
||||
partial class AddsLibraryScanResultTickColumn
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("GenreId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "GenreId");
|
||||
|
||||
b.HasIndex("GenreId");
|
||||
|
||||
b.ToTable("BookGenres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TagId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "TagId");
|
||||
|
||||
b.HasIndex("TagId");
|
||||
|
||||
b.ToTable("BookTags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("PermissionName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Permissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("RoleName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("RoleId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("RoleId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RolePermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("UserId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserPermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.HasIndex("UserId", "RoleId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Genres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("CoverImage")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<bool>("DownloadMedatadaFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsLocked")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("LibraryType")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<bool>("SaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("Libraries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("LibraryScans", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryScanId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasMaxLength(24)
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<long>("FileSize")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid?>("LibraryScanEntityId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanEntityId");
|
||||
|
||||
b.HasIndex("Path")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ContentHash", "FileSize", "Path")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("LibraryScanResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ASIN")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(21);
|
||||
|
||||
b.Property<string>("AppleBooksId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(29);
|
||||
|
||||
b.Property<string>("BarnesAndNobleId")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(33);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(32);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("Edition")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(19);
|
||||
|
||||
b.Property<string>("Format")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(18);
|
||||
|
||||
b.Property<string>("GoodreadsId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(22);
|
||||
|
||||
b.Property<string>("GoogleBooksId")
|
||||
.HasMaxLength(12)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(27);
|
||||
|
||||
b.Property<string>("LCCN")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(23);
|
||||
|
||||
b.Property<string>("LanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("LanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<string>("LanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<string>("LibraryThingId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(26);
|
||||
|
||||
b.Property<string>("OCLCNumber")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(24);
|
||||
|
||||
b.Property<string>("OpenLibraryId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(25);
|
||||
|
||||
b.Property<string>("OriginalLanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<string>("OriginalLanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<string>("OriginalLanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(15);
|
||||
|
||||
b.Property<DateOnly?>("OriginalReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<int?>("OriginalReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("OriginalTitle")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int?>("PageCount")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(17);
|
||||
|
||||
b.Property<string>("Publisher")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(16);
|
||||
|
||||
b.Property<DateOnly?>("ReReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<int?>("ReReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("ReleaseCountry")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("ReleaseVersion")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(35);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(34);
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(20);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("TempPassword")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime?>("TempPasswordCreated")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("TotpSecret")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("GenreId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("TagId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("Role");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("UserRoles")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithOne("UserRole")
|
||||
.HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Role");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("Libraries")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(260)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("Path");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("LibraryId");
|
||||
|
||||
b1.ToTable("LibraryContentLocations", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("LibraryId");
|
||||
});
|
||||
|
||||
b.Navigation("ContentLocations");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanEntityId");
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("LibraryScan");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("MaxValue")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("Value")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<int?>("VoteCount")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookRatings", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Format")
|
||||
.IsRequired()
|
||||
.HasMaxLength(6)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasMaxLength(13)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("ISBN");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookISBNs", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.Navigation("ISBNs");
|
||||
|
||||
b.Navigation("Ratings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserRoles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScans");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScanResults");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Navigation("Libraries");
|
||||
|
||||
b.Navigation("LibraryScans");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
|
||||
b.Navigation("UserRole");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations;
|
||||
|
||||
/// <inheritdoc />
|
||||
public partial class AddsLibraryScanResultTickColumn : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "LastModified",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "Ticks",
|
||||
table: "LibraryScanResults",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: 0L)
|
||||
.Annotation("Relational:ColumnOrder", 4);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Ticks",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "LastModified",
|
||||
table: "LibraryScanResults",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified))
|
||||
.Annotation("Relational:ColumnOrder", 4);
|
||||
}
|
||||
}
|
||||
+875
@@ -0,0 +1,875 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
[DbContext(typeof(LuminaDbContext))]
|
||||
[Migration("20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths")]
|
||||
partial class RemoveUniqueConstraintOnScanResultsFilePaths
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("GenreId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "GenreId");
|
||||
|
||||
b.HasIndex("GenreId");
|
||||
|
||||
b.ToTable("BookGenres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TagId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "TagId");
|
||||
|
||||
b.HasIndex("TagId");
|
||||
|
||||
b.ToTable("BookTags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("PermissionName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Permissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("RoleName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("RoleId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("RoleId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RolePermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("UserId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserPermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.HasIndex("UserId", "RoleId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Genres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("CoverImage")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<bool>("DownloadMedatadaFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsLocked")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("LibraryType")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<bool>("SaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("Libraries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("LibraryScans", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryScanId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasMaxLength(24)
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<long>("FileSize")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid?>("LibraryScanEntityId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanEntityId");
|
||||
|
||||
b.HasIndex("Path");
|
||||
|
||||
b.HasIndex("ContentHash", "FileSize", "Path");
|
||||
|
||||
b.ToTable("LibraryScanResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ASIN")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(21);
|
||||
|
||||
b.Property<string>("AppleBooksId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(29);
|
||||
|
||||
b.Property<string>("BarnesAndNobleId")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(33);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(32);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("Edition")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(19);
|
||||
|
||||
b.Property<string>("Format")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(18);
|
||||
|
||||
b.Property<string>("GoodreadsId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(22);
|
||||
|
||||
b.Property<string>("GoogleBooksId")
|
||||
.HasMaxLength(12)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(27);
|
||||
|
||||
b.Property<string>("LCCN")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(23);
|
||||
|
||||
b.Property<string>("LanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("LanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<string>("LanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<string>("LibraryThingId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(26);
|
||||
|
||||
b.Property<string>("OCLCNumber")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(24);
|
||||
|
||||
b.Property<string>("OpenLibraryId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(25);
|
||||
|
||||
b.Property<string>("OriginalLanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<string>("OriginalLanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<string>("OriginalLanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(15);
|
||||
|
||||
b.Property<DateOnly?>("OriginalReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<int?>("OriginalReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("OriginalTitle")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int?>("PageCount")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(17);
|
||||
|
||||
b.Property<string>("Publisher")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(16);
|
||||
|
||||
b.Property<DateOnly?>("ReReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<int?>("ReReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("ReleaseCountry")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("ReleaseVersion")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(35);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(34);
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(20);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("TempPassword")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime?>("TempPasswordCreated")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("TotpSecret")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("GenreId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("TagId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("Role");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("UserRoles")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithOne("UserRole")
|
||||
.HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Role");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("Libraries")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(260)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("Path");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("LibraryId");
|
||||
|
||||
b1.ToTable("LibraryContentLocations", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("LibraryId");
|
||||
});
|
||||
|
||||
b.Navigation("ContentLocations");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanEntityId");
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("LibraryScan");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("MaxValue")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("Value")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<int?>("VoteCount")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookRatings", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Format")
|
||||
.IsRequired()
|
||||
.HasMaxLength(6)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasMaxLength(13)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("ISBN");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookISBNs", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.Navigation("ISBNs");
|
||||
|
||||
b.Navigation("Ratings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserRoles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScans");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScanResults");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Navigation("Libraries");
|
||||
|
||||
b.Navigation("LibraryScans");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
|
||||
b.Navigation("UserRole");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations;
|
||||
|
||||
/// <inheritdoc />
|
||||
public partial class RemoveUniqueConstraintOnScanResultsFilePaths : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScanResults_ContentHash_FileSize_Path",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScanResults_Path",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanResults_ContentHash_FileSize_Path",
|
||||
table: "LibraryScanResults",
|
||||
columns: new[] { "ContentHash", "FileSize", "Path" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanResults_Path",
|
||||
table: "LibraryScanResults",
|
||||
column: "Path");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScanResults_ContentHash_FileSize_Path",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScanResults_Path",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanResults_ContentHash_FileSize_Path",
|
||||
table: "LibraryScanResults",
|
||||
columns: new[] { "ContentHash", "FileSize", "Path" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanResults_Path",
|
||||
table: "LibraryScanResults",
|
||||
column: "Path",
|
||||
unique: true);
|
||||
}
|
||||
}
|
||||
Generated
+876
@@ -0,0 +1,876 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
[DbContext(typeof(LuminaDbContext))]
|
||||
[Migration("20250502152428_AddsIndexOnLibraryScansTable")]
|
||||
partial class AddsIndexOnLibraryScansTable
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("GenreId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "GenreId");
|
||||
|
||||
b.HasIndex("GenreId");
|
||||
|
||||
b.ToTable("BookGenres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("TagId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("BookId", "TagId");
|
||||
|
||||
b.HasIndex("TagId");
|
||||
|
||||
b.ToTable("BookTags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("PermissionName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Permissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("RoleName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Roles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("RoleId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("RoleId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RolePermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("PermissionId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId", "PermissionId");
|
||||
|
||||
b.HasIndex("PermissionId");
|
||||
|
||||
b.HasIndex("UserId", "PermissionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserPermissions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("RoleId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("UserId");
|
||||
|
||||
b.HasIndex("RoleId");
|
||||
|
||||
b.HasIndex("UserId", "RoleId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("UserRoles", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Genres", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b =>
|
||||
{
|
||||
b.Property<string>("Name")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Name");
|
||||
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("CoverImage")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<bool>("DownloadMedatadaFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<bool>("IsEnabled")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<bool>("IsLocked")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("LibraryType")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<bool>("SaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.ToTable("Libraries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.HasIndex("LibraryId", "Status", "CreatedOnUtc")
|
||||
.IsDescending(true, false, true);
|
||||
|
||||
b.ToTable("LibraryScans", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryScanId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasMaxLength(24)
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<long>("FileSize")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid?>("LibraryScanEntityId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanEntityId");
|
||||
|
||||
b.HasIndex("Path");
|
||||
|
||||
b.HasIndex("ContentHash", "FileSize", "Path");
|
||||
|
||||
b.ToTable("LibraryScanResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<string>("ASIN")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(21);
|
||||
|
||||
b.Property<string>("AppleBooksId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(29);
|
||||
|
||||
b.Property<string>("BarnesAndNobleId")
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(28);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(33);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(32);
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(2000)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<string>("Edition")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(19);
|
||||
|
||||
b.Property<string>("Format")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(18);
|
||||
|
||||
b.Property<string>("GoodreadsId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(22);
|
||||
|
||||
b.Property<string>("GoogleBooksId")
|
||||
.HasMaxLength(12)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(27);
|
||||
|
||||
b.Property<string>("LCCN")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(23);
|
||||
|
||||
b.Property<string>("LanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<string>("LanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<string>("LanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<string>("LibraryThingId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(26);
|
||||
|
||||
b.Property<string>("OCLCNumber")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(24);
|
||||
|
||||
b.Property<string>("OpenLibraryId")
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(25);
|
||||
|
||||
b.Property<string>("OriginalLanguageCode")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<string>("OriginalLanguageName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<string>("OriginalLanguageNativeName")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(15);
|
||||
|
||||
b.Property<DateOnly?>("OriginalReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<int?>("OriginalReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("OriginalTitle")
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<int?>("PageCount")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(17);
|
||||
|
||||
b.Property<string>("Publisher")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(16);
|
||||
|
||||
b.Property<DateOnly?>("ReReleaseDate")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<int?>("ReReleaseYear")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<string>("ReleaseCountry")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("ReleaseVersion")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(35);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(34);
|
||||
|
||||
b.Property<int?>("VolumeNumber")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(20);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Books", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<string>("Password")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<string>("TempPassword")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<DateTime?>("TempPasswordCreated")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<string>("TotpSecret")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Username")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("GenreId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("BookTags", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("BookId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("TagId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("RolePermissions")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("Role");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("PermissionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("UserPermissions")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Permission");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role")
|
||||
.WithMany("UserRoles")
|
||||
.HasForeignKey("RoleId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithOne("UserRole")
|
||||
.HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Role");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("Libraries")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Path")
|
||||
.IsRequired()
|
||||
.HasMaxLength(260)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("Path");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("LibraryId");
|
||||
|
||||
b1.ToTable("LibraryContentLocations", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("LibraryId");
|
||||
});
|
||||
|
||||
b.Navigation("ContentLocations");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
.WithMany("LibraryScans")
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Library");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanEntityId");
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("LibraryScan");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("MaxValue")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<string>("Source")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<decimal>("Value")
|
||||
.HasColumnType("decimal(3,2)");
|
||||
|
||||
b1.Property<int?>("VoteCount")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookRatings", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<Guid>("BookId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Format")
|
||||
.IsRequired()
|
||||
.HasMaxLength(6)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b1.Property<string>("Value")
|
||||
.IsRequired()
|
||||
.HasMaxLength(13)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnName("ISBN");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("BookId");
|
||||
|
||||
b1.ToTable("BookISBNs", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("BookId");
|
||||
});
|
||||
|
||||
b.Navigation("ISBNs");
|
||||
|
||||
b.Navigation("Ratings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b =>
|
||||
{
|
||||
b.Navigation("RolePermissions");
|
||||
|
||||
b.Navigation("UserRoles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScans");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b =>
|
||||
{
|
||||
b.Navigation("LibraryScanResults");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b =>
|
||||
{
|
||||
b.Navigation("Libraries");
|
||||
|
||||
b.Navigation("LibraryScans");
|
||||
|
||||
b.Navigation("UserPermissions");
|
||||
|
||||
b.Navigation("UserRole");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations;
|
||||
|
||||
/// <inheritdoc />
|
||||
public partial class AddsIndexOnLibraryScansTable : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScans_LibraryId",
|
||||
table: "LibraryScans");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScans_LibraryId_Status_CreatedOnUtc",
|
||||
table: "LibraryScans",
|
||||
columns: new[] { "LibraryId", "Status", "CreatedOnUtc" },
|
||||
descending: new[] { true, false, true });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScans_LibraryId_Status_CreatedOnUtc",
|
||||
table: "LibraryScans");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScans_LibraryId",
|
||||
table: "LibraryScans",
|
||||
column: "LibraryId");
|
||||
}
|
||||
}
|
||||
+1028
File diff suppressed because it is too large.
Load diff
+210
@@ -0,0 +1,210 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsMediaLibraryScanSnapshotsAndStagingTables : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<DateTime>(
|
||||
name: "UpdatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: true,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT",
|
||||
oldNullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 11)
|
||||
.OldAnnotation("Relational:ColumnOrder", 10);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "UpdatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: true,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT",
|
||||
oldNullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 12)
|
||||
.OldAnnotation("Relational:ColumnOrder", 11);
|
||||
|
||||
migrationBuilder.AlterColumn<DateTime>(
|
||||
name: "CreatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 9)
|
||||
.OldAnnotation("Relational:ColumnOrder", 8);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CreatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 10)
|
||||
.OldAnnotation("Relational:ColumnOrder", 9);
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "SkipUnchangedDirectoriesDuringScan",
|
||||
table: "Libraries",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false)
|
||||
.Annotation("Relational:ColumnOrder", 8);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "DirectoryScanFingerprints",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Path = table.Column<string>(type: "TEXT", maxLength: 1024, nullable: false),
|
||||
LastWriteTimeUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_DirectoryScanFingerprints", x => new { x.LibraryId, x.Path });
|
||||
table.ForeignKey(
|
||||
name: "FK_DirectoryScanFingerprints_Libraries_LibraryId",
|
||||
column: x => x.LibraryId,
|
||||
principalTable: "Libraries",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LibraryScanSnapshots",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Path = table.Column<string>(type: "TEXT", maxLength: 1024, nullable: false),
|
||||
ContentHash = table.Column<ulong>(type: "INTEGER", nullable: false),
|
||||
FileSize = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
Ticks = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
CreatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||
CreatedBy = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UpdatedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
UpdatedBy = table.Column<Guid>(type: "TEXT", nullable: true),
|
||||
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LibraryScanSnapshots", x => new { x.LibraryId, x.Path });
|
||||
table.ForeignKey(
|
||||
name: "FK_LibraryScanSnapshots_Libraries_LibraryId",
|
||||
column: x => x.LibraryId,
|
||||
principalTable: "Libraries",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "LibraryScanStagingResults",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Path = table.Column<string>(type: "TEXT", maxLength: 1024, nullable: false),
|
||||
Size = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
Ticks = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
ContentHash = table.Column<ulong>(type: "INTEGER", nullable: false),
|
||||
PreviousContentHash = table.Column<ulong>(type: "INTEGER", nullable: false),
|
||||
NeedsRehash = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
IsNew = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
LibraryScanId = table.Column<Guid>(type: "TEXT", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_LibraryScanStagingResults", x => new { x.LibraryScanId, x.Path });
|
||||
table.ForeignKey(
|
||||
name: "FK_LibraryScanStagingResults_LibraryScans_LibraryScanId",
|
||||
column: x => x.LibraryScanId,
|
||||
principalTable: "LibraryScans",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_DirectoryScanFingerprints_LibraryId",
|
||||
table: "DirectoryScanFingerprints",
|
||||
column: "LibraryId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanSnapshots_LibraryId",
|
||||
table: "LibraryScanSnapshots",
|
||||
column: "LibraryId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanStagingResults_LibraryScanId_NeedsRehash",
|
||||
table: "LibraryScanStagingResults",
|
||||
columns: new[] { "LibraryScanId", "NeedsRehash" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "DirectoryScanFingerprints");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "LibraryScanSnapshots");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "LibraryScanStagingResults");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "SkipUnchangedDirectoriesDuringScan",
|
||||
table: "Libraries");
|
||||
|
||||
migrationBuilder.AlterColumn<DateTime>(
|
||||
name: "UpdatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: true,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT",
|
||||
oldNullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 10)
|
||||
.OldAnnotation("Relational:ColumnOrder", 11);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "UpdatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: true,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT",
|
||||
oldNullable: true)
|
||||
.Annotation("Relational:ColumnOrder", 11)
|
||||
.OldAnnotation("Relational:ColumnOrder", 12);
|
||||
|
||||
migrationBuilder.AlterColumn<DateTime>(
|
||||
name: "CreatedOnUtc",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(DateTime),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 8)
|
||||
.OldAnnotation("Relational:ColumnOrder", 9);
|
||||
|
||||
migrationBuilder.AlterColumn<Guid>(
|
||||
name: "CreatedBy",
|
||||
table: "Libraries",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(Guid),
|
||||
oldType: "TEXT")
|
||||
.Annotation("Relational:ColumnOrder", 9)
|
||||
.OldAnnotation("Relational:ColumnOrder", 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1019
File diff suppressed because it is too large.
Load diff
+49
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class RemovesLibraryScanResultsShadowForeignKey : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_LibraryScanResults_LibraryScans_LibraryScanEntityId",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_LibraryScanResults_LibraryScanEntityId",
|
||||
table: "LibraryScanResults");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "LibraryScanEntityId",
|
||||
table: "LibraryScanResults");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "LibraryScanEntityId",
|
||||
table: "LibraryScanResults",
|
||||
type: "TEXT",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_LibraryScanResults_LibraryScanEntityId",
|
||||
table: "LibraryScanResults",
|
||||
column: "LibraryScanEntityId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_LibraryScanResults_LibraryScans_LibraryScanEntityId",
|
||||
table: "LibraryScanResults",
|
||||
column: "LibraryScanEntityId",
|
||||
principalTable: "LibraryScans",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
}
|
||||
}
|
||||
src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.Designer.cs
Generated
+1019
File diff suppressed because it is too large.
Load diff
+48
@@ -0,0 +1,48 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class RenamesLibraryScanSettingsColumns : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "SkipUnchangedDirectoriesDuringScan",
|
||||
table: "Libraries",
|
||||
newName: "ShouldSkipUnchangedDirectoriesDuringScan");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "SaveMetadataInMediaDirectories",
|
||||
table: "Libraries",
|
||||
newName: "ShouldSaveMetadataInMediaDirectories");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "DownloadMedatadaFromWeb",
|
||||
table: "Libraries",
|
||||
newName: "DownloadMetadataFromWeb");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "ShouldSkipUnchangedDirectoriesDuringScan",
|
||||
table: "Libraries",
|
||||
newName: "SkipUnchangedDirectoriesDuringScan");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "ShouldSaveMetadataInMediaDirectories",
|
||||
table: "Libraries",
|
||||
newName: "SaveMetadataInMediaDirectories");
|
||||
|
||||
migrationBuilder.RenameColumn(
|
||||
name: "DownloadMetadataFromWeb",
|
||||
table: "Libraries",
|
||||
newName: "DownloadMedatadaFromWeb");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "9.0.0");
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.0");
|
||||
|
||||
modelBuilder.Entity("BookGenres", b =>
|
||||
{
|
||||
@@ -239,6 +239,31 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("Tags", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<DateTime>("LastWriteTimeUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.HasKey("LibraryId", "Path");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.ToTable("DirectoryScanFingerprints", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -252,13 +277,13 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<bool>("DownloadMedatadaFromWeb")
|
||||
b.Property<bool>("DownloadMetadataFromWeb")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true)
|
||||
@@ -279,10 +304,14 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<bool>("SaveMetadataInMediaDirectories")
|
||||
b.Property<bool>("ShouldSaveMetadataInMediaDirectories")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<bool>("ShouldSkipUnchangedDirectoriesDuringScan")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasMaxLength(255)
|
||||
@@ -291,11 +320,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(10);
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT");
|
||||
@@ -342,10 +371,11 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.HasIndex("LibraryId", "Status", "CreatedOnUtc")
|
||||
.IsDescending(true, false, true);
|
||||
|
||||
b.ToTable("LibraryScans", (string)null);
|
||||
});
|
||||
|
||||
@@ -372,26 +402,119 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<DateTime>("LastModified")
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid?>("LibraryScanEntityId")
|
||||
.HasColumnType("TEXT");
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanEntityId");
|
||||
b.HasIndex("Path");
|
||||
|
||||
b.HasIndex("Path")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ContentHash", "FileSize", "Path")
|
||||
.IsUnique();
|
||||
b.HasIndex("ContentHash", "FileSize", "Path");
|
||||
|
||||
b.ToTable("LibraryScanResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<long>("FileSize")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.HasKey("LibraryId", "Path");
|
||||
|
||||
b.HasIndex("LibraryId");
|
||||
|
||||
b.ToTable("LibraryScanSnapshots", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("LibraryScanId")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Path")
|
||||
.HasMaxLength(1024)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<ulong>("ContentHash")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<bool>("IsNew")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<bool>("NeedsRehash")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<ulong>("PreviousContentHash")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<long>("Ticks")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.HasKey("LibraryScanId", "Path");
|
||||
|
||||
b.HasIndex("LibraryScanId", "NeedsRehash");
|
||||
|
||||
b.ToTable("LibraryScanStagingResults", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -686,6 +809,15 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User")
|
||||
@@ -745,12 +877,8 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanEntityId");
|
||||
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan")
|
||||
.WithMany()
|
||||
.WithMany("LibraryScanResults")
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
@@ -758,6 +886,26 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.Navigation("LibraryScan");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library")
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Library");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b =>
|
||||
{
|
||||
b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("LibraryScanId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b =>
|
||||
{
|
||||
b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 =>
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Dapper;
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for directory scan fingerprints.
|
||||
/// </summary>
|
||||
internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerprintRepository
|
||||
{
|
||||
private const int UPSERT_BATCH_SIZE = 500; // keeps the number of bound parameters of a single UPSERT statement well under the SQLite parameter limit
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DirectoryScanFingerprintRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext, used to derive the database connection string.</param>
|
||||
public DirectoryScanFingerprintRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the directory scan fingerprints of a media library, mapped by the directory path.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the directory scan fingerprints.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of directory scan fingerprints, or an error.</returns>
|
||||
public async Task<ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string GET_FINGERPRINTS_SQL = """
|
||||
SELECT Id, LibraryId, Path, LastWriteTimeUtc
|
||||
FROM DirectoryScanFingerprints
|
||||
WHERE LibraryId = @libraryId;
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(GET_FINGERPRINTS_SQL, new { libraryId }, cancellationToken: cancellationToken);
|
||||
|
||||
IEnumerable<DirectoryScanFingerprintEntity> fingerprints = await connection.QueryAsync<DirectoryScanFingerprintEntity>(command).ConfigureAwait(false);
|
||||
return fingerprints.ToDictionary(fingerprint => fingerprint.Path, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts or updates the provided directory scan fingerprints in the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="entities">The directory scan fingerprints 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>> UpsertRangeAsync(IReadOnlyCollection<DirectoryScanFingerprintEntity> entities, CancellationToken cancellationToken)
|
||||
{
|
||||
// nothing to upsert for an empty collection
|
||||
if (entities.Count == 0)
|
||||
return Result.Updated;
|
||||
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
List<DirectoryScanFingerprintEntity> remainingEntities = [.. entities];
|
||||
// upsert the entities in batches, to keep the number of bound parameters of a single UPSERT statement under the SQLite parameter limit
|
||||
while (remainingEntities.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
List<DirectoryScanFingerprintEntity> batch = remainingEntities.GetRange(0, Math.Min(UPSERT_BATCH_SIZE, remainingEntities.Count));
|
||||
await UpsertBatchAsync(connection, transaction, batch, cancellationToken).ConfigureAwait(false);
|
||||
remainingEntities.RemoveRange(0, batch.Count);
|
||||
}
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking.
|
||||
/// </summary>
|
||||
/// <returns>The opened database connection.</returns>
|
||||
private async Task<SqliteConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString);
|
||||
await connection.OpenAsync(cancellationToken);
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Upserts a batch of directory scan fingerprints using a single multi-row UPSERT statement.
|
||||
/// </summary>
|
||||
/// <param name="connection">The connection on which to execute the upsert.</param>
|
||||
/// <param name="transaction">The transaction in which the upsert is executed.</param>
|
||||
/// <param name="batch">The batch of directory scan fingerprints to upsert.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task UpsertBatchAsync(SqliteConnection connection, DbTransaction transaction, IReadOnlyList<DirectoryScanFingerprintEntity> batch, CancellationToken cancellationToken)
|
||||
{
|
||||
StringBuilder upsertSql = new("INSERT INTO DirectoryScanFingerprints (Id, LibraryId, Path, LastWriteTimeUtc) VALUES ");
|
||||
DynamicParameters parameters = new();
|
||||
for (int i = 0; i < batch.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
upsertSql.Append(", ");
|
||||
upsertSql.Append($"(@Id{i}, @LibraryId{i}, @Path{i}, @LastWriteTimeUtc{i})");
|
||||
DirectoryScanFingerprintEntity entity = batch[i];
|
||||
parameters.Add($"Id{i}", entity.Id);
|
||||
parameters.Add($"LibraryId{i}", entity.LibraryId);
|
||||
parameters.Add($"Path{i}", entity.Path);
|
||||
parameters.Add($"LastWriteTimeUtc{i}", entity.LastWriteTimeUtc);
|
||||
}
|
||||
upsertSql.Append(" ON CONFLICT (LibraryId, Path) DO UPDATE SET LastWriteTimeUtc = excluded.LastWriteTimeUtc;");
|
||||
|
||||
CommandDefinition command = new(upsertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,6 @@ using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -42,27 +36,4 @@ internal sealed class LibraryScanResultRepository : ILibraryScanResultRepository
|
||||
_luminaDbContext.LibraryScanResults.Add(libraryScan);
|
||||
return Task.FromResult(ErrorOrFactory.From(Result.Created));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all media library scan results that belong to the last scan of a library identified by <paramref name="libraryId"/>, from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the results of the last scans.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a path mapped dictionary of <see cref="LibraryScanResultEntity"/>, or an error.</returns>
|
||||
public async Task<ErrorOr<Dictionary<string, LibraryScanResultEntity>>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _luminaDbContext.LibraryScanResults
|
||||
.Where(libraryScanResult =>
|
||||
libraryScanResult.LibraryScan.LibraryId == libraryId && // navigation property
|
||||
libraryScanResult.LibraryScanId == _luminaDbContext.LibraryScans // subquery for latest scan Id
|
||||
.Where(libraryScan => libraryScan.LibraryId == libraryId)
|
||||
.OrderByDescending(libraryScan => libraryScan.CreatedOnUtc)
|
||||
.Select(libraryScan => libraryScan.Id)
|
||||
.FirstOrDefault())
|
||||
.ToDictionaryAsync( // since these are used in large quantity comparisons, dictionary allows for O(1) lookups, instead of lists, with O(n * m)
|
||||
libraryScanResult => libraryScanResult.Path,
|
||||
libraryScanResult => libraryScanResult,
|
||||
StringComparer.Ordinal, // UNIX systems allow for case sensitive file paths
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Dapper;
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for media library scan snapshots.
|
||||
/// </summary>
|
||||
internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanSnapshotRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext, used to derive the database connection string.</param>
|
||||
public LibraryScanSnapshotRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the paths of the media library scan snapshot items that are no longer present in the current scan, meaning they were deleted from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to get the deleted media library scan snapshot item paths.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths.</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 deleted media library scan snapshot item paths, or an error.</returns>
|
||||
public async Task<ErrorOr<IReadOnlyList<string>>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string GET_DELETED_PATHS_SQL = """
|
||||
SELECT snapshot.Path
|
||||
FROM LibraryScanSnapshots AS snapshot
|
||||
WHERE snapshot.LibraryId = @libraryId
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM LibraryScanStagingResults AS staging
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND staging.Path = snapshot.Path
|
||||
);
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(GET_DELETED_PATHS_SQL, new { libraryId, scanId }, cancellationToken: cancellationToken);
|
||||
|
||||
IEnumerable<string> deletedPaths = await connection.QueryAsync<string>(command).ConfigureAwait(false);
|
||||
return deletedPaths.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
|
||||
/// The operation updates the changed media library scan snapshot items, deletes the ones that are no longer present on disk, adds audit entries for all changed, new and deleted items,
|
||||
/// and clears the staging results of the current scan.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the library for which to apply the scan results.</param>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose results are applied.</param>
|
||||
/// <param name="userId">The unique identifier of the user that initiated the media library scan, used for audit purposes.</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>> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
DateTime nowUtc = DateTime.UtcNow;
|
||||
object parameters = new { libraryId, scanId, userId, nowUtc };
|
||||
|
||||
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as lowercase hex (hex(randomblob(16))), which the storage layer parses as a Guid;
|
||||
// generating the Ids in code would defeat the purpose of these single statement bulk inserts
|
||||
|
||||
// add an audit entry for every media library scan snapshot item that is no longer present in the current scan, meaning it was deleted from the storage medium
|
||||
const string AUDIT_DELETED_SQL = """
|
||||
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, Ticks)
|
||||
SELECT hex(randomblob(16)), @scanId, 'Deleted', snapshot.Path, snapshot.ContentHash, snapshot.FileSize, snapshot.Ticks
|
||||
FROM LibraryScanSnapshots AS snapshot
|
||||
WHERE snapshot.LibraryId = @libraryId
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM LibraryScanStagingResults AS staging
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND staging.Path = snapshot.Path
|
||||
);
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(AUDIT_DELETED_SQL, parameters, transaction, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
|
||||
// add an audit entry for every new or changed media library scan staging result
|
||||
const string AUDIT_CHANGED_SQL = """
|
||||
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, Ticks)
|
||||
SELECT hex(randomblob(16)), @scanId, CASE WHEN staging.IsNew = 1 THEN 'New' ELSE 'Modified' END, staging.Path, staging.ContentHash, staging.Size, staging.Ticks
|
||||
FROM LibraryScanStagingResults AS staging
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND staging.NeedsRehash = 1;
|
||||
""";
|
||||
|
||||
command = new(AUDIT_CHANGED_SQL, parameters, transaction);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
|
||||
// delete the media library scan snapshot items that are no longer present in the current scan, meaning they were deleted from the storage medium
|
||||
const string DELETE_MISSING_SQL = """
|
||||
DELETE FROM LibraryScanSnapshots
|
||||
WHERE LibraryId = @libraryId
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM LibraryScanStagingResults AS staging
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND staging.Path = LibraryScanSnapshots.Path
|
||||
);
|
||||
""";
|
||||
|
||||
command = new(DELETE_MISSING_SQL, parameters, transaction);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
|
||||
// upsert the new and changed media library scan staging results into the media library scan snapshot
|
||||
const string UPSERT_SQL = """
|
||||
INSERT INTO LibraryScanSnapshots (Id, LibraryId, Path, ContentHash, FileSize, Ticks, CreatedOnUtc, CreatedBy, UpdatedOnUtc, UpdatedBy)
|
||||
SELECT hex(randomblob(16)), @libraryId, staging.Path, staging.ContentHash, staging.Size, staging.Ticks, @nowUtc, @userId, NULL, NULL
|
||||
FROM LibraryScanStagingResults AS staging
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND staging.NeedsRehash = 1
|
||||
ON CONFLICT (LibraryId, Path) DO UPDATE SET
|
||||
ContentHash = excluded.ContentHash,
|
||||
FileSize = excluded.FileSize,
|
||||
Ticks = excluded.Ticks,
|
||||
UpdatedOnUtc = @nowUtc,
|
||||
UpdatedBy = @userId;
|
||||
""";
|
||||
|
||||
command = new(UPSERT_SQL, parameters, transaction);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
|
||||
// clear the staging results of the current scan, as they have been fully applied to the media library scan snapshot
|
||||
const string CLEAR_STAGING_SQL = "DELETE FROM LibraryScanStagingResults WHERE LibraryScanId = @scanId;";
|
||||
|
||||
command = new(CLEAR_STAGING_SQL, parameters, transaction);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking.
|
||||
/// </summary>
|
||||
/// <returns>The opened database connection.</returns>
|
||||
private async Task<SqliteConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString);
|
||||
await connection.OpenAsync(cancellationToken);
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Dapper;
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for media library scan staging results.
|
||||
/// </summary>
|
||||
internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingResultsRepository
|
||||
{
|
||||
private const int INSERT_BATCH_SIZE = 500; // keeps the number of bound parameters of a single INSERT statement well under the SQLite parameter limit
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryScanStagingResultsRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext, used to derive the database connection string.</param>
|
||||
public LibraryScanStagingResultsRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a range of media library scan staging results to the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="entities">The media library scan staging results to add.</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<Created>> InsertRangeAsync(IReadOnlyCollection<LibraryScanStagingResultsEntity> entities, CancellationToken cancellationToken)
|
||||
{
|
||||
// nothing to insert for an empty collection
|
||||
if (entities.Count == 0)
|
||||
return Result.Created;
|
||||
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
List<LibraryScanStagingResultsEntity> remainingEntities = [.. entities];
|
||||
// insert the entities in batches, to keep the number of bound parameters of a single INSERT statement under the SQLite parameter limit
|
||||
while (remainingEntities.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
List<LibraryScanStagingResultsEntity> batch = remainingEntities.GetRange(0, Math.Min(INSERT_BATCH_SIZE, remainingEntities.Count));
|
||||
await InsertBatchAsync(connection, transaction, batch, cancellationToken).ConfigureAwait(false);
|
||||
remainingEntities.RemoveRange(0, batch.Count);
|
||||
}
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the media library scan staging results of the current scan by comparing them against the media library scan snapshot of a previous scan, determining which file system items
|
||||
/// are new, which ones changed and need their content hashed, and which ones are unchanged.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are marked.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot is compared against.</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>> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
// compare the discovered file system items against the media library scan snapshot of the previous scan, entirely in the database, so that the snapshot never needs to be loaded into memory:
|
||||
// an item with no snapshot entry is new, an item with the same size and last write time is unchanged and keeps the stored hash, and everything else changed and needs its content hashed again
|
||||
const string MARK_CHANGES_SQL = """
|
||||
UPDATE LibraryScanStagingResults AS staging
|
||||
SET ContentHash = COALESCE(snapshot.ContentHash, 0),
|
||||
PreviousContentHash = COALESCE(snapshot.ContentHash, 0),
|
||||
NeedsRehash = CASE
|
||||
WHEN snapshot.ContentHash IS NULL THEN 1
|
||||
WHEN staging.Size = snapshot.FileSize AND staging.Ticks = snapshot.Ticks THEN 0
|
||||
ELSE 1
|
||||
END,
|
||||
IsNew = CASE WHEN snapshot.ContentHash IS NULL THEN 1 ELSE 0 END
|
||||
FROM LibraryScanSnapshots AS snapshot
|
||||
WHERE staging.LibraryScanId = @scanId
|
||||
AND snapshot.LibraryId = @libraryId
|
||||
AND snapshot.Path = staging.Path;
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(MARK_CHANGES_SQL, new { scanId, libraryId }, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of media library scan staging results of the current scan that need their content hashed.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are counted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the number of staging results that need hashing, or an error.</returns>
|
||||
public async Task<ErrorOr<int>> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string GET_FILES_TO_HASH_COUNT_SQL = """
|
||||
SELECT COUNT(*)
|
||||
FROM LibraryScanStagingResults
|
||||
WHERE LibraryScanId = @scanId
|
||||
AND NeedsRehash = 1;
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(GET_FILES_TO_HASH_COUNT_SQL, new { scanId }, cancellationToken: cancellationToken);
|
||||
|
||||
return await connection.ExecuteScalarAsync<int>(command).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a page of the media library scan staging results that need their content hashed, ordered by path, using keyset pagination.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are retrieved.</param>
|
||||
/// <param name="lastPath">The path of the last retrieved file system item, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
|
||||
/// <param name="pageSize">The maximum number of staging results to retrieve.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of staging results that need hashing, or an error.</returns>
|
||||
public async Task<ErrorOr<IReadOnlyList<HashedFileSystemFile>>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string GET_FILES_TO_HASH_SQL = """
|
||||
SELECT Path, Size, Ticks, PreviousContentHash AS OldHash
|
||||
FROM LibraryScanStagingResults
|
||||
WHERE LibraryScanId = @scanId
|
||||
AND NeedsRehash = 1
|
||||
AND (@lastPath IS NULL OR Path > @lastPath)
|
||||
ORDER BY Path
|
||||
LIMIT @pageSize;
|
||||
""";
|
||||
|
||||
CommandDefinition command = new(GET_FILES_TO_HASH_SQL, new { scanId, lastPath, pageSize }, cancellationToken: cancellationToken);
|
||||
|
||||
IEnumerable<HashedFileSystemFile> page = await connection.QueryAsync<HashedFileSystemFile>(command).ConfigureAwait(false);
|
||||
return page.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the content hashes of the provided media library scan staging results.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are updated.</param>
|
||||
/// <param name="hashedFiles">The file system items whose content hashes are updated.</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>> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection<HashedFileSystemFile> hashedFiles, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
const string UPDATE_HASH_SQL = """
|
||||
UPDATE LibraryScanStagingResults
|
||||
SET ContentHash = @contentHash
|
||||
WHERE LibraryScanId = @scanId
|
||||
AND Path = @path;
|
||||
""";
|
||||
foreach (HashedFileSystemFile hashedFile in hashedFiles)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
CommandDefinition command = new(UPDATE_HASH_SQL, new { scanId, contentHash = hashedFile.CurrentHash, path = hashedFile.Path }, transaction, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
}
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Updated;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all the media library scan staging results of the provided media library scan from the storage medium.
|
||||
/// </summary>
|
||||
/// <param name="scanId">The unique identifier of the media library scan whose staging results are cleared.</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<Success>> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
const string CLEAR_SQL = "DELETE FROM LibraryScanStagingResults WHERE LibraryScanId = @scanId;";
|
||||
|
||||
CommandDefinition command = new(CLEAR_SQL, new { scanId }, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
return Result.Success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking.
|
||||
/// </summary>
|
||||
/// <returns>The opened database connection.</returns>
|
||||
private async Task<SqliteConnection> OpenConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString);
|
||||
await connection.OpenAsync(cancellationToken);
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a batch of media library scan staging results using a single multi-row INSERT statement.
|
||||
/// </summary>
|
||||
/// <param name="connection">The connection on which to execute the insert.</param>
|
||||
/// <param name="transaction">The transaction in which the insert is executed.</param>
|
||||
/// <param name="batch">The batch of media library scan staging results to insert.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private static async Task InsertBatchAsync(SqliteConnection connection, DbTransaction transaction, IReadOnlyList<LibraryScanStagingResultsEntity> batch, CancellationToken cancellationToken)
|
||||
{
|
||||
StringBuilder insertSql = new("INSERT INTO LibraryScanStagingResults (Id, LibraryScanId, Path, Size, Ticks, ContentHash, PreviousContentHash, NeedsRehash, IsNew) VALUES ");
|
||||
DynamicParameters parameters = new();
|
||||
for (int i = 0; i < batch.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
insertSql.Append(", ");
|
||||
insertSql.Append($"(@Id{i}, @LibraryScanId{i}, @Path{i}, @Size{i}, @Ticks{i}, @ContentHash{i}, @PreviousContentHash{i}, @NeedsRehash{i}, @IsNew{i})");
|
||||
LibraryScanStagingResultsEntity entity = batch[i];
|
||||
parameters.Add($"Id{i}", entity.Id);
|
||||
parameters.Add($"LibraryScanId{i}", entity.LibraryScanId);
|
||||
parameters.Add($"Path{i}", entity.Path);
|
||||
parameters.Add($"Size{i}", entity.Size);
|
||||
parameters.Add($"Ticks{i}", entity.Ticks);
|
||||
parameters.Add($"ContentHash{i}", entity.ContentHash);
|
||||
parameters.Add($"PreviousContentHash{i}", entity.PreviousContentHash);
|
||||
parameters.Add($"NeedsRehash{i}", entity.NeedsRehash);
|
||||
parameters.Add($"IsNew{i}", entity.IsNew);
|
||||
}
|
||||
|
||||
CommandDefinition command = new(insertSql.ToString(), parameters, transaction, cancellationToken: cancellationToken);
|
||||
|
||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<LibraryEntity> Libraries { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanEntity> LibraryScans { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanResultEntity> LibraryScanResults { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanSnapshotEntity> LibraryScanSnapshots { get; set; } = null!;
|
||||
public virtual DbSet<LibraryScanStagingResultsEntity> LibraryScanStagingResults { get; set; } = null!;
|
||||
public virtual DbSet<DirectoryScanFingerprintEntity> DirectoryScanFingerprints { get; set; } = null!;
|
||||
public virtual DbSet<RoleEntity> Roles { get; set; } = null!;
|
||||
public virtual DbSet<UserRoleEntity> UserRoles { get; set; } = null!;
|
||||
public virtual DbSet<PermissionEntity> Permissions { get; set; } = null!;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.1.66" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0">
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the statuses of the files processed during a media library scan.
|
||||
/// </summary>
|
||||
public enum LibraryScanFileStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// The file contents have been changed.
|
||||
/// </summary>
|
||||
Modified,
|
||||
|
||||
/// <summary>
|
||||
/// The file has been added.
|
||||
/// </summary>
|
||||
New,
|
||||
|
||||
/// <summary>
|
||||
/// The file has been deleted.
|
||||
/// </summary>
|
||||
Deleted
|
||||
}
|
||||
+37
-22
@@ -63,12 +63,18 @@ public class Library : AggregateRoot<LibraryId>
|
||||
/// <summary>
|
||||
/// Gets whether this media library should update the metadata of its elements from the web, or not.
|
||||
/// </summary>
|
||||
public bool DownloadMedatadaFromWeb { get; private set; } = true;
|
||||
public bool DownloadMetadataFromWeb { get; private set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// </summary>
|
||||
public bool SaveMetadataInMediaDirectories { get; private set; }
|
||||
public bool ShouldSaveMetadataInMediaDirectories { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether this media library should skip the directories whose contents have not changed since the last scan, during the scan. This is an opt-in setting, because it relies on directory metadata,
|
||||
/// which does not change when the contents of an existing file are edited, and such edits could be missed while this setting is enabled.
|
||||
/// </summary>
|
||||
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of objects representing the file system paths that make up the media library.
|
||||
@@ -91,8 +97,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
/// <param name="coverImage">The path of the image file used as the cover for the library.</param>
|
||||
/// <param name="isEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
|
||||
private Library(
|
||||
LibraryId id,
|
||||
@@ -103,8 +110,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
string? coverImage,
|
||||
bool isEnabled,
|
||||
bool isLocked,
|
||||
bool downloadMedatadaFromWeb,
|
||||
bool saveMetadataInMediaDirectories,
|
||||
bool downloadMetadataFromWeb,
|
||||
bool shouldSaveMetadataInMediaDirectories,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan,
|
||||
List<ScanId> scanIds) : base(id)
|
||||
{
|
||||
UserId = userId;
|
||||
@@ -114,8 +122,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
CoverImage = coverImage;
|
||||
IsEnabled = isEnabled;
|
||||
IsLocked = isLocked;
|
||||
DownloadMedatadaFromWeb = downloadMedatadaFromWeb;
|
||||
SaveMetadataInMediaDirectories = saveMetadataInMediaDirectories;
|
||||
DownloadMetadataFromWeb = downloadMetadataFromWeb;
|
||||
ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories;
|
||||
ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan;
|
||||
_scanIds = scanIds;
|
||||
}
|
||||
|
||||
@@ -129,11 +138,12 @@ public class Library : AggregateRoot<LibraryId>
|
||||
/// <param name="coverImageSourcePath">The path of the image file chosen by the user to be used as the cover for the library.</param>
|
||||
/// <param name="isEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="Library"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<Library> Create(
|
||||
UserId userId,
|
||||
@@ -143,8 +153,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
string? coverImageSourcePath,
|
||||
bool isEnabled,
|
||||
bool isLocked,
|
||||
bool downloadMedatadaFromWeb,
|
||||
bool saveMetadataInMediaDirectories,
|
||||
bool downloadMetadataFromWeb,
|
||||
bool shouldSaveMetadataInMediaDirectories,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan,
|
||||
List<ScanId> scanIds)
|
||||
{
|
||||
List<FileSystemPathId> tempContentLocations = [];
|
||||
@@ -165,8 +176,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
coverImageSourcePath,
|
||||
isEnabled,
|
||||
isLocked,
|
||||
downloadMedatadaFromWeb,
|
||||
saveMetadataInMediaDirectories,
|
||||
downloadMetadataFromWeb,
|
||||
shouldSaveMetadataInMediaDirectories,
|
||||
shouldSkipUnchangedDirectoriesDuringScan,
|
||||
scanIds
|
||||
);
|
||||
}
|
||||
@@ -182,11 +194,12 @@ public class Library : AggregateRoot<LibraryId>
|
||||
/// <param name="coverImageSourcePath">The path of the image file chosen by the user to be used as the cover for the library.</param>
|
||||
/// <param name="isEnabled">Whether this media library is enabled or not. A disabled media library is never shown or changed.</param>
|
||||
/// <param name="isLocked">Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.</param>
|
||||
/// <param name="downloadMedatadaFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="saveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether this media library should update the metadata of its elements from the web, or not.</param>
|
||||
/// <param name="shouldSaveMetadataInMediaDirectories">Whether this media library should copy the downloaded metadata into the media library content locations, or not.</param>
|
||||
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.</param>
|
||||
/// <param name="scanIds">The list of objects representing the unique identifier of scans of the media library.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="Library"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
|
||||
/// </returns>
|
||||
public static ErrorOr<Library> Create(
|
||||
LibraryId id,
|
||||
@@ -197,8 +210,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
string? coverImageSourcePath,
|
||||
bool isEnabled,
|
||||
bool isLocked,
|
||||
bool downloadMedatadaFromWeb,
|
||||
bool saveMetadataInMediaDirectories,
|
||||
bool downloadMetadataFromWeb,
|
||||
bool shouldSaveMetadataInMediaDirectories,
|
||||
bool shouldSkipUnchangedDirectoriesDuringScan,
|
||||
List<ScanId> scanIds)
|
||||
{
|
||||
List<FileSystemPathId> tempContentLocations = [];
|
||||
@@ -219,8 +233,9 @@ public class Library : AggregateRoot<LibraryId>
|
||||
coverImageSourcePath,
|
||||
isEnabled,
|
||||
isLocked,
|
||||
downloadMedatadaFromWeb,
|
||||
saveMetadataInMediaDirectories,
|
||||
downloadMetadataFromWeb,
|
||||
shouldSaveMetadataInMediaDirectories,
|
||||
shouldSkipUnchangedDirectoriesDuringScan,
|
||||
scanIds
|
||||
);
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
|
||||
/// <summary>
|
||||
/// Domain event raised when a media library item was present in the media library scan snapshot of a previous scan, but it is no longer present on disk.
|
||||
/// </summary>
|
||||
/// <param name="Id">The unique identifier of the domain event.</param>
|
||||
/// <param name="LibraryId">The unique identifier of the library to which the deleted media library item belonged.</param>
|
||||
/// <param name="MediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <param name="Path">The path of the media library item that was deleted.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Path: {Path}")]
|
||||
public record LibraryMediaItemDeletedDomainEvent(
|
||||
Guid Id,
|
||||
LibraryId LibraryId,
|
||||
MediaLibraryScanCompositeId MediaLibraryScanCompositeId,
|
||||
string Path,
|
||||
DateTime OccurredOnUtc
|
||||
) : IDomainEvent;
|
||||
+3
-1
@@ -15,10 +15,12 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib
|
||||
/// <param name="LibraryId">The unique identifier of the library whose scan has failed.</param>
|
||||
/// <param name="MediaLibraryScanCompositeId">Model for tracking media library scans.</param>
|
||||
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
|
||||
/// <param name="ErrorMessage">The optional descriptive message of the failure, used for diagnostic purposes.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record LibraryScanFailedDomainEvent(
|
||||
Guid Id,
|
||||
LibraryId LibraryId,
|
||||
MediaLibraryScanCompositeId MediaLibraryScanCompositeId,
|
||||
DateTime OccurredOnUtc
|
||||
DateTime OccurredOnUtc,
|
||||
string? ErrorMessage = null
|
||||
) : IDomainEvent;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
|
||||
/// </summary>
|
||||
public interface IScanJobRegistry
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the media library scan jobs registered for the provided <paramref name="hookName"/>.
|
||||
/// </summary>
|
||||
/// <param name="hookName">The name of the hook point at which the media library scan jobs were injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The collection of media library scan jobs registered at the provided hook point.</returns>
|
||||
IEnumerable<IMediaLibraryScanJob> GetJobsForHook(string hookName, LibraryId libraryId);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected.
|
||||
/// </summary>
|
||||
public static class ScanJobHooks
|
||||
{
|
||||
/// <summary>
|
||||
/// The hook that runs after the file system discovery job, and before the scan diff job.
|
||||
/// </summary>
|
||||
public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after the scan diff job, and before the scan hash job.
|
||||
/// </summary>
|
||||
public const string AFTER_SCAN_DIFF = "AfterScanDiff";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after the scan hash job, and before any metadata enrichment jobs.
|
||||
/// </summary>
|
||||
public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs after any metadata enrichment jobs, and before the scan results save job.
|
||||
/// </summary>
|
||||
public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment";
|
||||
|
||||
/// <summary>
|
||||
/// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave";
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
public interface IHashComparerJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for computing the differences between the files on disk and the media library scan snapshot of the previous scan.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanDiffJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for computing the content hashes of the files that changed since the previous scan.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanHashJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for persisting the results of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
public interface IMediaLibraryScanResultsSaveJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans.
|
||||
/// </summary>
|
||||
public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
public interface IRepositoryMetadataSaveJob : IMediaLibraryScanJob
|
||||
{
|
||||
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for filtering only files that have known book formats extensions.
|
||||
/// </summary>
|
||||
public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
|
||||
namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the media library scan job for discovering books file system items.
|
||||
/// </summary>
|
||||
public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob
|
||||
{
|
||||
}
|
||||
+55
-30
@@ -1,6 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using System.Collections.Generic;
|
||||
@@ -14,57 +15,81 @@ namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext
|
||||
internal class BookLibraryTypeScanner : IBookLibraryTypeScanner
|
||||
{
|
||||
private readonly IMediaLibraryScanJobFactory _mediaScanJobFactory;
|
||||
private readonly IScanJobRegistry _scanJobRegistry;
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// The media library type that this media library scanner supports.
|
||||
/// </summary>
|
||||
public LibraryType SupportedType { get; } = LibraryType.Book;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookLibraryTypeScanner"/> class.
|
||||
/// </summary>
|
||||
/// <param name="mediaScanJobFactory">Injected factory for creating media library scan jobs.</param>
|
||||
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory)
|
||||
/// <param name="scanJobRegistry">Injected registry of the media library scan jobs injected by plugins at the defined hook points.</param>
|
||||
public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry)
|
||||
{
|
||||
_mediaScanJobFactory = mediaScanJobFactory;
|
||||
_scanJobRegistry = scanJobRegistry;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb)
|
||||
/// <summary>
|
||||
/// Creates the media library scan jobs for the provided media library.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The unique identifier of the media library for which to create the media library scan jobs.</param>
|
||||
/// <param name="downloadMetadataFromWeb">Whether the library permits downloading data from the web, or not.</param>
|
||||
/// <returns>A collection of media library scan jobs.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb)
|
||||
{
|
||||
// declare the list of jobs that this scanner requires
|
||||
IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IFileSystemDiscoveryJob>(libraryId);
|
||||
IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataDiscoveryJob>(libraryId);
|
||||
IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob<IBooksFileExtensionsFilterJob>(libraryId);
|
||||
IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob<IHashComparerJob>(libraryId);
|
||||
IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob<IBooksFileSystemDiscoveryJob>(libraryId);
|
||||
IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanDiffJob>(libraryId);
|
||||
IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanHashJob>(libraryId);
|
||||
IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob<IGoodReadsMetadataScrapJob>(libraryId);
|
||||
IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob<IRepositoryMetadataSaveJob>(libraryId);
|
||||
IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob<IMediaLibraryScanResultsSaveJob>(libraryId);
|
||||
|
||||
// establish the hierarchical relationships between jobs
|
||||
fileSystemDiscoveryJob.AddChild(booksFileExtensionsFilterJob);
|
||||
repositoryMetadataDiscoveryJob.AddChild(hashComparerJob);
|
||||
|
||||
booksFileExtensionsFilterJob.AddChild(hashComparerJob);
|
||||
booksFileExtensionsFilterJob.AddParent(fileSystemDiscoveryJob);
|
||||
// establish the hierarchical relationships between jobs, splicing the plugin jobs at the defined hook points
|
||||
IMediaLibraryScanJob previousJob = fileSystemDiscoveryJob;
|
||||
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_FILE_SYSTEM_DISCOVERY, libraryId);
|
||||
previousJob.AddChild(mediaLibraryScanDiffJob);
|
||||
mediaLibraryScanDiffJob.AddParent(previousJob);
|
||||
|
||||
hashComparerJob.AddParent(booksFileExtensionsFilterJob);
|
||||
hashComparerJob.AddParent(repositoryMetadataDiscoveryJob);
|
||||
previousJob = SpliceJobsAtHook(mediaLibraryScanDiffJob, ScanJobHooks.AFTER_SCAN_DIFF, libraryId);
|
||||
previousJob.AddChild(mediaLibraryScanHashJob);
|
||||
mediaLibraryScanHashJob.AddParent(previousJob);
|
||||
|
||||
if (downloadMedatadaFromWeb)
|
||||
previousJob = SpliceJobsAtHook(mediaLibraryScanHashJob, ScanJobHooks.BEFORE_METADATA_ENRICHMENT, libraryId);
|
||||
if (downloadMetadataFromWeb)
|
||||
{
|
||||
hashComparerJob.AddChild(goodReadsMetadataScrapJob);
|
||||
goodReadsMetadataScrapJob.AddChild(repositoryMetadataSaveJob);
|
||||
|
||||
goodReadsMetadataScrapJob.AddParent(hashComparerJob);
|
||||
repositoryMetadataSaveJob.AddParent(goodReadsMetadataScrapJob);
|
||||
}
|
||||
else // TODO: perform some action with local files?
|
||||
{
|
||||
hashComparerJob.AddChild(repositoryMetadataSaveJob);
|
||||
|
||||
repositoryMetadataSaveJob.AddParent(hashComparerJob);
|
||||
previousJob.AddChild(goodReadsMetadataScrapJob);
|
||||
goodReadsMetadataScrapJob.AddParent(previousJob);
|
||||
previousJob = goodReadsMetadataScrapJob;
|
||||
}
|
||||
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.AFTER_METADATA_ENRICHMENT, libraryId);
|
||||
previousJob = SpliceJobsAtHook(previousJob, ScanJobHooks.BEFORE_SCAN_RESULTS_SAVE, libraryId);
|
||||
previousJob.AddChild(mediaLibraryScanResultsSaveJob);
|
||||
mediaLibraryScanResultsSaveJob.AddParent(previousJob);
|
||||
|
||||
// return the top level jobs that will be triggered when the scan will be started
|
||||
yield return fileSystemDiscoveryJob;
|
||||
yield return repositoryMetadataDiscoveryJob;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splices the plugin jobs registered at the provided <paramref name="hookName"/> after the <paramref name="previousJob"/>, and returns the last job of the extended chain.
|
||||
/// </summary>
|
||||
/// <param name="previousJob">The job after which the plugin jobs are spliced.</param>
|
||||
/// <param name="hookName">The name of the hook point at which the plugin jobs are injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The last job of the extended chain, which can be used as the parent for the next job.</returns>
|
||||
private IMediaLibraryScanJob SpliceJobsAtHook(IMediaLibraryScanJob previousJob, string hookName, LibraryId libraryId)
|
||||
{
|
||||
IMediaLibraryScanJob currentJob = previousJob;
|
||||
foreach (IMediaLibraryScanJob pluginJob in _scanJobRegistry.GetJobsForHook(hookName, libraryId))
|
||||
{
|
||||
currentJob.AddChild(pluginJob);
|
||||
pluginJob.AddParent(currentJob);
|
||||
currentJob = pluginJob;
|
||||
}
|
||||
return currentJob;
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.5" />
|
||||
<PackageReference Include="System.IO.Abstractions" Version="21.1.3" />
|
||||
<PackageReference Include="System.IO.FileSystem.AccessControl" Version="5.0.0" />
|
||||
<PackageReference Include="Mediator.Abstractions" Version="3.0.0-preview.27" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Application.Core.MediaLibrary.Management.Progress;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
@@ -17,6 +18,7 @@ using Lumina.Infrastructure.Core.Authorization;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
|
||||
@@ -24,6 +26,8 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Infrastructure.Core.Time;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
@@ -66,13 +70,13 @@ public static class InfrastructureLayerServices
|
||||
services.AddSingleton<IMediaLibrariesScanQueue, MediaLibrariesScanQueue>();
|
||||
services.AddSingleton<IMediaLibrariesScanCancellationTracker, MediaLibrariesScanCancellationTracker>();
|
||||
services.AddHostedService<MediaLibraryScanJobProcessorJob>();
|
||||
services.AddSingleton<IScanJobRegistry>(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary<string, IReadOnlyList<Type>>()));
|
||||
|
||||
services.AddTransient<IFileSystemDiscoveryJob, FileSystemDiscoveryJob>();
|
||||
services.AddTransient<IRepositoryMetadataDiscoveryJob, RepositoryMetadataDiscoveryJob>();
|
||||
services.AddTransient<IBooksFileExtensionsFilterJob, BooksFileExtensionsFilterJob>();
|
||||
services.AddTransient<IHashComparerJob, HashComparerJob>();
|
||||
services.AddTransient<IBooksFileSystemDiscoveryJob, BooksFileSystemDiscoveryJob>();
|
||||
services.AddTransient<IMediaLibraryScanDiffJob, MediaLibraryScanDiffJob>();
|
||||
services.AddTransient<IMediaLibraryScanHashJob, MediaLibraryScanHashJob>();
|
||||
services.AddTransient<IGoodReadsMetadataScrapJob, GoodReadsMetadataScrapJob>();
|
||||
services.AddTransient<IRepositoryMetadataSaveJob, RepositoryMetadataSaveJob>();
|
||||
services.AddTransient<IMediaLibraryScanResultsSaveJob, MediaLibraryScanResultsSaveJob>();
|
||||
|
||||
|
||||
services.AddSingleton<IMediaLibraryScanProgressNotifier, DebouncedMediaLibraryScanProgressNotifier>();
|
||||
|
||||
-238
@@ -1,238 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering file system items.
|
||||
/// </summary>
|
||||
internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started file system discovery scan job...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
long processedFiles = 0L;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
// get the files for each of the media library content locations
|
||||
List<FileInfo> discoveredFiles = [];
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
foreach (FileInfo file in GetFiles(contentLocation.Path, true, cancellationToken))
|
||||
{
|
||||
discoveredFiles.Add(file);
|
||||
processedFiles++;
|
||||
|
||||
// increment the number of processed elements progress in a high-frequency counter with low overhead check
|
||||
if (processedFiles % 1000 == 0)
|
||||
{
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
processedContentLocations++;
|
||||
}
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended file system discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {discoveredFiles.Count} files.");
|
||||
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, discoveredFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all files under the specified directory.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="includeHiddenElements">Specifies whether hidden files and directories should be included.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details.
|
||||
/// </remarks>
|
||||
/// <returns>The discovered collection of files.</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private static IEnumerable<FileInfo> GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> directoryStack = new();
|
||||
directoryStack.Enqueue(new DirectoryInfo(rootDirectoryPath));
|
||||
|
||||
EnumerationOptions enumerationOptions = new()
|
||||
{
|
||||
AttributesToSkip = includeHiddenElements ? FileAttributes.None : FileAttributes.Hidden,
|
||||
IgnoreInaccessible = true,
|
||||
RecurseSubdirectories = false
|
||||
};
|
||||
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
|
||||
// and could result in stack overflow on deeply nested directories
|
||||
while (directoryStack.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
DirectoryInfo currentDirectory = directoryStack.Dequeue();
|
||||
|
||||
// process files first
|
||||
IEnumerable<FileInfo>? files = null;
|
||||
try
|
||||
{
|
||||
files = currentDirectory.EnumerateFiles("*", enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (files is not null)
|
||||
{
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
yield return file;
|
||||
}
|
||||
}
|
||||
|
||||
// process subdirectories - each new subdirectory is added to the same stack queue, for later processing
|
||||
IEnumerable<DirectoryInfo>? subdirs = null;
|
||||
try
|
||||
{
|
||||
subdirs = currentDirectory.EnumerateDirectories("*", enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (subdirs is not null)
|
||||
{
|
||||
foreach (DirectoryInfo subdir in subdirs)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
directoryStack.Enqueue(subdir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
-197
@@ -1,197 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for comparing hashes.
|
||||
/// </summary>
|
||||
internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private Dictionary<string, LibraryScanResultEntity> libraryScanResultEntities = [];
|
||||
private List<FileInfo> files = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HashComparerJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public HashComparerJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
|
||||
// store the incoming payloads as they arrive from parent jobs
|
||||
if (input is Dictionary<string, LibraryScanResultEntity> libraryScanResultsPayload)
|
||||
libraryScanResultEntities = libraryScanResultsPayload;
|
||||
else if (input is List<FileInfo> filesPayload)
|
||||
files = filesPayload;
|
||||
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started file hashing...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
IFileService fileService = asyncServiceScope.ServiceProvider.GetService<IFileService>()!;
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job; total progress is going twice through the list of files, once to determine what needs to be hashed, second to actually hash
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, files.Count * 2, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
// pre-allocate with worst case scenario, to avoid memory copying and garbage collection
|
||||
List<FileInfo> filesToHash = new(files.Count);
|
||||
|
||||
for (int i = 0; i < files.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
FileInfo file = files[i];
|
||||
// fastest path - file does not exist in past scan, so it's a new file
|
||||
if (!libraryScanResultEntities.TryGetValue(file.FullName, out LibraryScanResultEntity? previousScanFile))
|
||||
filesToHash.Add(file);
|
||||
else if (file.Length != previousScanFile.FileSize) // next best comparison, check if file size or the last modified date changed
|
||||
filesToHash.Add(file); // definitely changed
|
||||
else if (file.LastWriteTimeUtc != previousScanFile.LastModified) // potential change - requires hash verification
|
||||
filesToHash.Add(file);
|
||||
|
||||
// remove any found items, to speed up subsequent lookups (if needed, all the remaining entries in this dictionary at the end of the scan are deleted filed)
|
||||
libraryScanResultEntities.Remove(file.FullName);
|
||||
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, files.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
int processedFilesCount = 0;
|
||||
List<ChangedFileSystemFile> processedFiles = await fileHashService.HashFilesAsync(filesToHash, libraryScanResultEntities,
|
||||
async () =>
|
||||
{
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), files.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended file hashing in {sw.ElapsedMilliseconds}ms, hashed {processedFiles.Count} files.");
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, processedFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+33
-54
@@ -1,21 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -23,25 +16,31 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for retrieving persistence data from any eventual previous scans.
|
||||
/// Media library scan job for computing the differences between the files on disk and the media library scan snapshot of the previous scan.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob
|
||||
internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibraryScanDiffJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataDiscoveryJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanDiffJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanDiffJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -52,62 +51,40 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started repo discovering...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository<ILibraryScanResultRepository>();
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job, it's a 1 step job - retrieving stuff from repository
|
||||
// set the initial progress of the scan job, it's a 1 step job - comparing the discovered files against the media library scan snapshot
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// get the results of the last scan of the media library
|
||||
ErrorOr<Dictionary<string, LibraryScanResultEntity>> getScanResultsResult =
|
||||
await libraryScanResultRepository.GetPathMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getScanResultsResult.IsError)
|
||||
return;
|
||||
// mark the staging results against the media library scan snapshot of the previous scan
|
||||
ErrorOr<Updated> markChangesResult = await stagingResultsRepository.MarkChangesAgainstSnapshotAsync(ScanId.Value, LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (markChangesResult.IsError)
|
||||
throw new InvalidOperationException(markChangesResult.FirstError.Description);
|
||||
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended repository discovery scan job in {sw.ElapsedMilliseconds}ms, discovered {getScanResultsResult.Value.Count} items.");
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, getScanResultsResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -116,6 +93,11 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -129,12 +111,9 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData");
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "ComparingFileHashes");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for computing the content hashes of the files that changed since the previous scan.
|
||||
/// </summary>
|
||||
internal sealed class MediaLibraryScanHashJob : MediaLibraryScanJob, IMediaLibraryScanHashJob
|
||||
{
|
||||
private const int HASHING_PAGE_SIZE = 1000; // the number of files that are hashed and written back in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public MediaLibraryScanHashJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService<IFileHashService>()!;
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// count the files that need hashing, for progress reporting purposes
|
||||
ErrorOr<int> getFilesToHashCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashCountResult.IsError)
|
||||
throw new InvalidOperationException(getFilesToHashCountResult.FirstError.Description);
|
||||
int totalFilesToHash = getFilesToHashCountResult.Value;
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedFilesCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// process the files that need hashing in pages, keeping the peak memory bounded regardless of the library size
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<IReadOnlyList<HashedFileSystemFile>> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getFilesToHashPageResult.IsError)
|
||||
throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> filesToHashPage = getFilesToHashPageResult.Value;
|
||||
if (filesToHashPage.Count == 0)
|
||||
break;
|
||||
|
||||
// hash the files of the current page in parallel, invoking the progress callback before each file
|
||||
List<HashedFileSystemFile> hashedFiles = await fileHashService.HashFilesAsync(filesToHashPage, async () =>
|
||||
{
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedFilesCount), totalFilesToHash, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// write the computed hashes back to the staging results
|
||||
ErrorOr<Updated> updateHashesResult = await stagingResultsRepository.UpdateFileHashesAsync(ScanId.Value, hashedFiles, cancellationToken).ConfigureAwait(false);
|
||||
if (updateHashesResult.IsError)
|
||||
throw new InvalidOperationException(updateHashesResult.FirstError.Description);
|
||||
|
||||
lastPath = filesToHashPage[^1].Path;
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "HashingFileContents");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+47
-51
@@ -1,20 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -22,25 +17,31 @@ using System.Threading.Tasks;
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for persisting data of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// Media library scan job for persisting the results of the current scan. This should always be the last job in the directed acyclic job graph.
|
||||
/// </summary>
|
||||
internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob
|
||||
internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMediaLibraryScanResultsSaveJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RepositoryMetadataSaveJob"/> class.
|
||||
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
public MediaLibraryScanResultsSaveJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -51,54 +52,48 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started repository saving...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository<ILibraryScanSnapshotRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
// set the initial progress of the scan job, it's a 1 step job - applying the scan results to the storage medium
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> ints = [1, 2, 3];
|
||||
foreach (int nr in ints)
|
||||
// get the paths of the media library scan snapshot items that are no longer present in the current scan, so that deletion events can be raised for them
|
||||
ErrorOr<IReadOnlyList<string>> getDeletedPathsResult = await libraryScanSnapshotRepository.GetDeletedPathsAsync(LibraryId.Value, ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getDeletedPathsResult.IsError)
|
||||
throw new InvalidOperationException(getDeletedPathsResult.FirstError.Description);
|
||||
|
||||
// apply the results of the current scan to the storage medium, atomically replacing the media library scan snapshot of the previous scan
|
||||
ErrorOr<Updated> applySnapshotSwapResult = await libraryScanSnapshotRepository.ApplySnapshotSwapAsync(LibraryId.Value, ScanId.Value, UserId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (applySnapshotSwapResult.IsError)
|
||||
throw new InvalidOperationException(applySnapshotSwapResult.FirstError.Description);
|
||||
|
||||
// raise a deletion event for every media library scan snapshot item that is no longer present on disk
|
||||
foreach (string deletedPath in getDeletedPathsResult.Value)
|
||||
{
|
||||
await Task.Delay(500);
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await publisher.Publish(new LibraryMediaItemDeletedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, deletedPath, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
// this job finished, and it's the last in the chain, the scan is completed
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
await publisher.Publish(new LibraryScanFinishedDomainEvent(Guid.NewGuid(), compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended repository saving scan job in {sw.ElapsedMilliseconds}ms, saved {ints.Count} items.");
|
||||
// this should always be the last job in the directed acyclic job graph, so no linked child to call further
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -108,6 +103,11 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,13 +123,9 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "SavingScanData");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Helper for publishing the media library scan failure domain event, from within a media library scan job.
|
||||
/// </summary>
|
||||
internal static class ScanFailurePublisher
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes the media library scan failure domain event for the scan that the job is part of.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">Injected factory for creating scopes in which the publisher is resolved.</param>
|
||||
/// <param name="libraryId">The unique identifier of the library whose scan has failed.</param>
|
||||
/// <param name="compositeKey">Model for tracking media library scans.</param>
|
||||
/// <param name="exception">The exception that caused the failure.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public static async Task PublishAsync(IServiceScopeFactory serviceScopeFactory, LibraryId libraryId, MediaLibraryScanCompositeId compositeKey, Exception exception, CancellationToken cancellationToken)
|
||||
{
|
||||
// failure reporting is best-effort, a failure to report the failure must not crash the job processing
|
||||
try
|
||||
{
|
||||
await using AsyncServiceScope asyncServiceScope = serviceScopeFactory.CreateAsyncScope();
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), libraryId, compositeKey, DateTime.UtcNow, exception.Message), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// the failure reporting is best-effort, as the exception cannot be reported if the reporting itself fails
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph.
|
||||
/// </summary>
|
||||
internal sealed class ScanJobRegistry : IScanJobRegistry
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly IReadOnlyDictionary<string, IReadOnlyList<Type>> _jobsByHook;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScanJobRegistry"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">The service provider, used to resolve the registered plugin jobs.</param>
|
||||
/// <param name="jobsByHook">The media library scan job types registered for each hook point, provided by the composition root of the plugin system.</param>
|
||||
public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary<string, IReadOnlyList<Type>> jobsByHook)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_jobsByHook = jobsByHook;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media library scan jobs registered for the provided <paramref name="hookName"/>.
|
||||
/// </summary>
|
||||
/// <param name="hookName">The name of the hook point at which the media library scan jobs were injected.</param>
|
||||
/// <param name="libraryId">The unique identifier of the media library upon which the scan is performed.</param>
|
||||
/// <returns>The collection of media library scan jobs registered at the provided hook point.</returns>
|
||||
public IEnumerable<IMediaLibraryScanJob> GetJobsForHook(string hookName, LibraryId libraryId)
|
||||
{
|
||||
// no plugin jobs are registered for this hook point, unless the plugin system provides them
|
||||
if (!_jobsByHook.TryGetValue(hookName, out IReadOnlyList<Type>? jobTypes))
|
||||
yield break;
|
||||
|
||||
foreach (Type jobType in jobTypes)
|
||||
{
|
||||
IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType);
|
||||
pluginJob.LibraryId = libraryId;
|
||||
yield return pluginJob;
|
||||
}
|
||||
}
|
||||
}
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Common.Errors;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for filtering only files that have known book formats extensions.
|
||||
/// </summary>
|
||||
internal sealed class BooksFileExtensionsFilterJob : MediaLibraryScanJob, IBooksFileExtensionsFilterJob
|
||||
{
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly string[] _knownBookFileExtensions =
|
||||
[
|
||||
".pdf", ".epub", ".mobi", ".azw", ".azw3",
|
||||
".cbz", ".cbr", ".djvu", ".fb2", ".lit",
|
||||
".prc", ".txt", ".doc", ".docx", ".rtf"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileExtensionsFilterJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// </param>
|
||||
public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
if (input is List<FileInfo> payload)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Console.WriteLine("Started book file filtering...");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>();
|
||||
IPathService pathService = asyncServiceScope.ServiceProvider.GetService<IPathService>()!;
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
|
||||
List<FileInfo> bookFiles = new(payload.Count / 2); // pre-allocate with estimated capacity (boy, that's an optimistic view on books...)
|
||||
for (int i = 0; i < payload.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
FileInfo file = payload[i];
|
||||
|
||||
if (HasKnownBookExtension(file.Name.AsSpan()))
|
||||
bookFiles.Add(file);
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// update job progress report
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, i, payload.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
return;
|
||||
// update the last update time
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
sw.Stop();
|
||||
Console.WriteLine($"Ended book file filtering in {sw.ElapsedMilliseconds}ms, filtered {bookFiles.Count} files.");
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, bookFiles, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if <paramref name="filePath"/> has a known book file extension or not.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The file path to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="filePath"/> contains a known book file extension, <see langword="false"/> otherwise.</returns>
|
||||
public bool HasKnownBookExtension(ReadOnlySpan<char> filePath)
|
||||
{
|
||||
// find the last dot in the path
|
||||
int lastDotIndex = filePath.LastIndexOf('.');
|
||||
|
||||
// if no dot found or it's the last character, return false
|
||||
if (lastDotIndex == -1)
|
||||
return false;
|
||||
|
||||
// get the extension part (including the dot)
|
||||
ReadOnlySpan<char> extension = filePath[lastDotIndex..];
|
||||
|
||||
// check against each known extension
|
||||
foreach (string knownExt in _knownBookFileExtensions)
|
||||
if (extension.SequenceEqual(knownExt.AsSpan()))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "FilteringBookFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return Errors.LibraryScanning.FailedToCreateScanJobProgress;
|
||||
}
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
|
||||
|
||||
/// <summary>
|
||||
/// Media library scan job for discovering book file system items.
|
||||
/// </summary>
|
||||
internal sealed class BooksFileSystemDiscoveryJob : MediaLibraryScanJob, IBooksFileSystemDiscoveryJob
|
||||
{
|
||||
private const int STAGING_BATCH_SIZE = 1000; // the number of discovered files that are written to the staging results in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private static readonly HashSet<string> s_bookExtensions = new(
|
||||
[
|
||||
".pdf", ".epub", ".mobi", ".azw", ".azw3",
|
||||
".cbz", ".cbr", ".djvu", ".fb2", ".lit",
|
||||
".prc", ".txt", ".doc", ".docx", ".rtf"
|
||||
],
|
||||
StringComparer.OrdinalIgnoreCase
|
||||
);
|
||||
private static readonly EnumerationOptions s_enumerationOptions = new()
|
||||
{
|
||||
AttributesToSkip = FileAttributes.None, // hidden files and directories are included in the discovery
|
||||
IgnoreInaccessible = true,
|
||||
RecurseSubdirectories = false
|
||||
};
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// increment the number of parents that finished their execution and called this job (beware race conditions, jobs run in parallel)
|
||||
int parentsCompleted = Interlocked.Increment(ref parentsPayloadsExecuted);
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// file system processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryRepository libraryRepository = unitOfWork.GetRepository<ILibraryRepository>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository<IDirectoryScanFingerprintRepository>();
|
||||
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
throw new InvalidOperationException(getLibraryResult.IsError ? getLibraryResult.FirstError.Description : "The media library was not found.");
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
throw new InvalidOperationException(domainLibraryResult.FirstError.Description);
|
||||
|
||||
// when the fast skip is enabled, load the directory scan fingerprints of the library, used to skip the directories that have not changed since the last scan
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath = null;
|
||||
if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan)
|
||||
{
|
||||
ErrorOr<Dictionary<string, DirectoryScanFingerprintEntity>> getFingerprintsResult = await directoryScanFingerprintRepository.GetMappedByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getFingerprintsResult.IsError)
|
||||
throw new InvalidOperationException(getFingerprintsResult.FirstError.Description);
|
||||
fingerprintsByPath = getFingerprintsResult.Value;
|
||||
}
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
TimeSpan heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
DateTime lastHeartbeat = DateTime.UtcNow;
|
||||
int processedContentLocations = 0;
|
||||
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch = [];
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch = [];
|
||||
|
||||
// get the files for each of the media library content locations
|
||||
foreach (FileSystemPathId contentLocation in domainLibraryResult.Value.ContentLocations)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await DiscoverContentLocationAsync(
|
||||
contentLocation.Path,
|
||||
fingerprintsByPath is not null,
|
||||
fingerprintsByPath,
|
||||
stagingBatch,
|
||||
fingerprintBatch,
|
||||
stagingResultsRepository,
|
||||
directoryScanFingerprintRepository,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
processedContentLocations++;
|
||||
|
||||
// increment the number of processed elements progress in a high-frequency counter with low overhead check
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if (now - lastHeartbeat >= heartbeatInterval)
|
||||
{
|
||||
publishJobProgressResult = await PublishJobProgress(
|
||||
publisher, compositeKey, processedContentLocations, domainLibraryResult.Value.ContentLocations.Count, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastHeartbeat = now;
|
||||
}
|
||||
}
|
||||
|
||||
// flush any remaining discovered files and directory scan fingerprints that did not reach the batch size
|
||||
if (stagingBatch.Count > 0)
|
||||
{
|
||||
ErrorOr<Created> insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsError)
|
||||
throw new InvalidOperationException(insertResult.FirstError.Description);
|
||||
}
|
||||
if (fingerprintBatch.Count > 0)
|
||||
{
|
||||
ErrorOr<Updated> upsertResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsError)
|
||||
throw new InvalidOperationException(upsertResult.FirstError.Description);
|
||||
}
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers the book files of a content location of the media library, using a breadth-first traversal, and writes them in batches to the staging results.
|
||||
/// </summary>
|
||||
/// <param name="rootDirectoryPath">The path of the root directory from which to start collecting files.</param>
|
||||
/// <param name="skipUnchangedDirectories">Whether to skip the directories whose last write time has not changed since the last scan, or not.</param>
|
||||
/// <param name="fingerprintsByPath">The directory scan fingerprints of the library, mapped by the directory path. Can be <see langword="null"/> when the fast skip is disabled.</param>
|
||||
/// <param name="stagingBatch">The batch of discovered files that is written to the staging results when it reaches the batch size.</param>
|
||||
/// <param name="fingerprintBatch">The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size.</param>
|
||||
/// <param name="stagingResultsRepository">The repository used to write the discovered files to the staging results.</param>
|
||||
/// <param name="directoryScanFingerprintRepository">The repository used to write the directory scan fingerprints to the storage medium.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <remarks>
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
private async Task DiscoverContentLocationAsync(
|
||||
string rootDirectoryPath,
|
||||
bool skipUnchangedDirectories,
|
||||
Dictionary<string, DirectoryScanFingerprintEntity>? fingerprintsByPath,
|
||||
List<LibraryScanStagingResultsEntity> stagingBatch,
|
||||
List<DirectoryScanFingerprintEntity> fingerprintBatch,
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository,
|
||||
IDirectoryScanFingerprintRepository directoryScanFingerprintRepository,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Queue<DirectoryInfo> directoryQueue = new();
|
||||
directoryQueue.Enqueue(new DirectoryInfo(rootDirectoryPath));
|
||||
|
||||
// use a breadth-first traversal iterative approach, instead of recursion, which is heavier on call frames and memory
|
||||
// and could result in stack overflow on deeply nested directories
|
||||
while (directoryQueue.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
DirectoryInfo currentDirectory = directoryQueue.Dequeue();
|
||||
|
||||
// when the fast skip is enabled, skip the whole subtree of a directory whose last write time has not changed since the last scan
|
||||
if (skipUnchangedDirectories)
|
||||
{
|
||||
DateTime currentLastWriteTimeUtc = currentDirectory.LastWriteTimeUtc;
|
||||
if (fingerprintsByPath is not null &&
|
||||
fingerprintsByPath.TryGetValue(currentDirectory.FullName, out DirectoryScanFingerprintEntity? fingerprint) &&
|
||||
fingerprint.LastWriteTimeUtc == currentLastWriteTimeUtc)
|
||||
continue;
|
||||
|
||||
fingerprintBatch.Add(new DirectoryScanFingerprintEntity()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = LibraryId.Value,
|
||||
Path = currentDirectory.FullName,
|
||||
LastWriteTimeUtc = currentLastWriteTimeUtc
|
||||
});
|
||||
// flush the collected directory scan fingerprints in bounded batches, so that the memory usage stays proportional to the batch size, no matter how many directories the library has
|
||||
if (fingerprintBatch.Count >= STAGING_BATCH_SIZE)
|
||||
{
|
||||
ErrorOr<Updated> upsertFingerprintsResult = await directoryScanFingerprintRepository.UpsertRangeAsync(fingerprintBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertFingerprintsResult.IsError)
|
||||
throw new InvalidOperationException(upsertFingerprintsResult.FirstError.Description);
|
||||
fingerprintBatch.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// process the files of the current directory
|
||||
IEnumerable<FileInfo>? files = null;
|
||||
try
|
||||
{
|
||||
files = currentDirectory.EnumerateFiles("*", s_enumerationOptions)
|
||||
.Where(file => s_bookExtensions.Contains(file.Extension));
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (files is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (FileInfo file in files)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
stagingBatch.Add(new LibraryScanStagingResultsEntity()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryScanId = ScanId.Value,
|
||||
Path = file.FullName,
|
||||
Size = file.Length,
|
||||
Ticks = file.LastWriteTimeUtc.Ticks,
|
||||
ContentHash = 0,
|
||||
PreviousContentHash = 0,
|
||||
NeedsRehash = true,
|
||||
IsNew = true
|
||||
});
|
||||
if (stagingBatch.Count >= STAGING_BATCH_SIZE)
|
||||
{
|
||||
ErrorOr<Created> insertBatchResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false);
|
||||
if (insertBatchResult.IsError)
|
||||
throw new InvalidOperationException(insertBatchResult.FirstError.Description);
|
||||
stagingBatch.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// a file might become inaccessible between enumeration and processing, so the remaining files of the directory are skipped
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// process the subdirectories - each new subdirectory is added to the same stack queue, for later processing
|
||||
IEnumerable<DirectoryInfo>? subdirectories = null;
|
||||
try
|
||||
{
|
||||
subdirectories = currentDirectory.EnumerateDirectories("*", s_enumerationOptions);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
|
||||
if (subdirectories is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (DirectoryInfo subdirectory in subdirectories)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
directoryQueue.Enqueue(subdirectory);
|
||||
}
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "DiscoveringFiles");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+101
-61
@@ -1,20 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
|
||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
using Mediator;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
@@ -26,21 +24,28 @@ namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Writt
|
||||
/// </summary>
|
||||
internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodReadsMetadataScrapJob
|
||||
{
|
||||
private const int ENRICHMENT_PAGE_SIZE = 1000; // the number of media library items that are enriched in a single batch, keeping the peak memory bounded regardless of the library size
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GoodReadsMetadataScrapJob"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details.
|
||||
/// Injected factory for creating scopes in which services are requested.
|
||||
/// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details.
|
||||
/// </param>
|
||||
public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Executes the payload of the media library scan job.
|
||||
/// </summary>
|
||||
/// <typeparam name="TInput">The type of the input parameter representing the data to be processed by this payload.</typeparam>
|
||||
/// <param name="id">The unique identifier of the media library scan job.</param>
|
||||
/// <param name="input">The input data to be processed by this payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task ExecuteAsync<TInput>(Guid id, TInput input, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
@@ -50,67 +55,76 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
|
||||
// only execute this job's payload when it has no parents, or when all the parents finished their execution
|
||||
if (Parents.Count == 0 || parentsCompleted == Parents.Count)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
Console.WriteLine("started goodreads metadata");
|
||||
// see docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork? unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>();
|
||||
IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>();
|
||||
ILibraryRepository libraryRepository = unitOfWork!.GetRepository<ILibraryRepository>();
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// get the library from the repository
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError || getLibraryResult.Value is null)
|
||||
// this needs to be wrapped in a task because even though this job is processed in a "fire and forget" async manner, it still does synchronous
|
||||
// processing that takes time, and would block the processing of scan jobs in the in-memory queue
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
Status = LibraryScanJobStatus.Running;
|
||||
// see docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md for details:
|
||||
await using AsyncServiceScope asyncServiceScope = _serviceScopeFactory.CreateAsyncScope();
|
||||
IUnitOfWork unitOfWork = asyncServiceScope.ServiceProvider.GetService<IUnitOfWork>()!;
|
||||
IPublisher publisher = asyncServiceScope.ServiceProvider.GetService<IPublisher>()!;
|
||||
ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository<ILibraryScanStagingResultsRepository>();
|
||||
|
||||
// convert it to a domain object
|
||||
ErrorOr<Library> domainLibraryResult = getLibraryResult.Value.ToDomainEntity();
|
||||
if (domainLibraryResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId);
|
||||
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload");
|
||||
//ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
// count the media library items that need their metadata enriched, which are the items that were new or changed in this scan
|
||||
ErrorOr<int> getItemsToEnrichCountResult = await stagingResultsRepository.GetFilesToHashCountAsync(ScanId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getItemsToEnrichCountResult.IsError)
|
||||
throw new InvalidOperationException(getItemsToEnrichCountResult.FirstError.Description);
|
||||
int totalItemsToEnrich = getItemsToEnrichCountResult.Value;
|
||||
|
||||
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
// set the initial progress of the scan job
|
||||
ErrorOr<Success> publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
|
||||
List<int> ints = Enumerable.Range(0, 20).ToList();
|
||||
foreach (int nr in ints)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
// increment the number of processed elements progress
|
||||
scanJobProgressResult = MediaLibraryScanJobProgress.Create(
|
||||
nr, 20, "GoodReadsMetadataDownload");
|
||||
//scanJobProgressResult.Value.CompletedItems + 1, domainLibraryResult.Value.ContentLocations.Count, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
DateTime lastUpdateTime = DateTime.UtcNow;
|
||||
int minUpdateIntervalMs = 100;
|
||||
int processedItemsCount = 0;
|
||||
string? lastPath = null;
|
||||
|
||||
// process the media library items that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size
|
||||
while (true)
|
||||
{
|
||||
await publisher!.Publish(new LibraryScanFailedDomainEvent(Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
return;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
ErrorOr<IReadOnlyList<HashedFileSystemFile>> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false);
|
||||
if (getItemsToEnrichPageResult.IsError)
|
||||
throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description);
|
||||
IReadOnlyList<HashedFileSystemFile> itemsToEnrichPage = getItemsToEnrichPageResult.Value;
|
||||
if (itemsToEnrichPage.Count == 0)
|
||||
break;
|
||||
|
||||
// TODO: retrieve the metadata of each media library item from GoodReads, and store it, once the real scraping is implemented
|
||||
foreach (HashedFileSystemFile item in itemsToEnrichPage)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// check if enough time has passed since last update
|
||||
DateTime now = DateTime.UtcNow;
|
||||
if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs)
|
||||
{
|
||||
// increment the number of processed elements progress
|
||||
publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, Interlocked.Increment(ref processedItemsCount), totalItemsToEnrich, cancellationToken).ConfigureAwait(false);
|
||||
if (publishJobProgressResult.IsError)
|
||||
throw new InvalidOperationException(publishJobProgressResult.FirstError.Description);
|
||||
lastUpdateTime = now;
|
||||
}
|
||||
}
|
||||
|
||||
lastPath = itemsToEnrichPage[^1].Path;
|
||||
}
|
||||
await publisher!.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher!.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
Console.WriteLine("ended goodreads metadata");
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, ints, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// this job finished, increment the number of processed jobs progress
|
||||
await publisher.Publish(new LibraryScanProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
Status = LibraryScanJobStatus.Completed;
|
||||
|
||||
// call each linked child with the obtained payload
|
||||
foreach (IMediaLibraryScanJob child in Children)
|
||||
await child.ExecuteAsync(id, input, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
@@ -118,5 +132,31 @@ internal sealed class GoodReadsMetadataScrapJob : MediaLibraryScanJob, IGoodRead
|
||||
Status = LibraryScanJobStatus.Canceled;
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
Status = LibraryScanJobStatus.Failed;
|
||||
await ScanFailurePublisher.PublishAsync(_serviceScopeFactory, LibraryId, MediaLibraryScanCompositeId.Create(ScanId, UserId), exception, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Publishes a job progress update.
|
||||
/// </summary>
|
||||
/// <param name="publisher">The service used to publish the progress update.</param>
|
||||
/// <param name="compositeKey">The composite unique identifier of a media library scan.</param>
|
||||
/// <param name="currentProgress">The current job progress.</param>
|
||||
/// <param name="totalProgress">The total job progress.</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>
|
||||
private async Task<ErrorOr<Success>> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<MediaLibraryScanJobProgress> scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "GoodReadsMetadataDownload");
|
||||
if (scanJobProgressResult.IsError)
|
||||
return scanJobProgressResult.Errors;
|
||||
|
||||
await publisher.Publish(new LibraryScanJobProgressChangedDomainEvent(
|
||||
Guid.NewGuid(), LibraryId, compositeKey, scanJobProgressResult.Value, DateTime.UtcNow), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Microsoft.Extensions.ObjectPool;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -22,70 +20,62 @@ internal class FileHashService : IFileHashService
|
||||
{
|
||||
private const int SAMPLE_COUNT = 6; // number of sample points for hash computation
|
||||
private const ushort DEFAULT_BUFFER_SIZE = 65535; // buffer size (64KB - 1) for reading file chunks
|
||||
private readonly ThreadLocal<byte[]> _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing
|
||||
private static readonly ObjectPool<XxHash64> s_hasherPool = new DefaultObjectPool<XxHash64>(new DefaultPooledObjectPolicy<XxHash64>()); // object pool for reusing hashers, to reduce GC pressure
|
||||
private static readonly ThreadLocal<XxHash64> s_threadLocalHasher = new(() => new XxHash64()); // thread-local hasher to avoid contention and pool management overhead during parallel processing
|
||||
private static readonly ulong s_emptyFileHash = ComputeEmptyHash();
|
||||
|
||||
/// <summary>
|
||||
/// Hashes <paramref name="files"/> by sampling chunks from them.
|
||||
/// Hashes <paramref name="inputFiles"/> by sampling chunks from them.
|
||||
/// </summary>
|
||||
/// <param name="files">The collection of files to hash.</param>
|
||||
/// <param name="previousScanResults">Lookup dictionary of a previous media library scan, used to determine if a file changed or not.</param>
|
||||
/// <param name="inputFiles">The collection of files to hash.</param>
|
||||
/// <param name="callback">Callback to invoke during processing of elements.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>A collection of files that changed since last library scan, along with their hashes.</returns>
|
||||
public async Task<List<ChangedFileSystemFile>> HashFilesAsync(
|
||||
List<FileInfo> files,
|
||||
Dictionary<string, LibraryScanResultEntity> previousScanResults,
|
||||
Func<Task> callback,
|
||||
CancellationToken cancellationToken)
|
||||
/// <returns>A collection of the hashed files, along with their hashes.</returns>
|
||||
public async Task<List<HashedFileSystemFile>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFile> inputFiles, Func<Task> callback, CancellationToken cancellationToken)
|
||||
{
|
||||
List<ChangedFileSystemFile> changedFiles = [];
|
||||
List<HashedFileSystemFile> outputFiles = [];
|
||||
object listLock = new();
|
||||
int totalFiles = files.Count;
|
||||
|
||||
// make use of all available processors
|
||||
ParallelOptions parallelOptions = new()
|
||||
{
|
||||
CancellationToken = cancellationToken,
|
||||
MaxDegreeOfParallelism = Environment.ProcessorCount
|
||||
MaxDegreeOfParallelism = Environment.ProcessorCount // TODO: make this configurable, such that parallelism can be turned off for mechanical hard drives
|
||||
};
|
||||
await Parallel.ForEachAsync(files, parallelOptions, async (file, cancellationToken) =>
|
||||
await Parallel.ForEachAsync(inputFiles, parallelOptions, async (file, cancellationToken) =>
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
// invoke the method that triggers progress reporting
|
||||
await callback().ConfigureAwait(false);
|
||||
// if file has no contents, it needs no hashing
|
||||
if (file.Length == 0)
|
||||
return;
|
||||
// buffer management with thread-local reuse
|
||||
byte[] buffer = _threadLocalBuffer.Value ?? new byte[DEFAULT_BUFFER_SIZE];
|
||||
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Length);
|
||||
|
||||
ushort bufferSize = (ushort)Math.Min(DEFAULT_BUFFER_SIZE, file.Size);
|
||||
|
||||
// get the file hash and check if it differs from the one stored on previous scan
|
||||
ulong currentHash = ComputeFileHash(file.FullName, file.Length, bufferSize, buffer);
|
||||
bool isChanged = !previousScanResults.TryGetValue(file.FullName, out LibraryScanResultEntity? previous) || previous.ContentHash != currentHash;
|
||||
ulong currentHash = file.Size == 0
|
||||
? s_emptyFileHash // precomputed constant: XxHash64 hash of zero-length input
|
||||
: ComputeFileHash(file.Path, file.Size, bufferSize);
|
||||
|
||||
if (isChanged) // hash changed, file needs to be re-scanned
|
||||
lock (listLock)
|
||||
changedFiles.Add(new ChangedFileSystemFile(file, currentHash));
|
||||
// the decision of whether a file changed is already made before hashing, so all files that reach this point get their hash stored
|
||||
lock (listLock)
|
||||
outputFiles.Add(file with { CurrentHash = currentHash });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine($"Error processing {file.FullName}: {ex.Message}");
|
||||
Debug.WriteLine($"Error processing {file.Path}: {ex.Message}");
|
||||
}
|
||||
});
|
||||
|
||||
return changedFiles;
|
||||
return outputFiles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes content hash using memory-mapped sampling.
|
||||
/// </summary>
|
||||
/// <param name="filePath">The path of the file to hash.</param>
|
||||
/// <param name="fileSize">The size of the file, in bytes.</param>
|
||||
/// <param name="bufferSize">Sample window size (automatically clamped to file size).</param>
|
||||
/// <param name="buffer">Reusable read buffer (thread-local allocation optimized).</param>
|
||||
private unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize, byte[] buffer)
|
||||
private static unsafe ulong ComputeFileHash(string filePath, long fileSize, ushort bufferSize)
|
||||
{
|
||||
// create a memory-mapped file for efficient access to large files
|
||||
using MemoryMappedFile memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read);
|
||||
@@ -98,8 +88,11 @@ internal class FileHashService : IFileHashService
|
||||
{
|
||||
// get a direct pointer to the memory-mapped file, for faster access
|
||||
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref memoryPointer);
|
||||
// get a hasher from the pool to avoid allocations
|
||||
XxHash64 hasher = s_hasherPool.Get();
|
||||
|
||||
// get the thread-local hasher and reset it before use; resetting at entry (rather than at exit) ensures
|
||||
// the hasher is always in a clean state even if a previous call on this thread threw mid-computation
|
||||
XxHash64 hasher = s_threadLocalHasher.Value!;
|
||||
hasher.Reset();
|
||||
|
||||
// allocate hash result buffer on the stack, to avoid heap allocation
|
||||
Span<byte> hashSpan = stackalloc byte[sizeof(ulong)];
|
||||
@@ -122,7 +115,7 @@ internal class FileHashService : IFileHashService
|
||||
return BitConverter.ToUInt64(hashSpan);
|
||||
}
|
||||
finally
|
||||
{
|
||||
{
|
||||
if (memoryPointer is not null) // always release the pointer, to prevent memory leaks
|
||||
memoryMappedViewAccessor.SafeMemoryMappedViewHandle.ReleasePointer();
|
||||
}
|
||||
@@ -145,7 +138,7 @@ internal class FileHashService : IFileHashService
|
||||
// for larger files, sample at strategic points:
|
||||
yield return 0; // beginning of the file
|
||||
yield return fileSize / 4; // quarter of the file
|
||||
yield return fileSize / 2; // file of the file
|
||||
yield return fileSize / 2; // half of the file
|
||||
yield return 3 * fileSize / 4; // three quarters of the file
|
||||
yield return Math.Max(0, fileSize - bufferSize); // end of the file (ensure we don't go past the end)
|
||||
|
||||
@@ -154,4 +147,16 @@ internal class FileHashService : IFileHashService
|
||||
for (int i = 1; i <= SAMPLE_COUNT - 4; i++)
|
||||
yield return interval * i;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the hash for an empty file, which is a special case, since it has no content to sample.
|
||||
/// </summary>
|
||||
/// <returns>The hash value for an empty file.</returns>
|
||||
private static ulong ComputeEmptyHash()
|
||||
{
|
||||
XxHash64 hasher = new();
|
||||
Span<byte> hashSpan = stackalloc byte[sizeof(ulong)];
|
||||
hasher.TryGetCurrentHash(hashSpan, out _);
|
||||
return BitConverter.ToUInt64(hashSpan);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Debug"
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
|
||||
}
|
||||
},
|
||||
"Enrich": [
|
||||
|
||||
+13
-9
@@ -34,8 +34,9 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
|
||||
CoverImage: "/media/posters/myPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
RequestParam(r => r.Title, "The title of the media library. Required.");
|
||||
@@ -44,8 +45,9 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
|
||||
RequestParam(r => r.CoverImage, "The path of the image file used as the cover for the library. Optional.");
|
||||
RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.");
|
||||
RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.");
|
||||
RequestParam(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
|
||||
RequestParam(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
|
||||
RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
|
||||
RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
|
||||
RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.");
|
||||
|
||||
ResponseParam<LibraryResponse>(r => r.Id, "The unique identifier of the entity.");
|
||||
ResponseParam<LibraryResponse>(r => r.UserId, "The unique identifier of the user owning the media library.");
|
||||
@@ -55,12 +57,13 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
|
||||
ResponseParam<LibraryResponse>(r => r.CoverImage, "The path of the image file used as the cover for the library.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.CreatedOnUtc, "The date and time when the entity was created.");
|
||||
ResponseParam<LibraryResponse>(r => r.UpdatedOnUtc, "The date and time when the entity was last updated.");
|
||||
|
||||
Response(201, "The media library was successfuly created.", example:
|
||||
Response(201, "The media library was successfully created.", example:
|
||||
new LibraryResponse(
|
||||
Id: Guid.NewGuid(),
|
||||
UserId: Guid.NewGuid(),
|
||||
@@ -70,8 +73,9 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
|
||||
CoverImage: "/media/myPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
));
|
||||
|
||||
+6
-4
@@ -33,8 +33,9 @@ public class GetEnabledLibrariesEndpointSummary : Summary<GetEnabledLibrariesEnd
|
||||
CoverImage: "/media/myTvShowPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
),
|
||||
@@ -47,8 +48,9 @@ public class GetEnabledLibrariesEndpointSummary : Summary<GetEnabledLibrariesEnd
|
||||
CoverImage: "/media/myMoviePoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: true,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: true,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: true,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
)
|
||||
|
||||
+6
-4
@@ -33,8 +33,9 @@ public class GetLibrariesEndpointSummary : Summary<GetLibrariesEndpoint, EmptyRe
|
||||
CoverImage: "/media/myTvShowPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
),
|
||||
@@ -47,8 +48,9 @@ public class GetLibrariesEndpointSummary : Summary<GetLibrariesEndpoint, EmptyRe
|
||||
CoverImage: "/media/myMoviePoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: true,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: true,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: true,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
)
|
||||
|
||||
+6
-4
@@ -38,8 +38,9 @@ public class GetLibraryEndpointSummary : Summary<GetLibraryEndpoint, GetLibraryR
|
||||
ResponseParam<LibraryResponse>(r => r.CoverImage, "The path of the image file used as the cover for the library.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.CreatedOnUtc, "The date and time when the entity was created.");
|
||||
ResponseParam<LibraryResponse>(r => r.UpdatedOnUtc, "The date and time when the entity was last updated.");
|
||||
|
||||
@@ -52,8 +53,9 @@ public class GetLibraryEndpointSummary : Summary<GetLibraryEndpoint, GetLibraryR
|
||||
CoverImage: "/media/myPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
));
|
||||
|
||||
+13
-9
@@ -36,8 +36,9 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
|
||||
CoverImage: "/media/posters/myPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false
|
||||
);
|
||||
|
||||
RequestParam(r => r.Id, "The unique identifier of the media library. Required.");
|
||||
@@ -48,8 +49,9 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
|
||||
RequestParam(r => r.CoverImage, "The path of the image file used as the cover for the library. Optional.");
|
||||
RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional.");
|
||||
RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional.");
|
||||
RequestParam(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
|
||||
RequestParam(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
|
||||
RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional.");
|
||||
RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional.");
|
||||
RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional.");
|
||||
|
||||
ResponseParam<LibraryResponse>(r => r.Id, "The unique identifier of the entity.");
|
||||
ResponseParam<LibraryResponse>(r => r.UserId, "The unique identifier of the user owning the media library.");
|
||||
@@ -59,12 +61,13 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
|
||||
ResponseParam<LibraryResponse>(r => r.CoverImage, "The path of the image file used as the cover for the library.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed.");
|
||||
ResponseParam<LibraryResponse>(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not.");
|
||||
ResponseParam<LibraryResponse>(r => r.CreatedOnUtc, "The date and time when the entity was created.");
|
||||
ResponseParam<LibraryResponse>(r => r.UpdatedOnUtc, "The date and time when the entity was last updated.");
|
||||
|
||||
Response(200, "The media library was successfuly updated.", example:
|
||||
Response(200, "The media library was successfully updated.", example:
|
||||
new LibraryResponse(
|
||||
Id: Guid.NewGuid(),
|
||||
UserId: Guid.NewGuid(),
|
||||
@@ -74,8 +77,9 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
|
||||
CoverImage: "/media/myPoster.jpg",
|
||||
IsEnabled: true,
|
||||
IsLocked: false,
|
||||
DownloadMedatadaFromWeb: true,
|
||||
SaveMetadataInMediaDirectories: false,
|
||||
DownloadMetadataFromWeb: true,
|
||||
ShouldSaveMetadataInMediaDirectories: false,
|
||||
ShouldSkipUnchangedDirectoriesDuringScan: false,
|
||||
CreatedOnUtc: DateTime.UtcNow,
|
||||
UpdatedOnUtc: default
|
||||
));
|
||||
|
||||
@@ -12,6 +12,7 @@ using Lumina.Presentation.Api.Common.DependencyInjection;
|
||||
using Lumina.Presentation.Api.Common.Middlewares;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -86,6 +87,15 @@ public class Program
|
||||
{
|
||||
LuminaDbContext context = services.GetRequiredService<LuminaDbContext>();
|
||||
await context.Database.MigrateAsync();
|
||||
|
||||
// enable the Write-Ahead Logging journal mode and a busy timeout, so that the Entity Framework connection and the dedicated connections
|
||||
// used by the bulk data access operations of Dapper can access the database concurrently, without database locking errors
|
||||
SqliteConnection sqliteConnection = new(context.Database.GetDbConnection().ConnectionString);
|
||||
sqliteConnection.Open();
|
||||
using SqliteCommand sqliteCommand = sqliteConnection.CreateCommand();
|
||||
sqliteCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA busy_timeout=10000;";
|
||||
sqliteCommand.ExecuteNonQuery();
|
||||
sqliteConnection.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -56,10 +56,16 @@ public class LibraryModel
|
||||
/// <summary>
|
||||
/// Gets or sets whether this media library should update the metadata of its elements from the web, or not.
|
||||
/// </summary>
|
||||
public bool DownloadMedatadaFromWeb { get; set; } = true;
|
||||
public bool DownloadMetadataFromWeb { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether this media library should copy the downloaded metadata into the media library content locations, or not.
|
||||
/// </summary>
|
||||
public bool SaveMetadataInMediaDirectories { get; set; } = false;
|
||||
public bool ShouldSaveMetadataInMediaDirectories { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether this media library should skip the directories whose contents have not changed since the last scan, during the scan. This is an opt-in setting, because it relies on directory metadata,
|
||||
/// which does not change when the contents of an existing file are edited, and such edits could be missed while this setting is enabled.
|
||||
/// </summary>
|
||||
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; set; } = false;
|
||||
}
|
||||
+1
@@ -95,6 +95,7 @@ public class LibraryManagementController : Controller
|
||||
[RequirePermission(AuthorizationPermission.CanCreateLibraries)]
|
||||
public async Task<IActionResult> SaveLibrary([FromBody] LibraryModel data, CancellationToken cancellationToken)
|
||||
{
|
||||
// TODO: 1. this also needs to send the image files themselves to the API, since the server could be remote; for now, it assumes local paths which it can later read, which works only if the server is local too
|
||||
// call different API endpoints based on whether this is a new library or an existing one
|
||||
LibraryModel response = data.Id.HasValue
|
||||
? await _apiHttpClient.PutAsync<LibraryModel, LibraryModel>($"libraries/{data.Id}", data, cancellationToken).ConfigureAwait(false)
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Filmreihe</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Buchdateien werden gefiltert...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Metadaten werden von GoodReads heruntergeladen...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Berechne die Datei-Hashes...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Grafischer Roman</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Entfernen</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Vergangene Scan-Daten werden abgerufen...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Scandaten werden gespeichert...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Film Series</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtering book files...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Downloading metadata from GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Hashing file contents...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Graphic Novel</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Remove</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Retrieving past scan data...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Saving scan data...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinematográfica</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtrando archivos de libros...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Descargando metadatos de GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calculando los hashes de los archivos...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Novela Gráfica</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Eliminar</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Recuperando datos de escaneos anteriores...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Guardando datos del escaneo...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinématographique</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtrage des fichiers de livres...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Téléchargement des métadonnées depuis GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calcul des hachages des fichiers...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Roman Graphique</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Supprimer</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Récupération des données de scan précédentes...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Sauvegarde des données de scan en cours...</value>
|
||||
</data>
|
||||
|
||||
@@ -186,12 +186,12 @@
|
||||
<data name="FilmSeries" xml:space="preserve">
|
||||
<value>Saga Cinematografica</value>
|
||||
</data>
|
||||
<data name="FilteringBookFiles" xml:space="preserve">
|
||||
<value>Filtraggio dei file di libri...</value>
|
||||
</data>
|
||||
<data name="GoodReadsMetadataDownload" xml:space="preserve">
|
||||
<value>Scaricamento dei metadati da GoodReads...</value>
|
||||
</data>
|
||||
<data name="HashingFileContents" xml:space="preserve">
|
||||
<value>Calcolo degli hash dei file...</value>
|
||||
</data>
|
||||
<data name="GraphicNovel" xml:space="preserve">
|
||||
<value>Romanzo Grafico</value>
|
||||
</data>
|
||||
@@ -252,9 +252,6 @@
|
||||
<data name="Remove" xml:space="preserve">
|
||||
<value>Rimuovere</value>
|
||||
</data>
|
||||
<data name="RetrievingPastScanData" xml:space="preserve">
|
||||
<value>Recupero dei dati di scansione precedenti...</value>
|
||||
</data>
|
||||
<data name="SavingScanData" xml:space="preserve">
|
||||
<value>Salvataggio dei dati di scansione...</value>
|
||||
</data>
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user