diff --git a/.editorconfig b/.editorconfig index 040ccd3e..781bea5c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..36ebb823 --- /dev/null +++ b/AGENTS.md @@ -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` and `ErrorOr` 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` - never throw exceptions unless explicitly needed, for example, in startup configuration files. +- In XML documentation, use `` for language specific references, don't use the generic `etc`. 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 blocks). +- prefer avoiding `/// ` 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 `AddLayerServices()` + 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/.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). diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntity.cs new file mode 100644 index 00000000..8da50a5d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntity.cs @@ -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; + +/// +/// 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. +/// +[DebuggerDisplay("Id: {Id}; Path: {Path}")] +public class DirectoryScanFingerprintEntity : IStorageEntity +{ + /// + /// Gets the Id of the directory scan fingerprint. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the media library to which this directory scan fingerprint belongs. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the path of the directory to which this directory scan fingerprint belongs. + /// + public required string Path { get; init; } + + /// + /// Gets the last write time of the directory, in UTC, at the moment when the directory was scanned. + /// + public required DateTime LastWriteTimeUtc { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index 080dc156..92edd6ec 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -63,12 +63,17 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMedatadaFromWeb { get; init; } + public bool DownloadMetadataFromWeb { get; init; } /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. /// - public bool SaveMetadataInMediaDirectories { get; init; } + public bool ShouldSaveMetadataInMediaDirectories { get; init; } + + /// + /// Gets whether this media library should skip the directories whose contents have not changed since the last scan, during the scan. + /// + public bool ShouldSkipUnchangedDirectoriesDuringScan { get; init; } /// /// Gets the user that owns the media library. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs index 8ccc1472..81810acc 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntity.cs @@ -23,6 +23,11 @@ public class LibraryScanResultEntity : IStorageEntity /// public required Guid LibraryScanId { get; init; } + /// + /// Gets the status of the media library scan file. + /// + public required LibraryScanFileStatus Status { get; init; } + /// /// Gets the path of the media library scan file. /// @@ -39,9 +44,9 @@ public class LibraryScanResultEntity : IStorageEntity public required long FileSize { get; init; } /// - /// 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. /// - public required DateTime LastModified { get; init; } + public required long Ticks { get; init; } /// /// Gets the media library scan that this scan result belongs to. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntity.cs new file mode 100644 index 00000000..acf4713d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntity.cs @@ -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; + +/// +/// Repository entity for a media library item, representing the current state of a previously scanned media item, as a snapshot. +/// +[DebuggerDisplay("Id: {Id}; Path: {Path}")] +public class LibraryScanSnapshotEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets the Id of the media library scan snapshot item. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the media library to which this media library scan snapshot item belongs. + /// + public required Guid LibraryId { get; init; } + + /// + /// Gets the path of the media library scan snapshot item. + /// + public required string Path { get; init; } + + /// + /// Gets the hash calculated for the media library scan snapshot item. + /// + public required ulong ContentHash { get; init; } + + /// + /// Gets the size of the media library scan snapshot item, in bytes. + /// + public required long FileSize { get; init; } + + /// + /// Gets the time and date when the media library scan snapshot item was last modified, stored in ticks. + /// + public required long Ticks { get; init; } + + /// + /// Gets the media library to which this media library scan snapshot item belongs. + /// + public required LibraryEntity Library { get; init; } = null!; + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntity.cs new file mode 100644 index 00000000..eb77076a --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntity.cs @@ -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; + +/// +/// 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. +/// +[DebuggerDisplay("Id: {Id}; Path: {Path}")] +public class LibraryScanStagingResultsEntity : IStorageEntity +{ + /// + /// Gets the Id of the media library scan staging result. + /// + public required Guid Id { get; init; } + + /// + /// Gets the Id of the media library scan that this staging result belongs to. + /// + public required Guid LibraryScanId { get; init; } + + /// + /// Gets the path of the media library scan staging result. + /// + public required string Path { get; init; } + + /// + /// Gets the size of the media library scan staging result, in bytes. + /// + public required long Size { get; init; } + + /// + /// Gets the time and date when the file system item was last modified, stored in ticks. + /// + public required long Ticks { get; init; } + + /// + /// Gets the hash calculated for the media library scan staging result. + /// + public required ulong ContentHash { get; init; } + + /// + /// 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. + /// + public required ulong PreviousContentHash { get; init; } + + /// + /// 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. + /// + public required bool NeedsRehash { get; init; } + + /// + /// 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. + /// + public required bool IsNew { get; init; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs new file mode 100644 index 00000000..9251f07d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Common/Actions/IInsertRangeRepositoryAction.cs @@ -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; + +/// +/// Interface defining the "insert range" action for interacting with a generic persistance medium. +/// +/// The type used for the insert range action. It should implement . +public interface IInsertRangeRepositoryAction where TModel : IStorageEntity +{ + /// + /// Saves a collection of elements of type in the storage medium. + /// + /// The elements to be saved. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> InsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs new file mode 100644 index 00000000..c075318d --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/IDirectoryScanFingerprintRepository.cs @@ -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; + +/// +/// Interface for the repository for directory scan fingerprints. +/// +public interface IDirectoryScanFingerprintRepository : IRepository +{ + /// + /// Gets the directory scan fingerprints of a media library, mapped by the directory path. + /// + /// The unique identifier of the library for which to get the directory scan fingerprints. + /// Cancellation token that can be used to stop the execution. + /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. + Task>> GetMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Inserts or updates the provided directory scan fingerprints in the storage medium. + /// + /// The directory scan fingerprints to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertRangeAsync(IReadOnlyCollection entities, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs index 09a580be..bbc44d54 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanResultRepository.cs @@ -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, IInsertRepositoryAction { - /// - /// Gets all media library scan results that belong to the last scan of a library identified by , from the storage medium. - /// - /// The unique identifier of the library for which to get the results of the last scans. - /// Cancellation token that can be used to stop the execution. - /// An containing either a path mapped dictionary of , or an error. - Task>> GetPathMappedByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs new file mode 100644 index 00000000..b8d260c9 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanSnapshotRepository.cs @@ -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; + +/// +/// Interface for the repository for media library scan snapshots. +/// +public interface ILibraryScanSnapshotRepository : IRepository +{ + /// + /// 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. + /// + /// The unique identifier of the library for which to get the deleted media library scan snapshot item paths. + /// The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of deleted media library scan snapshot item paths, or an error. + Task>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken); + + /// + /// 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. + /// + /// The unique identifier of the library for which to apply the scan results. + /// The unique identifier of the media library scan whose results are applied. + /// The unique identifier of the user that initiated the media library scan, used for audit purposes. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ApplySnapshotSwapAsync(Guid libraryId, Guid scanId, Guid userId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs new file mode 100644 index 00000000..14e22897 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaLibrary/ILibraryScanStagingResultsRepository.cs @@ -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; + +/// +/// Interface for the repository for media library scan staging results. +/// +public interface ILibraryScanStagingResultsRepository : IRepository, + IInsertRangeRepositoryAction +{ + /// + /// 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. + /// + /// The unique identifier of the media library scan whose staging results are marked. + /// The unique identifier of the library whose media library scan snapshot is compared against. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the number of media library scan staging results of the current scan that need their content hashed. + /// + /// The unique identifier of the media library scan whose staging results are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of staging results that need hashing, or an error. + Task> GetFilesToHashCountAsync(Guid scanId, CancellationToken cancellationToken); + + /// + /// Gets a page of the media library scan staging results that need their content hashed, ordered by path, using keyset pagination. + /// + /// The unique identifier of the media library scan whose staging results are retrieved. + /// The path of the last retrieved file system item, used for keyset pagination. Pass to get the first page. + /// The maximum number of staging results to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of staging results that need hashing, or an error. + Task>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken); + + /// + /// Updates the content hashes of the provided media library scan staging results. + /// + /// The unique identifier of the media library scan whose staging results are updated. + /// The file system items whose content hashes are updated. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection hashedFiles, CancellationToken cancellationToken); + + /// + /// Clears all the media library scan staging results of the provided media library scan from the storage medium. + /// + /// The unique identifier of the media library scan whose staging results are cleared. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ClearForScanAsync(Guid scanId, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs b/src/Lumina.Application/Common/Infrastructure/Models/FileSystem/FileSystemTreeNode.cs similarity index 92% rename from src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs rename to src/Lumina.Application/Common/Infrastructure/Models/FileSystem/FileSystemTreeNode.cs index 8bbd941a..e0e07f3b 100644 --- a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/FileSystemTreeNode.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/FileSystem/FileSystemTreeNode.cs @@ -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; /// /// Generic file system node. diff --git a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs deleted file mode 100644 index 04fd1433..00000000 --- a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/ChangedFileSystemFile.cs +++ /dev/null @@ -1,14 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -using System.IO; -#endregion - -namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; - -/// -/// Represents an item for the payload of the file hashing media library scan job. -/// -/// The file to whom belongs. -/// The hash of . -[DebuggerDisplay("File: {File}; FileHash: {FileHash}")] -public record ChangedFileSystemFile(FileInfo File, ulong FileHash); diff --git a/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/HashedFileSystemFile.cs b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/HashedFileSystemFile.cs new file mode 100644 index 00000000..355b8b9d --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Models/MediaLibraryScanJobPayloads/HashedFileSystemFile.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads; + +/// +/// Represents an item for the payload of the file hashing media library scan job. +/// +[DebuggerDisplay("Path = {Path}, CurrentHash = {CurrentHash}, OldHash = {OldHash}, Ticks = {Ticks}, Size = {Size}")] +[StructLayout(LayoutKind.Sequential)] +public struct HashedFileSystemFile : IEquatable +{ + /// + /// The path of the file system file. + /// + public string Path { get; set; } + + /// + /// The size of the file system file. + /// + public long Size { get; set; } + + /// + /// The current hash obtained by sampling the file system file contents. + /// + public ulong CurrentHash { get; set; } + + /// + /// The old hash of the file system file, stored at the previous scan. + /// + public ulong OldHash { get; set; } + + /// + /// The time and date when the file system file was last modified, stored in ticks. + /// + public long Ticks { get; set; } + + /// + public readonly bool Equals(HashedFileSystemFile other) + { + return Size == other.Size && CurrentHash == other.CurrentHash && OldHash == other.OldHash && Ticks == other.Ticks && Path == other.Path; + } + + /// + public override readonly bool Equals(object? obj) + { + return obj is HashedFileSystemFile item && Equals(item); + } + + /// + public static bool operator ==(HashedFileSystemFile left, HashedFileSystemFile right) + { + return left.Equals(right); + } + + /// + public static bool operator !=(HashedFileSystemFile left, HashedFileSystemFile right) + { + return !(left == right); + } + + /// + public override readonly int GetHashCode() + { + return HashCode.Combine(Size, CurrentHash, OldHash, Ticks, Path); + } +} diff --git a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs index b191d607..8d42f473 100644 --- a/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs +++ b/src/Lumina.Application/Common/Infrastructure/Security/IFileHashService.cs @@ -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 by sampling chunks from them. /// /// The collection of files to hash. - /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. /// Callback to invoke during processing of elements. /// Cancellation token that can be used to stop the execution. - /// A collection of files that changed since last library scan, along with their hashes. - Task> HashFilesAsync( - List files, - Dictionary previousScanResults, - Func callback, - CancellationToken cancellationToken); + /// A collection of the hashed files, along with their hashes. + Task> HashFilesAsync(IReadOnlyCollection files, Func callback, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index deda7756..75673944 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -27,8 +27,9 @@ public static class AddMediaLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMedatadaFromWeb, - request.SaveMetadataInMediaDirectories + request.DownloadMetadataFromWeb, + request.ShouldSaveMetadataInMediaDirectories, + request.ShouldSkipUnchangedDirectoriesDuringScan ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 92c979af..08598ec3 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -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 /// /// The repository entity to be converted. /// - /// An containing either a successfuly converted , or an error message. + /// An containing either a successfully converted , or an error message. /// public static ErrorOr 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() ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index 75f59244..dac14f8a 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -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, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index 6275c61c..c0dfc446 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -27,8 +27,9 @@ public static class UpdateLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMedatadaFromWeb, - request.SaveMetadataInMediaDirectories + request.DownloadMetadataFromWeb, + request.ShouldSaveMetadataInMediaDirectories, + request.ShouldSkipUnchangedDirectoriesDuringScan ); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index 466ed364..d520d53a 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -17,8 +17,9 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [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>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 6f5f9976..0083ff4d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -65,7 +65,7 @@ public class AddLibraryCommandHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfuly created , or an error message. + /// An containing either a successfully created , or an error message. /// public async ValueTask> Handle(AddLibraryCommand request, CancellationToken cancellationToken) { @@ -98,8 +98,9 @@ public class AddLibraryCommandHandler : IRequestHandlerThe path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [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>; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 2f023a52..f7974192 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -68,7 +68,7 @@ public class UpdateLibraryCommandHandler : IRequestHandlerThe request to be handled. /// Cancellation token that can be used to stop the execution. /// - /// An containing either a successfuly updated , or an error message. + /// An containing either a successfully updated , or an error message. /// public async ValueTask> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken) { @@ -110,8 +110,9 @@ public class UpdateLibraryCommandHandler : IRequestHandler ScanId.Create(libraryScan.Id)).ToList() ); if (createLibraryResult.IsError) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs index 3614631d..d22c19a0 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandler.cs @@ -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 { private readonly IMediaLibraryScanningService _mediaLibraryScanningService; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly ILibraryScanRepository _libraryScanRepository; + private readonly IUnitOfWork _unitOfWork; /// /// Initializes a new instance of the class. /// /// Injected service for scanning media libraries. + /// Injected tracker used for canceling media library scans. + /// Injected tracker used for media library scans progress. /// Injected unit of work for interacting with the data access layer repositories. - 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(); + _unitOfWork = unitOfWork; } /// @@ -58,5 +74,14 @@ public class LibraryScanCancelledDomainEventHandler : INotificationHandler cancelScanResult = _mediaLibraryScanningService.CancelScan(libraryScanDomainResult.Value); if (cancelScanResult.IsError) throw new EventualConsistencyException(cancelScanResult.FirstError, cancelScanResult.Errors); + + // release the scan processing resources + ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(domainEvent.ScanId, UserId.Create(getLibraryScansResult.Value.UserId)); + _mediaLibrariesScanCancellationTracker.RemoveScan(compositeId); + _mediaLibrariesScanProgressTracker.RemoveScanProgress(compositeId); + ErrorOr clearStagingResult = await stagingResultsRepository.ClearForScanAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); + if (clearStagingResult.IsError) + throw new EventualConsistencyException(clearStagingResult.FirstError, clearStagingResult.Errors); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 11784bc4..e202ef87 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -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 { private readonly IMediaLibraryScanProgressNotifier _debouncedLibraryScanProgressNotifier; + private readonly IMediaLibrariesScanCancellationTracker _mediaLibrariesScanCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker; private readonly IUnitOfWork _unitOfWork; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. + /// Injected tracker used for canceling media library scans. + /// Injected tracker used for media library scans progress. /// Injected service for notifying media libraries scan progress changes to third parties. - 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(); + ILibraryScanStagingResultsRepository stagingResultsRepository = _unitOfWork.GetRepository(); // get the library scan from the repository ErrorOr getLibraryScansResult = await libraryScanRepository.GetByIdAsync( @@ -69,8 +82,16 @@ public class LibraryScanFailedDomainEventHandler : INotificationHandler 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); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 4926a4bb..17ee8a78 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -63,7 +63,7 @@ public class LibraryScanQueuedDomainEventHandler : INotificationHandler 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); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index 9b0021db..bfc717ba 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -13,8 +13,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [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 ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index c718ab86..2f18881a 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -18,8 +18,9 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. -/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [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 ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 98bd578f..4cc80534 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -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 ); diff --git a/src/Lumina.DataAccess/Common/Configuration/DirectoryScanFingerprintConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/DirectoryScanFingerprintConfiguration.cs new file mode 100644 index 00000000..5b411119 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/DirectoryScanFingerprintConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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() + .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); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 77d66a5b..6e085ae3 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -46,13 +46,16 @@ public class LibraryConfiguration : IEntityTypeConfiguration 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 // 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); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs index 6c14ad63..3765248c 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanConfiguration.cs @@ -57,5 +57,11 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration 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 } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanResultConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanResultConfiguration.cs index a4a78bd7..5f500424 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryScanResultConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanResultConfiguration.cs @@ -18,12 +18,12 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration 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 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() + .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); } } diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanSnapshotConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanSnapshotConfiguration.cs new file mode 100644 index 00000000..756de536 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanSnapshotConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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); + } +} diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryScanStagingResultsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryScanStagingResultsConfiguration.cs new file mode 100644 index 00000000..d5c13f92 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryScanStagingResultsConfiguration.cs @@ -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; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder 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() + .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 }); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.Designer.cs new file mode 100644 index 00000000..8f3096da --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.Designer.cs @@ -0,0 +1,877 @@ +// +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 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastModified") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.cs b/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.cs new file mode 100644 index 00000000..49c17494 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250302132630_AddsLibraryScanFileStatusColumn.cs @@ -0,0 +1,30 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddsLibraryScanFileStatusColumn : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Status", + table: "LibraryScanResults", + type: "TEXT", + maxLength: 10, + nullable: false, + defaultValue: "") + .Annotation("Relational:ColumnOrder", 5); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Status", + table: "LibraryScanResults"); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.Designer.cs new file mode 100644 index 00000000..74777280 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.Designer.cs @@ -0,0 +1,877 @@ +// +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 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.cs b/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.cs new file mode 100644 index 00000000..f105d955 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250317192401_AddsLibraryScanResultTickColumn.cs @@ -0,0 +1,42 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddsLibraryScanResultTickColumn : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "LastModified", + table: "LibraryScanResults"); + + migrationBuilder.AddColumn( + name: "Ticks", + table: "LibraryScanResults", + type: "INTEGER", + nullable: false, + defaultValue: 0L) + .Annotation("Relational:ColumnOrder", 4); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Ticks", + table: "LibraryScanResults"); + + migrationBuilder.AddColumn( + name: "LastModified", + table: "LibraryScanResults", + type: "TEXT", + nullable: false, + defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)) + .Annotation("Relational:ColumnOrder", 4); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.Designer.cs new file mode 100644 index 00000000..dbaf4644 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.Designer.cs @@ -0,0 +1,875 @@ +// +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 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.cs b/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.cs new file mode 100644 index 00000000..5eb788f4 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250502110735_RemoveUniqueConstraintOnScanResultsFilePaths.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class RemoveUniqueConstraintOnScanResultsFilePaths : Migration +{ + /// + 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"); + } + + /// + 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); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.Designer.cs new file mode 100644 index 00000000..975b71d0 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.Designer.cs @@ -0,0 +1,876 @@ +// +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 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.cs b/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.cs new file mode 100644 index 00000000..ec13ebc4 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20250502152428_AddsIndexOnLibraryScansTable.cs @@ -0,0 +1,36 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations; + +/// +public partial class AddsIndexOnLibraryScansTable : Migration +{ + /// + 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 }); + } + + /// + 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"); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.Designer.cs new file mode 100644 index 00000000..a71f6854 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.Designer.cs @@ -0,0 +1,1028 @@ +// +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("20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables")] + partial class AddsMediaLibraryScanSnapshotsAndStagingTables + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("SkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LibraryScanEntityId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("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.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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.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") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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.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 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.cs b/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.cs new file mode 100644 index 00000000..eba43685 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260808141154_AddsMediaLibraryScanSnapshotsAndStagingTables.cs @@ -0,0 +1,210 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsMediaLibraryScanSnapshotsAndStagingTables : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + 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( + 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( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 8); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 10) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AddColumn( + name: "SkipUnchangedDirectoriesDuringScan", + table: "Libraries", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 8); + + migrationBuilder.CreateTable( + name: "DirectoryScanFingerprints", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 1024, nullable: false), + LastWriteTimeUtc = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(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(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 1024, nullable: false), + ContentHash = table.Column(type: "INTEGER", nullable: false), + FileSize = table.Column(type: "INTEGER", nullable: false), + Ticks = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true), + LibraryId = table.Column(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(type: "TEXT", nullable: false), + Path = table.Column(type: "TEXT", maxLength: 1024, nullable: false), + Size = table.Column(type: "INTEGER", nullable: false), + Ticks = table.Column(type: "INTEGER", nullable: false), + ContentHash = table.Column(type: "INTEGER", nullable: false), + PreviousContentHash = table.Column(type: "INTEGER", nullable: false), + NeedsRehash = table.Column(type: "INTEGER", nullable: false), + IsNew = table.Column(type: "INTEGER", nullable: false), + LibraryScanId = table.Column(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" }); + } + + /// + 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( + 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( + 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( + name: "CreatedOnUtc", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(DateTime), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 8) + .OldAnnotation("Relational:ColumnOrder", 9); + + migrationBuilder.AlterColumn( + name: "CreatedBy", + table: "Libraries", + type: "TEXT", + nullable: false, + oldClrType: typeof(Guid), + oldType: "TEXT") + .Annotation("Relational:ColumnOrder", 9) + .OldAnnotation("Relational:ColumnOrder", 10); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.Designer.cs new file mode 100644 index 00000000..fb03680c --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.Designer.cs @@ -0,0 +1,1019 @@ +// +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("20260808191805_RemovesLibraryScanResultsShadowForeignKey")] + partial class RemovesLibraryScanResultsShadowForeignKey + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMedatadaFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("SaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("SkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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.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") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + 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 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.cs b/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.cs new file mode 100644 index 00000000..2b3b9419 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260808191805_RemovesLibraryScanResultsShadowForeignKey.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class RemovesLibraryScanResultsShadowForeignKey : Migration + { + /// + 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"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + 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"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.Designer.cs new file mode 100644 index 00000000..3b1c3929 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.Designer.cs @@ -0,0 +1,1019 @@ +// +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("20260809190243_RenamesLibraryScanSettingsColumns")] + partial class RenamesLibraryScanSettingsColumns + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("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("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("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("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("DownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("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("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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.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") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("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", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + 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 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("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 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.cs b/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.cs new file mode 100644 index 00000000..a75a570b --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260809190243_RenamesLibraryScanSettingsColumns.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class RenamesLibraryScanSettingsColumns : Migration + { + /// + 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"); + } + + /// + 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"); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index fb025ff4..edeeb777 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -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("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("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("Id") @@ -252,13 +277,13 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("CreatedBy") .HasColumnType("TEXT") - .HasColumnOrder(9); + .HasColumnOrder(10); b.Property("CreatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(8); + .HasColumnOrder(9); - b.Property("DownloadMedatadaFromWeb") + b.Property("DownloadMetadataFromWeb") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") .HasDefaultValue(true) @@ -279,10 +304,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(2); - b.Property("SaveMetadataInMediaDirectories") + b.Property("ShouldSaveMetadataInMediaDirectories") .HasColumnType("INTEGER") .HasColumnOrder(7); + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + b.Property("Title") .IsRequired() .HasMaxLength(255) @@ -291,11 +320,11 @@ namespace Lumina.DataAccess.Common.Migrations b.Property("UpdatedBy") .HasColumnType("TEXT") - .HasColumnOrder(11); + .HasColumnOrder(12); b.Property("UpdatedOnUtc") .HasColumnType("TEXT") - .HasColumnOrder(10); + .HasColumnOrder(11); b.Property("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("LastModified") + b.Property("Status") + .IsRequired() + .HasMaxLength(10) .HasColumnType("TEXT") - .HasColumnOrder(4); + .HasColumnOrder(5); - b.Property("LibraryScanEntityId") - .HasColumnType("TEXT"); + b.Property("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("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("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("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("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("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 => diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs new file mode 100644 index 00000000..d4e67b16 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/DirectoryScanFingerprintRepository.cs @@ -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; + +/// +/// Repository for directory scan fingerprints. +/// +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; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext, used to derive the database connection string. + public DirectoryScanFingerprintRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets the directory scan fingerprints of a media library, mapped by the directory path. + /// + /// The unique identifier of the library for which to get the directory scan fingerprints. + /// Cancellation token that can be used to stop the execution. + /// An containing either a path mapped dictionary of directory scan fingerprints, or an error. + public async Task>> 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 fingerprints = await connection.QueryAsync(command).ConfigureAwait(false); + return fingerprints.ToDictionary(fingerprint => fingerprint.Path, StringComparer.Ordinal); + } + + /// + /// Inserts or updates the provided directory scan fingerprints in the storage medium. + /// + /// The directory scan fingerprints to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpsertRangeAsync(IReadOnlyCollection 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 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 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; + } + + /// + /// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking. + /// + /// The opened database connection. + private async Task OpenConnectionAsync(CancellationToken cancellationToken) + { + SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString); + await connection.OpenAsync(cancellationToken); + return connection; + } + + /// + /// Upserts a batch of directory scan fingerprints using a single multi-row UPSERT statement. + /// + /// The connection on which to execute the upsert. + /// The transaction in which the upsert is executed. + /// The batch of directory scan fingerprints to upsert. + /// Cancellation token that can be used to stop the execution. + private static async Task UpsertBatchAsync(SqliteConnection connection, DbTransaction transaction, IReadOnlyList 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); + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs index 1cd4d2cd..38b16f7e 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanResultRepository.cs @@ -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)); } - - /// - /// Gets all media library scan results that belong to the last scan of a library identified by , from the storage medium. - /// - /// The unique identifier of the library for which to get the results of the last scans. - /// Cancellation token that can be used to stop the execution. - /// An containing either a path mapped dictionary of , or an error. - public async Task>> 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); - } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs new file mode 100644 index 00000000..69efca97 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanSnapshotRepository.cs @@ -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; + +/// +/// Repository for media library scan snapshots. +/// +internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext, used to derive the database connection string. + public LibraryScanSnapshotRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// 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. + /// + /// The unique identifier of the library for which to get the deleted media library scan snapshot item paths. + /// The unique identifier of the media library scan for which to determine the deleted media library scan snapshot item paths. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of deleted media library scan snapshot item paths, or an error. + public async Task>> 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 deletedPaths = await connection.QueryAsync(command).ConfigureAwait(false); + return deletedPaths.ToList(); + } + + /// + /// 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. + /// + /// The unique identifier of the library for which to apply the scan results. + /// The unique identifier of the media library scan whose results are applied. + /// The unique identifier of the user that initiated the media library scan, used for audit purposes. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking. + /// + /// The opened database connection. + private async Task OpenConnectionAsync(CancellationToken cancellationToken) + { + SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString); + await connection.OpenAsync(cancellationToken); + return connection; + } +} diff --git a/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs new file mode 100644 index 00000000..5fec40e0 --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Libraries/LibraryScanStagingResultsRepository.cs @@ -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; + +/// +/// Repository for media library scan staging results. +/// +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; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext, used to derive the database connection string. + public LibraryScanStagingResultsRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Adds a range of media library scan staging results to the storage medium. + /// + /// The media library scan staging results to add. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> InsertRangeAsync(IReadOnlyCollection 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 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 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; + } + + /// + /// 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. + /// + /// The unique identifier of the media library scan whose staging results are marked. + /// The unique identifier of the library whose media library scan snapshot is compared against. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Gets the number of media library scan staging results of the current scan that need their content hashed. + /// + /// The unique identifier of the media library scan whose staging results are counted. + /// Cancellation token that can be used to stop the execution. + /// An containing either the number of staging results that need hashing, or an error. + public async Task> 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(command).ConfigureAwait(false); + } + + /// + /// Gets a page of the media library scan staging results that need their content hashed, ordered by path, using keyset pagination. + /// + /// The unique identifier of the media library scan whose staging results are retrieved. + /// The path of the last retrieved file system item, used for keyset pagination. Pass to get the first page. + /// The maximum number of staging results to retrieve. + /// Cancellation token that can be used to stop the execution. + /// An containing either a page of staging results that need hashing, or an error. + public async Task>> 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 page = await connection.QueryAsync(command).ConfigureAwait(false); + return page.ToList(); + } + + /// + /// Updates the content hashes of the provided media library scan staging results. + /// + /// The unique identifier of the media library scan whose staging results are updated. + /// The file system items whose content hashes are updated. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection 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; + } + + /// + /// Clears all the media library scan staging results of the provided media library scan from the storage medium. + /// + /// The unique identifier of the media library scan whose staging results are cleared. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> 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; + } + + /// + /// Opens a dedicated connection to the database, so that the raw SQL operations performed here do not interfere with the Entity Framework change tracking. + /// + /// The opened database connection. + private async Task OpenConnectionAsync(CancellationToken cancellationToken) + { + SqliteConnection connection = new(_luminaDbContext.Database.GetDbConnection().ConnectionString); + await connection.OpenAsync(cancellationToken); + return connection; + } + + /// + /// Inserts a batch of media library scan staging results using a single multi-row INSERT statement. + /// + /// The connection on which to execute the insert. + /// The transaction in which the insert is executed. + /// The batch of media library scan staging results to insert. + /// Cancellation token that can be used to stop the execution. + private static async Task InsertBatchAsync(SqliteConnection connection, DbTransaction transaction, IReadOnlyList 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); + } +} diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs index dd09ea4e..b127d245 100644 --- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs +++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs @@ -20,6 +20,9 @@ public class LuminaDbContext : DbContext public virtual DbSet Libraries { get; set; } = null!; public virtual DbSet LibraryScans { get; set; } = null!; public virtual DbSet LibraryScanResults { get; set; } = null!; + public virtual DbSet LibraryScanSnapshots { get; set; } = null!; + public virtual DbSet LibraryScanStagingResults { get; set; } = null!; + public virtual DbSet DirectoryScanFingerprints { get; set; } = null!; public virtual DbSet Roles { get; set; } = null!; public virtual DbSet UserRoles { get; set; } = null!; public virtual DbSet Permissions { get; set; } = null!; diff --git a/src/Lumina.DataAccess/Lumina.DataAccess.csproj b/src/Lumina.DataAccess/Lumina.DataAccess.csproj index 76a5e210..307d4162 100644 --- a/src/Lumina.DataAccess/Lumina.DataAccess.csproj +++ b/src/Lumina.DataAccess/Lumina.DataAccess.csproj @@ -18,6 +18,7 @@ + diff --git a/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanFileStatus.cs b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanFileStatus.cs new file mode 100644 index 00000000..8f739fc6 --- /dev/null +++ b/src/Lumina.Domain/Common/Enums/MediaLibrary/LibraryScanFileStatus.cs @@ -0,0 +1,22 @@ +namespace Lumina.Domain.Common.Enums.MediaLibrary; + +/// +/// Enumeration for the statuses of the files processed during a media library scan. +/// +public enum LibraryScanFileStatus +{ + /// + /// The file contents have been changed. + /// + Modified, + + /// + /// The file has been added. + /// + New, + + /// + /// The file has been deleted. + /// + Deleted +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 7fbfb7c5..4666f1fb 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -63,12 +63,18 @@ public class Library : AggregateRoot /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMedatadaFromWeb { get; private set; } = true; + public bool DownloadMetadataFromWeb { get; private set; } = true; /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. /// - public bool SaveMetadataInMediaDirectories { get; private set; } + public bool ShouldSaveMetadataInMediaDirectories { get; private set; } + + /// + /// 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. + /// + public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; } /// /// Gets the list of objects representing the file system paths that make up the media library. @@ -91,8 +97,9 @@ public class Library : AggregateRoot /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. - /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. private Library( LibraryId id, @@ -103,8 +110,9 @@ public class Library : AggregateRoot string? coverImage, bool isEnabled, bool isLocked, - bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories, + bool downloadMetadataFromWeb, + bool shouldSaveMetadataInMediaDirectories, + bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) : base(id) { UserId = userId; @@ -114,8 +122,9 @@ public class Library : AggregateRoot 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 /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. - /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. /// - /// An containing either a successfuly created , or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( UserId userId, @@ -143,8 +153,9 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories, + bool downloadMetadataFromWeb, + bool shouldSaveMetadataInMediaDirectories, + bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) { List tempContentLocations = []; @@ -165,8 +176,9 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMedatadaFromWeb, - saveMetadataInMediaDirectories, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, scanIds ); } @@ -182,11 +194,12 @@ public class Library : AggregateRoot /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. - /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. + /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. /// - /// An containing either a successfuly created , or an error message. + /// An containing either a successfully created , or an error message. /// public static ErrorOr Create( LibraryId id, @@ -197,8 +210,9 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMedatadaFromWeb, - bool saveMetadataInMediaDirectories, + bool downloadMetadataFromWeb, + bool shouldSaveMetadataInMediaDirectories, + bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) { List tempContentLocations = []; @@ -219,8 +233,9 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMedatadaFromWeb, - saveMetadataInMediaDirectories, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, scanIds ); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs new file mode 100644 index 00000000..402da8d1 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEvent.cs @@ -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; + +/// +/// 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. +/// +/// The unique identifier of the domain event. +/// The unique identifier of the library to which the deleted media library item belonged. +/// Model for tracking media library scans. +/// The path of the media library item that was deleted. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Id}; Path: {Path}")] +public record LibraryMediaItemDeletedDomainEvent( + Guid Id, + LibraryId LibraryId, + MediaLibraryScanCompositeId MediaLibraryScanCompositeId, + string Path, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs index 9e4d143b..103ce5f8 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEvent.cs @@ -15,10 +15,12 @@ namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Lib /// The unique identifier of the library whose scan has failed. /// Model for tracking media library scans. /// The date and time when the domain event occurred. +/// The optional descriptive message of the failure, used for diagnostic purposes. [DebuggerDisplay("Id: {Id}")] public record LibraryScanFailedDomainEvent( Guid Id, LibraryId LibraryId, MediaLibraryScanCompositeId MediaLibraryScanCompositeId, - DateTime OccurredOnUtc + DateTime OccurredOnUtc, + string? ErrorMessage = null ) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs new file mode 100644 index 00000000..638c6827 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/IScanJobRegistry.cs @@ -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; + +/// +/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph. +/// +public interface IScanJobRegistry +{ + /// + /// Gets the media library scan jobs registered for the provided . + /// + /// The name of the hook point at which the media library scan jobs were injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The collection of media library scan jobs registered at the provided hook point. + IEnumerable GetJobsForHook(string hookName, LibraryId libraryId); +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs new file mode 100644 index 00000000..7dc27477 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Hooks/ScanJobHooks.cs @@ -0,0 +1,32 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Hooks; + +/// +/// Defines the named junction points of the media library scan job graph where plugin jobs can be injected. +/// +public static class ScanJobHooks +{ + /// + /// The hook that runs after the file system discovery job, and before the scan diff job. + /// + public const string AFTER_FILE_SYSTEM_DISCOVERY = "AfterFileSystemDiscovery"; + + /// + /// The hook that runs after the scan diff job, and before the scan hash job. + /// + public const string AFTER_SCAN_DIFF = "AfterScanDiff"; + + /// + /// The hook that runs after the scan hash job, and before any metadata enrichment jobs. + /// + public const string BEFORE_METADATA_ENRICHMENT = "BeforeMetadataEnrichment"; + + /// + /// The hook that runs after any metadata enrichment jobs, and before the scan results save job. + /// + public const string AFTER_METADATA_ENRICHMENT = "AfterMetadataEnrichment"; + + /// + /// The hook that runs before the scan results save job, which should always be the last job in the directed acyclic job graph. + /// + public const string BEFORE_SCAN_RESULTS_SAVE = "BeforeScanResultsSave"; +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs deleted file mode 100644 index a0cc2b9c..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IFileSystemDiscoveryJob.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for discovering file system items. -/// -public interface IFileSystemDiscoveryJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs deleted file mode 100644 index 43c11e1b..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IHashComparerJob.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for comparing hashes. -/// -public interface IHashComparerJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs new file mode 100644 index 00000000..8586c427 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanDiffJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// 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. +/// +public interface IMediaLibraryScanDiffJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs new file mode 100644 index 00000000..6cd58978 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanHashJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for computing the content hashes of the files that changed since the previous scan. +/// +public interface IMediaLibraryScanHashJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs new file mode 100644 index 00000000..0eea3233 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IMediaLibraryScanResultsSaveJob.cs @@ -0,0 +1,8 @@ +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// 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. +/// +public interface IMediaLibraryScanResultsSaveJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs deleted file mode 100644 index e07b0c3c..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataDiscoveryJob.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// Interface for the media library scan job for retrieving persistence data from any eventual previous scans. -/// -public interface IRepositoryMetadataDiscoveryJob : IMediaLibraryScanJob -{ - -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs deleted file mode 100644 index f9f8228e..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/IRepositoryMetadataSaveJob.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; - -/// -/// 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. -/// -public interface IRepositoryMetadataSaveJob : IMediaLibraryScanJob -{ - -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs deleted file mode 100644 index 46daf71b..00000000 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileExtensionsFilterJob.cs +++ /dev/null @@ -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; - -/// -/// Interface for the media library scan job for filtering only files that have known book formats extensions. -/// -public interface IBooksFileExtensionsFilterJob : IMediaLibraryScanJob -{ -} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..75a3f6f5 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Jobs/IBooksFileSystemDiscoveryJob.cs @@ -0,0 +1,10 @@ +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +namespace Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; + +/// +/// Interface for the media library scan job for discovering books file system items. +/// +public interface IBooksFileSystemDiscoveryJob : IMediaLibraryScanJob +{ +} diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index d9faa1d5..5c02cdce 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -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; - /// + /// + /// The media library type that this media library scanner supports. + /// public LibraryType SupportedType { get; } = LibraryType.Book; /// /// Initializes a new instance of the class. /// /// Injected factory for creating media library scan jobs. - public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory) + /// Injected registry of the media library scan jobs injected by plugins at the defined hook points. + public BookLibraryTypeScanner(IMediaLibraryScanJobFactory mediaScanJobFactory, IScanJobRegistry scanJobRegistry) { _mediaScanJobFactory = mediaScanJobFactory; + _scanJobRegistry = scanJobRegistry; } - /// - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMedatadaFromWeb) + /// + /// Creates the media library scan jobs for the provided media library. + /// + /// The unique identifier of the media library for which to create the media library scan jobs. + /// Whether the library permits downloading data from the web, or not. + /// A collection of media library scan jobs. + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb) { // declare the list of jobs that this scanner requires - IFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); - IRepositoryMetadataDiscoveryJob repositoryMetadataDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); - IBooksFileExtensionsFilterJob booksFileExtensionsFilterJob = _mediaScanJobFactory.CreateJob(libraryId); - IHashComparerJob hashComparerJob = _mediaScanJobFactory.CreateJob(libraryId); + IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanDiffJob mediaLibraryScanDiffJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanHashJob mediaLibraryScanHashJob = _mediaScanJobFactory.CreateJob(libraryId); IGoodReadsMetadataScrapJob goodReadsMetadataScrapJob = _mediaScanJobFactory.CreateJob(libraryId); - IRepositoryMetadataSaveJob repositoryMetadataSaveJob = _mediaScanJobFactory.CreateJob(libraryId); + IMediaLibraryScanResultsSaveJob mediaLibraryScanResultsSaveJob = _mediaScanJobFactory.CreateJob(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; + } + + /// + /// Splices the plugin jobs registered at the provided after the , and returns the last job of the extended chain. + /// + /// The job after which the plugin jobs are spliced. + /// The name of the hook point at which the plugin jobs are injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The last job of the extended chain, which can be used as the parent for the next job. + 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; } } diff --git a/src/Lumina.Domain/Lumina.Domain.csproj b/src/Lumina.Domain/Lumina.Domain.csproj index 3df233dd..63bdd3b1 100644 --- a/src/Lumina.Domain/Lumina.Domain.csproj +++ b/src/Lumina.Domain/Lumina.Domain.csproj @@ -18,7 +18,6 @@ - diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 3866c9b1..078aa845 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -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(); services.AddSingleton(); services.AddHostedService(); + services.AddSingleton(serviceProvider => new ScanJobRegistry(serviceProvider, new Dictionary>())); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddSingleton(); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs deleted file mode 100644 index c8fb72a7..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/FileSystemDiscoveryJob.cs +++ /dev/null @@ -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; - -/// -/// Media library scan job for discovering file system items. -/// -internal sealed class FileSystemDiscoveryJob : MediaLibraryScanJob, IFileSystemDiscoveryJob -{ - private readonly IServiceScopeFactory _serviceScopeFactory; - - /// - /// Initializes a new instance of the class. - /// - /// - /// 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. - /// - public FileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(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()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr 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 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 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 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; - } - } - - /// - /// Gets all files under the specified directory. - /// - /// The path of the root directory from which to start collecting files. - /// Specifies whether hidden files and directories should be included. - /// Cancellation token that can be used to stop the execution. - /// - /// See docs/technical/achitecture/architecture-knowledge-management/architecture-decision-log/architecture-decission-record-0003.md for details. - /// - /// The discovered collection of files. - [MethodImpl(MethodImplOptions.AggressiveOptimization)] - private static IEnumerable GetFiles(string rootDirectoryPath, bool includeHiddenElements, CancellationToken cancellationToken) - { - Queue 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? 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? 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); - } - } - } - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr 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; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs deleted file mode 100644 index 43478ace..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/HashComparerJob.cs +++ /dev/null @@ -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; - -/// -/// Media library scan job for comparing hashes. -/// -internal sealed class HashComparerJob : MediaLibraryScanJob, IHashComparerJob -{ - private readonly IServiceScopeFactory _serviceScopeFactory; - private Dictionary libraryScanResultEntities = []; - private List files = []; - - /// - /// Initializes a new instance of the class. - /// - /// - /// 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. - /// - public HashComparerJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(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 libraryScanResultsPayload) - libraryScanResultEntities = libraryScanResultsPayload; - else if (input is List 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()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - IFileService fileService = asyncServiceScope.ServiceProvider.GetService()!; - IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr 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 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 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 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 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; - } - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr 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; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs similarity index 57% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs index 6ccb3243..e788d7b1 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataDiscoveryJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJob.cs @@ -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; /// -/// 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. /// -internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRepositoryMetadataDiscoveryJob +internal sealed class MediaLibraryScanDiffJob : MediaLibraryScanJob, IMediaLibraryScanDiffJob { private readonly IServiceScopeFactory _serviceScopeFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// - /// 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. /// - public RepositoryMetadataDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + public MediaLibraryScanDiffJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(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()!; IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); - ILibraryScanResultRepository libraryScanResultRepository = unitOfWork.GetRepository(); + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the library from the repository - ErrorOr 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 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 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> 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 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); + } } /// @@ -129,12 +111,9 @@ internal sealed class RepositoryMetadataDiscoveryJob : MediaLibraryScanJob, IRep /// An representing either a successful operation, or an error. private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) { - ErrorOr scanJobProgressResult = MediaLibraryScanJobProgress.Create(currentProgress, totalProgress, "RetrievingPastScanData"); + ErrorOr 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); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs new file mode 100644 index 00000000..9eb65c5d --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJob.cs @@ -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; + +/// +/// Media library scan job for computing the content hashes of the files that changed since the previous scan. +/// +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; + + /// + /// Initializes a new instance of the class. + /// + /// + /// 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. + /// + public MediaLibraryScanHashJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + IFileHashService fileHashService = asyncServiceScope.ServiceProvider.GetService()!; + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // count the files that need hashing, for progress reporting purposes + ErrorOr 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 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> getFilesToHashPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, HASHING_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getFilesToHashPageResult.IsError) + throw new InvalidOperationException(getFilesToHashPageResult.FirstError.Description); + IReadOnlyList 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 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 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); + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr 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; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs similarity index 52% rename from src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs rename to src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs index 36a47324..675d269d 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/RepositoryMetadataSaveJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJob.cs @@ -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; /// -/// 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. /// -internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IRepositoryMetadataSaveJob +internal sealed class MediaLibraryScanResultsSaveJob : MediaLibraryScanJob, IMediaLibraryScanResultsSaveJob { private readonly IServiceScopeFactory _serviceScopeFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// - /// 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. /// - public RepositoryMetadataSaveJob(IServiceScopeFactory serviceScopeFactory) + public MediaLibraryScanResultsSaveJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(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()!; IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); + ILibraryScanSnapshotRepository libraryScanSnapshotRepository = unitOfWork.GetRepository(); + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the library from the repository - ErrorOr 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 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 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 publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, 1, cancellationToken).ConfigureAwait(false); if (publishJobProgressResult.IsError) - return; + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - List 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> 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 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); + } } /// @@ -123,13 +123,9 @@ internal sealed class RepositoryMetadataSaveJob : MediaLibraryScanJob, IReposito { ErrorOr 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; } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs new file mode 100644 index 00000000..2ec45bda --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisher.cs @@ -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; + +/// +/// Helper for publishing the media library scan failure domain event, from within a media library scan job. +/// +internal static class ScanFailurePublisher +{ + /// + /// Publishes the media library scan failure domain event for the scan that the job is part of. + /// + /// Injected factory for creating scopes in which the publisher is resolved. + /// The unique identifier of the library whose scan has failed. + /// Model for tracking media library scans. + /// The exception that caused the failure. + /// Cancellation token that can be used to stop the execution. + 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()!; + 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 + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs new file mode 100644 index 00000000..1f77daf0 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/ScanJobRegistry.cs @@ -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; + +/// +/// Registry of the media library scan jobs that are injected by plugins at the defined hook points of the media library scan job graph. +/// +internal sealed class ScanJobRegistry : IScanJobRegistry +{ + private readonly IServiceProvider _serviceProvider; + private readonly IReadOnlyDictionary> _jobsByHook; + + /// + /// Initializes a new instance of the class. + /// + /// The service provider, used to resolve the registered plugin jobs. + /// The media library scan job types registered for each hook point, provided by the composition root of the plugin system. + public ScanJobRegistry(IServiceProvider serviceProvider, IReadOnlyDictionary> jobsByHook) + { + _serviceProvider = serviceProvider; + _jobsByHook = jobsByHook; + } + + /// + /// Gets the media library scan jobs registered for the provided . + /// + /// The name of the hook point at which the media library scan jobs were injected. + /// The unique identifier of the media library upon which the scan is performed. + /// The collection of media library scan jobs registered at the provided hook point. + public IEnumerable 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? jobTypes)) + yield break; + + foreach (Type jobType in jobTypes) + { + IMediaLibraryScanJob pluginJob = (IMediaLibraryScanJob)_serviceProvider.GetRequiredService(jobType); + pluginJob.LibraryId = libraryId; + yield return pluginJob; + } + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs deleted file mode 100644 index ffdd71c4..00000000 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileExtensionsFilterJob.cs +++ /dev/null @@ -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; - -/// -/// Media library scan job for filtering only files that have known book formats extensions. -/// -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" - ]; - - /// - /// Initializes a new instance of the class. - /// - /// - /// 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. - /// - public BooksFileExtensionsFilterJob(IServiceScopeFactory serviceScopeFactory) - { - _serviceScopeFactory = serviceScopeFactory; - } - - /// - public override async Task ExecuteAsync(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 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()!; - IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; - ILibraryRepository libraryRepository = unitOfWork.GetRepository(); - IPathService pathService = asyncServiceScope.ServiceProvider.GetService()!; - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr 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 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 publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, payload.Count, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsError) - return; - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - - List 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; - } - } - - /// - /// Checks if has a known book file extension or not. - /// - /// The file path to be checked. - /// if contains a known book file extension, otherwise. - public bool HasKnownBookExtension(ReadOnlySpan 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 extension = filePath[lastDotIndex..]; - - // check against each known extension - foreach (string knownExt in _knownBookFileExtensions) - if (extension.SequenceEqual(knownExt.AsSpan())) - return true; - - return false; - } - - /// - /// Publishes a job progress update. - /// - /// The service used to publish the progress update. - /// The composite unique identifier of a media library scan. - /// The current job progress. - /// The total job progress. - /// Cancellation token that can be used to stop the execution. - /// An representing either a successful operation, or an error. - private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) - { - ErrorOr 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; - } -} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs new file mode 100644 index 00000000..549d94f9 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJob.cs @@ -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; + +/// +/// Media library scan job for discovering book file system items. +/// +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 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; + + /// + /// Initializes a new instance of the class. + /// + /// + /// 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. + /// + public BooksFileSystemDiscoveryJob(IServiceScopeFactory serviceScopeFactory) + { + _serviceScopeFactory = serviceScopeFactory; + } + + /// + public override async Task ExecuteAsync(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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryRepository libraryRepository = unitOfWork.GetRepository()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); + IDirectoryScanFingerprintRepository directoryScanFingerprintRepository = unitOfWork.GetRepository(); + + MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); + + // get the library from the repository + ErrorOr 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 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? fingerprintsByPath = null; + if (domainLibraryResult.Value.ShouldSkipUnchangedDirectoriesDuringScan) + { + ErrorOr> 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 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 stagingBatch = []; + List 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 insertResult = await stagingResultsRepository.InsertRangeAsync(stagingBatch, cancellationToken).ConfigureAwait(false); + if (insertResult.IsError) + throw new InvalidOperationException(insertResult.FirstError.Description); + } + if (fingerprintBatch.Count > 0) + { + ErrorOr 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); + } + } + + /// + /// 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. + /// + /// The path of the root directory from which to start collecting files. + /// Whether to skip the directories whose last write time has not changed since the last scan, or not. + /// The directory scan fingerprints of the library, mapped by the directory path. Can be when the fast skip is disabled. + /// The batch of discovered files that is written to the staging results when it reaches the batch size. + /// The batch of directory scan fingerprints that is written to the storage medium when it reaches the batch size. + /// The repository used to write the discovered files to the staging results. + /// The repository used to write the directory scan fingerprints to the storage medium. + /// Cancellation token that can be used to stop the execution. + /// + /// See docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0003.md for details. + /// + [MethodImpl(MethodImplOptions.AggressiveOptimization)] + private async Task DiscoverContentLocationAsync( + string rootDirectoryPath, + bool skipUnchangedDirectories, + Dictionary? fingerprintsByPath, + List stagingBatch, + List fingerprintBatch, + ILibraryScanStagingResultsRepository stagingResultsRepository, + IDirectoryScanFingerprintRepository directoryScanFingerprintRepository, + CancellationToken cancellationToken) + { + Queue 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 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? 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 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? 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); + } + } + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr 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; + } +} diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs index c9999f84..f0e2c15d 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/GoodReadsMetadataScrapJob.cs @@ -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 /// 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; /// /// Initializes a new instance of the class. /// /// - /// 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. /// public GoodReadsMetadataScrapJob(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } - /// + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter representing the data to be processed by this payload. + /// The unique identifier of the media library scan job. + /// The input data to be processed by this payload. + /// Cancellation token that can be used to stop the execution. public override async Task ExecuteAsync(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(); - IPublisher? publisher = asyncServiceScope.ServiceProvider.GetService(); - ILibraryRepository libraryRepository = unitOfWork!.GetRepository(); - MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - - // get the library from the repository - ErrorOr 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()!; + IPublisher publisher = asyncServiceScope.ServiceProvider.GetService()!; + ILibraryScanStagingResultsRepository stagingResultsRepository = unitOfWork.GetRepository(); - // convert it to a domain object - ErrorOr 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 scanJobProgressResult = MediaLibraryScanJobProgress.Create(0, 20, "GoodReadsMetadataDownload"); - //ErrorOr 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 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 publishJobProgressResult = await PublishJobProgress(publisher, compositeKey, 0, totalItemsToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsError) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - List 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> getItemsToEnrichPageResult = await stagingResultsRepository.GetFilesToHashPageAsync(ScanId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getItemsToEnrichPageResult.IsError) + throw new InvalidOperationException(getItemsToEnrichPageResult.FirstError.Description); + IReadOnlyList 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); + } + } + + /// + /// Publishes a job progress update. + /// + /// The service used to publish the progress update. + /// The composite unique identifier of a media library scan. + /// The current job progress. + /// The total job progress. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> PublishJobProgress(IPublisher publisher, MediaLibraryScanCompositeId compositeKey, int currentProgress, int totalProgress, CancellationToken cancellationToken) + { + ErrorOr 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; } } diff --git a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs index e8f9d53f..757e40e1 100644 --- a/src/Lumina.Infrastructure/Core/Security/FileHashService.cs +++ b/src/Lumina.Infrastructure/Core/Security/FileHashService.cs @@ -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 _threadLocalBuffer = new(() => new byte[DEFAULT_BUFFER_SIZE]); // thread-local buffer to minimize memory allocations during parallel processing - private static readonly ObjectPool s_hasherPool = new DefaultObjectPool(new DefaultPooledObjectPolicy()); // object pool for reusing hashers, to reduce GC pressure + private static readonly ThreadLocal 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(); /// - /// Hashes by sampling chunks from them. + /// Hashes by sampling chunks from them. /// - /// The collection of files to hash. - /// Lookup dictionary of a previous media library scan, used to determine if a file changed or not. + /// The collection of files to hash. /// Callback to invoke during processing of elements. /// Cancellation token that can be used to stop the execution. - /// A collection of files that changed since last library scan, along with their hashes. - public async Task> HashFilesAsync( - List files, - Dictionary previousScanResults, - Func callback, - CancellationToken cancellationToken) + /// A collection of the hashed files, along with their hashes. + public async Task> HashFilesAsync(IReadOnlyCollection inputFiles, Func callback, CancellationToken cancellationToken) { - List changedFiles = []; + List 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; } /// /// Computes content hash using memory-mapped sampling. /// + /// The path of the file to hash. + /// The size of the file, in bytes. /// Sample window size (automatically clamped to file size). - /// Reusable read buffer (thread-local allocation optimized). - 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 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; } + + /// + /// Computes the hash for an empty file, which is a special case, since it has no content to sample. + /// + /// The hash value for an empty file. + private static ulong ComputeEmptyHash() + { + XxHash64 hasher = new(); + Span hashSpan = stackalloc byte[sizeof(ulong)]; + hasher.TryGetCurrentHash(hashSpan, out _); + return BitConverter.ToUInt64(hashSpan); + } } diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 6145e0ae..8343e8e2 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -13,7 +13,7 @@ "MinimumLevel": { "Default": "Information", "Override": { - "Microsoft.EntityFrameworkCore.Database.Command": "Debug" + "Microsoft.EntityFrameworkCore.Database.Command": "Warning" } }, "Enrich": [ diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index 72cc4a77..e2c70d12 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -34,8 +34,9 @@ public class AddLibraryEndpointSummary : Summary r.Title, "The title of the media library. Required."); @@ -44,8 +45,9 @@ public class AddLibraryEndpointSummary : Summary 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(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -55,12 +57,13 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); - ResponseParam(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(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(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(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(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); - ResponseParam(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(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(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(r => r.UpdatedOnUtc, "The date and time when the entity was last updated."); @@ -52,8 +53,9 @@ public class GetLibraryEndpointSummary : Summary r.Id, "The unique identifier of the media library. Required."); @@ -48,8 +49,9 @@ public class UpdateLibraryEndpointSummary : Summary 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(r => r.Id, "The unique identifier of the entity."); ResponseParam(r => r.UserId, "The unique identifier of the user owning the media library."); @@ -59,12 +61,13 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMedatadaFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); - ResponseParam(r => r.SaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); + ResponseParam(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(r => r.CreatedOnUtc, "The date and time when the entity was created."); ResponseParam(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(); 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) { diff --git a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs index acc8e28a..e52dfb97 100644 --- a/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs +++ b/src/Lumina.Presentation.Web/Common/Models/Libraries/LibraryModel.cs @@ -56,10 +56,16 @@ public class LibraryModel /// /// Gets or sets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMedatadaFromWeb { get; set; } = true; + public bool DownloadMetadataFromWeb { get; set; } = true; /// /// Gets or sets whether this media library should copy the downloaded metadata into the media library content locations, or not. /// - public bool SaveMetadataInMediaDirectories { get; set; } = false; + public bool ShouldSaveMetadataInMediaDirectories { get; set; } = false; + + /// + /// 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. + /// + public bool ShouldSkipUnchangedDirectoriesDuringScan { get; set; } = false; } diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index 2e72d534..e884d370 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -95,6 +95,7 @@ public class LibraryManagementController : Controller [RequirePermission(AuthorizationPermission.CanCreateLibraries)] public async Task 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($"libraries/{data.Id}", data, cancellationToken).ConfigureAwait(false) diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx index ce6e8e39..167b3211 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.de-DE.resx @@ -186,12 +186,12 @@ Filmreihe - - Buchdateien werden gefiltert... - Metadaten werden von GoodReads heruntergeladen... + + Berechne die Datei-Hashes... + Grafischer Roman @@ -252,9 +252,6 @@ Entfernen - - Vergangene Scan-Daten werden abgerufen... - Scandaten werden gespeichert... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx index 3903ded1..a04e2a83 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.en-US.resx @@ -186,12 +186,12 @@ Film Series - - Filtering book files... - Downloading metadata from GoodReads... + + Hashing file contents... + Graphic Novel @@ -252,9 +252,6 @@ Remove - - Retrieving past scan data... - Saving scan data... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx index 634313d9..ca26806a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.es-ES.resx @@ -186,12 +186,12 @@ Saga Cinematográfica - - Filtrando archivos de libros... - Descargando metadatos de GoodReads... + + Calculando los hashes de los archivos... + Novela Gráfica @@ -252,9 +252,6 @@ Eliminar - - Recuperando datos de escaneos anteriores... - Guardando datos del escaneo... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx index 9c14201c..217d4007 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.fr-FR.resx @@ -186,12 +186,12 @@ Saga Cinématographique - - Filtrage des fichiers de livres... - Téléchargement des métadonnées depuis GoodReads... + + Calcul des hachages des fichiers... + Roman Graphique @@ -252,9 +252,6 @@ Supprimer - - Récupération des données de scan précédentes... - Sauvegarde des données de scan en cours... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx index 9958003b..f44f35d0 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.it-IT.resx @@ -186,12 +186,12 @@ Saga Cinematografica - - Filtraggio dei file di libri... - Scaricamento dei metadati da GoodReads... + + Calcolo degli hash dei file... + Romanzo Grafico @@ -252,9 +252,6 @@ Rimuovere - - Recupero dei dati di scansione precedenti... - Salvataggio dei dati di scansione... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx index 966d7ae2..525c1e48 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ja-JP.resx @@ -186,12 +186,12 @@ 映画シリーズ - - 書籍ファイルをフィルタリング中... - GoodReadsからメタデータをダウンロード中... + + ファイルのハッシュを計算中... + グラフィックノベル @@ -252,9 +252,6 @@ 削除 - - 過去のスキャンデータを取得中... - スキャンデータを保存中... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx index 3903ded1..a04e2a83 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.resx @@ -186,12 +186,12 @@ Film Series - - Filtering book files... - Downloading metadata from GoodReads... + + Hashing file contents... + Graphic Novel @@ -252,9 +252,6 @@ Remove - - Retrieving past scan data... - Saving scan data... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx index e22f1e82..17941f34 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ro-RO.resx @@ -186,12 +186,12 @@ Serie de Filme - - Se filtrează fișierele de tip carte... - Se descarcă metadate de pe GoodReads... + + Se calculează hash-urile fișierelor... + Roman Grafic @@ -252,9 +252,6 @@ Șterge - - Se preiau datele de scanare anterioare... - Se salvează datele de scanare... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx index 8e6340a9..c6fde0d8 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.ru-RU.resx @@ -186,12 +186,12 @@ Киносерия - - Фильтрация файлов книг... - Загрузка метаданных из GoodReads... + + Вычисление хешей файлов... + Графический Роман @@ -252,9 +252,6 @@ Удалить - - Получение данных прошлых сканирований... - Сохранение данных сканирования... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx index 4f22d893..b19516a5 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Index.zh-CN.resx @@ -186,12 +186,12 @@ 电影系列 - - 正在过滤书籍文件... - 正在从GoodReads下载元数据... + + 正在计算文件哈希... + 图像小说 @@ -252,9 +252,6 @@ 删除 - - 正在检索过去的扫描数据... - 正在保存扫描数据... diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs index 891a627c..63eaff32 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.Designer.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 @@ -261,9 +261,9 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { /// /// Looks up a localized string similar to Whether to save a copy of the downloaded metadata in the media library content locations directories, or not. This only has an effect if downloading metadata from the web is active.. /// - public static string DescriptionSaveMetadataInMediaDirectories { + public static string DescriptionShouldSaveMetadataInMediaDirectories { get { - return ResourceManager.GetString("DescriptionSaveMetadataInMediaDirectories", resourceCulture); + return ResourceManager.GetString("DescriptionShouldSaveMetadataInMediaDirectories", resourceCulture); } } @@ -531,9 +531,9 @@ namespace Lumina.Presentation.Web.Resources.Views.Library.Management { /// /// Looks up a localized string similar to Save Metadata In Media Directories. /// - public static string SaveMetadataInMediaDirectories { + public static string ShouldSaveMetadataInMediaDirectories { get { - return ResourceManager.GetString("SaveMetadataInMediaDirectories", resourceCulture); + return ResourceManager.GetString("ShouldSaveMetadataInMediaDirectories", resourceCulture); } } diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx index e630247e..37fe1da0 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.de-DE.resx @@ -183,9 +183,12 @@ Ob diese Medienbibliothek gesperrt ist oder nicht. Eine gesperrte Bibliothek wird den Benutzern angezeigt, wird aber nie gescannt, aktualisiert, verändert, usw. - + Ob eine Kopie der heruntergeladenen Metadaten in den Verzeichnissen der Medienbibliothek gespeichert werden soll oder nicht. Dies hat nur eine Auswirkung, wenn das Herunterladen von Metadaten aus dem Web aktiv ist. + + Wenn diese Option aktiviert ist, verwendet sie Verzeichnismetadaten, um Verzeichnisse zu überspringen, die sich seit dem letzten Scan nicht geändert haben. Dies kann die Scans _erheblich_ beschleunigen, aber beachten Sie, dass sich die Metadaten von Verzeichnissen _nicht_ ändern/aktualisieren, wenn vorhandene Dateien bearbeitet werden, sondern nur, wenn neue Dateien hinzugefügt oder vorhandene gelöscht werden. Aktivieren Sie diese Option nur, wenn Sie keine vorhandenen Dateien ändern. + Eine Bezeichnung für diese Bibliothek @@ -273,9 +276,12 @@ Speichern - + Metadaten In Medienverzeichnissen Speichern + + Unveränderte Ordner Beim Scannen Überspringen + Drehbuch diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx index ea47cf88..97df4b4a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.en-US.resx @@ -183,9 +183,12 @@ Whether this media library is locked or not. A locked library is displayed to the users, but it is never scanned, updated, modified, etc. - + Whether to save a copy of the downloaded metadata in the media library content locations directories, or not. This only has an effect if downloading metadata from the web is active. + + When enabled, this option uses directory metadata to skip directories that have not changed since the last scan. This can _significantly_ speed up scans, but be aware that directories metadata _does not_ change/update when editing existing files, it does so only when adding new files or deleting existing ones. Only enable this if you don't modify existing files. + A name to identify this library @@ -273,9 +276,12 @@ Save - + Save Metadata In Media Directories + + Skip Unchanged Directories During Scan + Screenplay diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx index 5d3732d1..fcc0e3d4 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.es-ES.resx @@ -183,9 +183,12 @@ Si esta biblioteca multimedia está bloqueada o no. Una biblioteca bloqueada se muestra a los usuarios, pero nunca se escanea, actualiza, modifica, etc. - + Si guardar o no una copia de los metadatos descargados en los directorios de contenido de la biblioteca multimedia. Esto solo tiene efecto si la descarga de metadatos desde la web está activa. + + Cuando esta opción está habilitada, utiliza los metadatos de los directorios para omitir los directorios que no han cambiado desde el último escaneo. Esto puede acelerar _significativamente_ los escaneos, pero tenga en cuenta que los metadatos de los directorios _no_ cambian/actualizan al editar archivos existentes, solo lo hacen al agregar archivos nuevos o eliminar archivos existentes. Habilite esta opción solo si no modifica archivos existentes. + Un nombre para identificar esta biblioteca @@ -273,9 +276,12 @@ Guardar - + Guardar Metadatos En Los Directorios Multimedia + + Omitir Carpetas Sin Cambios Durante El Escaneo + Guión diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx index 702920cb..7bfb65fc 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.fr-FR.resx @@ -183,9 +183,12 @@ Si cette médiathèque est verrouillée ou non. Une bibliothèque verrouillée est affichée aux utilisateurs, mais n'est jamais analysée, mise à jour, modifiée, etc. - + Si une copie des métadonnées téléchargées doit être sauvegardée dans les répertoires de contenu de la médiathèque ou non. Ceci n'a d'effet que si le téléchargement des métadonnées depuis le web est actif. + + Lorsque cette option est activée, elle utilise les métadonnées des dossiers pour ignorer les dossiers qui n'ont pas changé depuis la dernière analyse. Cela peut accélérer _considérablement_ les analyses, mais sachez que les métadonnées des dossiers _ne_ changent/mettent _pas_ à jour lors de la modification de fichiers existants, seulement lors de l'ajout de nouveaux fichiers ou de la suppression de fichiers existants. N'activez cette option que si vous ne modifiez pas les fichiers existants. + Un nom pour identifier cette bibliothèque @@ -273,9 +276,12 @@ Enregistrer - + Sauvegarder Les Métadonnées Dans Les Répertoires Média + + Ignorer Les Dossiers Inchangés Lors De L'Analyse + Scénario diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx index d0b07797..5274edc2 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.it-IT.resx @@ -183,9 +183,12 @@ Se questa libreria multimediale è bloccata o meno. Una libreria bloccata viene mostrata agli utenti, ma non viene mai scansionata, aggiornata, modificata, ecc. - + Se salvare o meno una copia dei metadati scaricati nelle directory dei contenuti della libreria multimediale. Questo ha effetto solo se il download dei metadati dal web è attivo. + + Quando questa opzione è abilitata, utilizza i metadati delle cartelle per saltare le cartelle che non sono cambiate dall'ultima scansione. Questo può accelerare _significativamente_ le scansioni, ma tieni presente che i metadati delle cartelle _non_ cambiano/aggiornano quando si modificano file esistenti, lo fanno solo quando si aggiungono nuovi file o si eliminano file esistenti. Abilita questa opzione solo se non modifichi i file esistenti. + Un nome per identificare questa biblioteca @@ -273,9 +276,12 @@ Salva - + Salvare I Metadati Nelle Directory Multimediali + + Salta Cartelle Invariate Durante La Scansione + Sceneggiatura diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx index 791fd9d6..bbfa5064 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ja-JP.resx @@ -183,9 +183,12 @@ このメディアライブラリがロックされているかどうか。ロックされたライブラリはユーザーに表示されますが、スキャン、更新、変更などは一切されません。 - + ダウンロードしたメタデータのコピーをメディアライブラリのコンテンツディレクトリに保存するかどうか。これはウェブからのメタデータのダウンロードが有効な場合のみ効果があります。 + + このオプションを有効にすると、ディレクトリのメタデータを使用して、前回のスキャン以降に変更されていないディレクトリをスキップします。これによりスキャンを_大幅に_高速化できますが、既存のファイルを編集してもディレクトリのメタデータは_変更/更新されない_ことに注意してください。変更されるのは、新しいファイルを追加したときや既存のファイルを削除したときだけです。既存のファイルを変更しない場合にのみ有効にしてください。 + この図書館を識別するための名称 @@ -273,9 +276,12 @@ 保存 - + メディアディレクトリにメタデータを保存 + + スキャン中に変更のないフォルダをスキップ + 脚本 diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx index ea47cf88..97df4b4a 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.resx @@ -183,9 +183,12 @@ Whether this media library is locked or not. A locked library is displayed to the users, but it is never scanned, updated, modified, etc. - + Whether to save a copy of the downloaded metadata in the media library content locations directories, or not. This only has an effect if downloading metadata from the web is active. + + When enabled, this option uses directory metadata to skip directories that have not changed since the last scan. This can _significantly_ speed up scans, but be aware that directories metadata _does not_ change/update when editing existing files, it does so only when adding new files or deleting existing ones. Only enable this if you don't modify existing files. + A name to identify this library @@ -273,9 +276,12 @@ Save - + Save Metadata In Media Directories + + Skip Unchanged Directories During Scan + Screenplay diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx index 251ebb68..766e12aa 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ro-RO.resx @@ -183,9 +183,12 @@ Dacă această bibliotecă media este blocată sau nu. O bibliotecă blocată este afișată utilizatorilor, dar nu este niciodată scanată, actualizată, modificată, etc. - + Dacă se salvează sau nu o copie a metadatelor descărcate în directoarele cu conținut ale bibliotecii media. Acest lucru are efect doar dacă descărcarea metadatelor de pe web este activă. + + Când această opțiune este activată, folosește metadatele directorului pentru a sări peste directoarele care nu s-au schimbat de la ultima scanare. Acest lucru poate accelera _semnificativ_ scanările, dar rețineți că metadatele directoarelor _nu_ se schimbă/actualizează atunci când editați fișiere existente, se schimbă doar atunci când adăugați fișiere noi sau ștergeți fișiere existente. Activați această opțiune numai dacă nu modificați fișierele existente. + Un nume pentru identificarea acestei biblioteci @@ -273,9 +276,12 @@ Salvează - + Salvează Metadatele În Directoarele Media + + Sari Peste Directorarele Neschimbate În Timpul Scanării + Scenariu diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx index 88bbd37f..a342b334 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.ru-RU.resx @@ -183,9 +183,12 @@ Заблокирована эта медиатека или нет. Заблокированная библиотека отображается пользователям, но никогда не сканируется, не обновляется, не изменяется и т.д. - + Сохранять копию загруженных метаданных в каталогах содержимого медиатеки или нет. Это действует только если активна загрузка метаданных из интернета. + + При включении этой опции используются метаданные каталогов, чтобы пропускать каталоги, не изменявшиеся с момента последнего сканирования. Это может _значительно_ ускорить сканирование, но учтите, что метаданные каталогов _не_ изменяются/обновляются при редактировании существующих файлов, а только при добавлении новых или удалении существующих. Включайте эту опцию только в том случае, если вы не изменяете существующие файлы. + Название для этой библиотеки @@ -273,9 +276,12 @@ Сохранить - + Сохранить Метаданные В Каталогах Медиафайлов + + Пропускать Неизмененные Папки При Сканировании + Сценарий diff --git a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx index 3bbb6979..6ec96635 100644 --- a/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Views/Library/Management/Item.zh-CN.resx @@ -183,9 +183,12 @@ 此媒体库是否已锁定。锁定的库会显示给用户,但永远不会被扫描、更新、修改等。 - + 是否在媒体库内容位置目录中保存已下载元数据的副本。这仅在从网络下载元数据处于活动状态时才有效。 + + 启用此选项后,将使用目录元数据跳过自上次扫描以来未更改的目录。这可以_显著_加快扫描速度,但请注意,编辑现有文件时目录元数据_不会_更改/更新,只有在添加新文件或删除现有文件时才会更改。仅当您不修改现有文件时才启用此选项。 + 给这个图书馆起个名字 @@ -273,9 +276,12 @@ 保存 - + 在媒体目录中保存元数据 + + 扫描时跳过未更改的文件夹 + 剧本 diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml index 9eba8668..4247df20 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Index.cshtml @@ -169,11 +169,10 @@ }; const jsLocalizedLibraryScanJobsStatuses = { DiscoveringFiles: '@_localizer["DiscoveringFiles"]', - RetrievingPastScanData: '@_localizer["RetrievingPastScanData"]', ComparingFileHashes: '@_localizer["ComparingFileHashes"]', + HashingFileContents: '@_localizer["HashingFileContents"]', GoodReadsMetadataDownload: '@_localizer["GoodReadsMetadataDownload"]', - SavingScanData: '@_localizer["SavingScanData"]', - FilteringBookFiles: '@_localizer["FilteringBookFiles"]' + SavingScanData: '@_localizer["SavingScanData"]' }; const jsLocalizedLibraryTypes = { Book: '@_localizer["Book"]', diff --git a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml index 6df068ca..f928383e 100644 --- a/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml +++ b/src/Lumina.Presentation.Web/Views/Library/Management/Item.cshtml @@ -170,11 +170,11 @@
- : + :
@@ -182,15 +182,27 @@
- +
- @_localizer["DescriptionSaveMetadataInMediaDirectories"] + @_localizer["DescriptionShouldSaveMetadataInMediaDirectories"] +
+
+
+ +
+
+ +
+ @_localizer["DescriptionShouldSkipUnchangedDirectoriesDuringScan"]
@@ -220,8 +232,9 @@ const mediaDirectoriesFormTable = document.getElementById('add-media-directory-form-table'); const chkIsEnabled = form.querySelector('[name="IsEnabled"]'); const chkIsLocked = form.querySelector('[name="IsLocked"]'); - const chkDownloadMedatadaFromWeb = form.querySelector('[name="DownloadMedatadaFromWeb"]'); - const chkSaveMetadataInMediaDirectories = form.querySelector('[name="SaveMetadataInMediaDirectories"]'); + const chkDownloadMetadataFromWeb = form.querySelector('[name="DownloadMetadataFromWeb"]'); + const chkShouldSaveMetadataInMediaDirectories = form.querySelector('[name="ShouldSaveMetadataInMediaDirectories"]'); + const chkShouldSkipUnchangedDirectoriesDuringScan = form.querySelector('[name="ShouldSkipUnchangedDirectoriesDuringScan"]'); // create new or update existing media library async function handleAddMediaLibraryAsync() { @@ -239,8 +252,9 @@ })(), IsEnabled: chkIsEnabled.checked, IsLocked: chkIsLocked.checked, - DownloadMedatadaFromWeb: chkDownloadMedatadaFromWeb.checked, - SaveMetadataInMediaDirectories: chkSaveMetadataInMediaDirectories.checked + DownloadMetadataFromWeb: chkDownloadMetadataFromWeb.checked, + ShouldSaveMetadataInMediaDirectories: chkShouldSaveMetadataInMediaDirectories.checked, + ShouldSkipUnchangedDirectoriesDuringScan: chkShouldSkipUnchangedDirectoriesDuringScan.checked }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl("SaveLibrary", "LibraryManagement")', formData); if (data) { diff --git a/src/Lumina.Presentation.Web/wwwroot/css/dialog.css b/src/Lumina.Presentation.Web/wwwroot/css/dialog.css index f9de69a6..1a5fc905 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/dialog.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/dialog.css @@ -7,12 +7,12 @@ height: 100%; background-color: #000000; opacity: 0.6; - z-index: 1998; + z-index: 998; } .dialog-container { display: none; - position: absolute; + position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css index 7d542613..c1d39e58 100644 --- a/src/Lumina.Presentation.Web/wwwroot/css/site.css +++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css @@ -107,7 +107,7 @@ main { #modal-background-article { display: none; z-index: 998; - position: absolute; + position: fixed; top: 0px; left: 0px; min-width: 100%; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index 0064f3e5..44c19ee2 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -26,6 +26,7 @@ public class AddMediaLibraryRequestMappingTests true, false, true, + false, false ); @@ -40,8 +41,8 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMedatadaFromWeb, result.DownloadMedatadaFromWeb); - Assert.Equal(request.SaveMetadataInMediaDirectories, result.SaveMetadataInMediaDirectories); + Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } [Theory] @@ -60,6 +61,7 @@ public class AddMediaLibraryRequestMappingTests true, false, true, + false, false ); @@ -74,8 +76,8 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMedatadaFromWeb, result.DownloadMedatadaFromWeb); - Assert.Equal(request.SaveMetadataInMediaDirectories, result.SaveMetadataInMediaDirectories); + Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } [Fact] @@ -98,6 +100,7 @@ public class AddMediaLibraryRequestMappingTests true, false, true, + false, false ); @@ -127,6 +130,7 @@ public class AddMediaLibraryRequestMappingTests true, false, true, + false, false ); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index d41ebf26..6ab208e4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -35,6 +35,7 @@ public class LibraryMappingTests false, true, false, + false, [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -54,8 +55,8 @@ public class LibraryMappingTests Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMedatadaFromWeb); - Assert.False(result.SaveMetadataInMediaDirectories); + Assert.True(result.DownloadMetadataFromWeb); + Assert.False(result.ShouldSaveMetadataInMediaDirectories); Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id)); } @@ -73,6 +74,7 @@ public class LibraryMappingTests false, true, false, + false, [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -104,6 +106,7 @@ public class LibraryMappingTests false, true, false, + false, [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -117,8 +120,8 @@ public class LibraryMappingTests Assert.Equal(library.CoverImage, result.CoverImage); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMedatadaFromWeb); - Assert.False(result.SaveMetadataInMediaDirectories); + Assert.True(result.DownloadMetadataFromWeb); + Assert.False(result.ShouldSaveMetadataInMediaDirectories); } [Fact] @@ -143,6 +146,7 @@ public class LibraryMappingTests false, true, false, + false, [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -176,6 +180,7 @@ public class LibraryMappingTests false, true, false, + false, [ScanId.CreateUnique()] ); Library library = libraryResult.Value; @@ -209,6 +214,7 @@ public class LibraryMappingTests false, true, false, + false, [] ); Library library = libraryResult.Value; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs index 802a4f2b..68116930 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Fixtures/DomainLibraryFixture.cs @@ -55,6 +55,7 @@ public class DomainLibraryFixture _faker.Random.Bool(), _faker.Random.Bool(), _faker.Random.Bool(), + _faker.Random.Bool(), [ScanId.CreateUnique(), ScanId.CreateUnique()] ); @@ -70,8 +71,9 @@ public class DomainLibraryFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMedatadaFromWeb = true, - bool saveMetadataInMediaDirectories = false, + bool downloadMetadataFromWeb = true, + bool shouldSaveMetadataInMediaDirectories = false, + bool shouldSkipUnchangedDirectoriesDuringScan = false, IEnumerable? scanIds = null) { ErrorOr library = id is null ? @@ -83,8 +85,9 @@ public class DomainLibraryFixture coverImage, isEnabled, isLocked, - downloadMedatadaFromWeb, - saveMetadataInMediaDirectories, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] ) : Library.Create( @@ -96,8 +99,9 @@ public class DomainLibraryFixture coverImage, isEnabled, isLocked, - downloadMedatadaFromWeb, - saveMetadataInMediaDirectories, + downloadMetadataFromWeb, + shouldSaveMetadataInMediaDirectories, + shouldSkipUnchangedDirectoriesDuringScan, scanIds?.Select(scanId => ScanId.Create(scanId)).ToList() ?? [ScanId.CreateUnique(), ScanId.CreateUnique()] );