mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #289 from BinaryAlley/refactor/standardize-comments-to-full-sentences
Formats code comments as full sentences
This commit is contained in:
712 files changed
+4416
-4415
No files matched your search
@@ -4,7 +4,7 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
workflow_dispatch: # enable manual triggers
|
workflow_dispatch: # Enable manual triggers.
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
run-platform-tests:
|
run-platform-tests:
|
||||||
@@ -32,8 +32,8 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
run: dotnet build src/Lumina.slnx --no-restore -p:SixLaborsLicenseEnforceBuild=true
|
run: dotnet build src/Lumina.slnx --no-restore -p:SixLaborsLicenseEnforceBuild=true
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
# blame-hang terminates a test that blocks for 10 minutes and dumps the hang stack,
|
# Blame-hang terminates a test that blocks for 10 minutes and dumps the hang stack,
|
||||||
# turning the recurring 'stuck job' into a failing job that names the culprit test
|
# turning the recurring 'stuck job' into a failing job that names the culprit test.
|
||||||
run: dotnet test src/Lumina.slnx --no-build --verbosity normal --blame-hang --blame-hang-timeout 10m
|
run: dotnet test src/Lumina.slnx --no-build --verbosity normal --blame-hang --blame-hang-timeout 10m
|
||||||
- name: Upload hang diagnostics
|
- name: Upload hang diagnostics
|
||||||
if: failure()
|
if: failure()
|
||||||
|
|||||||
@@ -444,6 +444,7 @@ namespace MyNamespace // Not Allowed
|
|||||||
```
|
```
|
||||||
|
|
||||||
#### Formatting:
|
#### Formatting:
|
||||||
|
- Write comments as sentences: capitalize the first word and end with a period. `TODO`, `FIXME`, `HACK`, `XXX` and `NOTE` bodies stay lowercase after the colon, and commented-out code is left exactly as written.
|
||||||
- Use a single space after keywords in control flow statements. For example:
|
- Use a single space after keywords in control flow statements. For example:
|
||||||
```csharp
|
```csharp
|
||||||
if (condition) // Correct
|
if (condition) // Correct
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ This project enforces many style rules via `.editorconfig` as build errors, so t
|
|||||||
|
|
||||||
- **Naming quality**: names must be explicit, even if long. Domain names must match the project's Ubiquitous Language exactly. Lambda parameters must be named descriptively, never single letters or shortened anti-pattern names (no `x`, `e`, `s`, etc).
|
- **Naming quality**: names must be explicit, even if long. Domain names must match the project's Ubiquitous Language exactly. Lambda parameters must be named descriptively, never single letters or shortened anti-pattern names (no `x`, `e`, `s`, etc).
|
||||||
- **Domain nullability**: domain code must never use nullable value types or reference nulls directly, it must use the `Optional<T>` and `Result<T>` types instead. Flag any raw `null`/`?` usage in domain code.
|
- **Domain nullability**: domain code must never use nullable value types or reference nulls directly, it must use the `Optional<T>` and `Result<T>` types instead. Flag any raw `null`/`?` usage in domain code.
|
||||||
- **Comments**: should explain *why*, not *what* (the code already shows what). Wrap only when substantially exceeding a 1920px monitor's width. Flag comments that just restate the code.
|
- **Comments**: should explain *why*, not *what* (the code already shows what). Wrap only when substantially exceeding a 1920px monitor's width. Flag comments that just restate the code. Comment text is written as a sentence: the first word is capitalized and the sentence ends with a period, in every code file the repository contains (C#, JavaScript, CSS, Razor, HTML, MSBuild/XML, SVG, YAML, Dockerfiles, and the bundled theme archives). Generated files (`*.Designer.cs`, `*ModelSnapshot.cs`, `AssemblyInfo.cs`) and tool configuration files (`.editorconfig`, `.gitignore`) are excluded. Section labels and marker comments follow the same rule, except the `// Arrange`, `// Act` and `// Assert` markers, which are always written bare, without a period. `TODO`, `FIXME`, `HACK`, `XXX` and `NOTE` already provide the capitalized first word, so the body after the colon is written in lowercase, unless it starts with a proper noun or a code identifier. Commented-out code is not prose and is left exactly as written.
|
||||||
- **XML documentation**: required on every public construct, and also on private properties and methods. Use `<see langword="etc"/>` for language keywords, not `<c>etc</c>`. Method summaries must not expose internal implementation details, unless truly relevant, in which case put that detail in a `<remarks>` block instead of the summary.
|
- **XML documentation**: required on every public construct, and also on private properties and methods. Use `<see langword="etc"/>` for language keywords, not `<c>etc</c>`. Method summaries must not expose internal implementation details, unless truly relevant, in which case put that detail in a `<remarks>` block instead of the summary.
|
||||||
- **`<inheritdoc/>`**: avoid on classes implementing interface members. Developers usually work in the implementing class and should see documentation there directly, without having to open the interface.
|
- **`<inheritdoc/>`**: avoid on classes implementing interface members. Developers usually work in the implementing class and should see documentation there directly, without having to open the interface.
|
||||||
- **Boolean naming**: boolean fields, properties, and methods returning booleans must start with a verb implying true/false: `is`, `are`, `should`, `has`, `was`, `can`, etc.
|
- **Boolean naming**: boolean fields, properties, and methods returning booleans must start with a verb implying true/false: `is`, `are`, `should`, `has`, `was`, `can`, etc.
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ internal sealed class CalibreArtworkProvider : IArtworkProvider<BookMetadataLook
|
|||||||
if (string.IsNullOrWhiteSpace(document.CoverHref))
|
if (string.IsNullOrWhiteSpace(document.CoverHref))
|
||||||
return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||||
|
|
||||||
// the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed
|
// The cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed.
|
||||||
string coverFileName = Path.GetFileName(document.CoverHref);
|
string coverFileName = Path.GetFileName(document.CoverHref);
|
||||||
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
|
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
|
||||||
return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ internal static class OpfReader
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
using FileStream fileStream = File.OpenRead(opfFilePath);
|
using FileStream fileStream = File.OpenRead(opfFilePath);
|
||||||
// the OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded
|
// The OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded.
|
||||||
XmlReaderSettings xmlReaderSettings = new()
|
XmlReaderSettings xmlReaderSettings = new()
|
||||||
{
|
{
|
||||||
DtdProcessing = DtdProcessing.Prohibit,
|
DtdProcessing = DtdProcessing.Prohibit,
|
||||||
@@ -48,7 +48,7 @@ internal static class OpfReader
|
|||||||
}
|
}
|
||||||
catch (XmlException)
|
catch (XmlException)
|
||||||
{
|
{
|
||||||
// a malformed OPF file must not prevent the enrichment of the book from proceeding
|
// A malformed OPF file must not prevent the enrichment of the book from proceeding.
|
||||||
}
|
}
|
||||||
|
|
||||||
return document;
|
return document;
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
|||||||
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null;
|
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null;
|
||||||
string? openLibraryId = bookMetadataLookup.OpenLibraryId;
|
string? openLibraryId = bookMetadataLookup.OpenLibraryId;
|
||||||
string? isbn = bookMetadataLookup.Isbn;
|
string? isbn = bookMetadataLookup.Isbn;
|
||||||
// if we have an Open Library Id, that's the first thing we should search by
|
// If we have an Open Library Id, that's the first thing we should search by.
|
||||||
if (!string.IsNullOrWhiteSpace(openLibraryId))
|
if (!string.IsNullOrWhiteSpace(openLibraryId))
|
||||||
{
|
{
|
||||||
string olid = NormalizeOlid(openLibraryId);
|
string olid = NormalizeOlid(openLibraryId);
|
||||||
@@ -123,10 +123,10 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
|||||||
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
|
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
// no Open Library Id, let's try by ISBN
|
// No Open Library Id, let's try by ISBN.
|
||||||
if (openLibraryEditionResponse is null && !string.IsNullOrWhiteSpace(isbn))
|
if (openLibraryEditionResponse is null && !string.IsNullOrWhiteSpace(isbn))
|
||||||
openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionByIsbnAsync(isbn, cancellationToken).ConfigureAwait(false);
|
openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionByIsbnAsync(isbn, cancellationToken).ConfigureAwait(false);
|
||||||
// if we still have no results, let's go nuclear and search by metadata
|
// If we still have no results, let's go nuclear and search by metadata.
|
||||||
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
|
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
|
||||||
{
|
{
|
||||||
IReadOnlyList<OpenLibrarySearchDocumentResponse> searchResults = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, 1, cancellationToken).ConfigureAwait(false);
|
IReadOnlyList<OpenLibrarySearchDocumentResponse> searchResults = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, 1, cancellationToken).ConfigureAwait(false);
|
||||||
@@ -143,7 +143,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
|||||||
if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0)
|
if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0)
|
||||||
openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionAsync(searchResults[0].EditionKeys[0], cancellationToken).ConfigureAwait(false);
|
openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionAsync(searchResults[0].EditionKeys[0], cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
// if by this time we still have no result, let's forget it...
|
// If by this time we still have no result, let's forget it...
|
||||||
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null && openLibrarySearchDocumentResponse is null)
|
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null && openLibrarySearchDocumentResponse is null)
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
@@ -208,7 +208,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
|||||||
private static int ScoreEdition(OpenLibraryEditionResponse openLibraryEdition, string? wantedIsbn, string? wantedLanguage)
|
private static int ScoreEdition(OpenLibraryEditionResponse openLibraryEdition, string? wantedIsbn, string? wantedLanguage)
|
||||||
{
|
{
|
||||||
int score = 0;
|
int score = 0;
|
||||||
// if we get an ISBN match, that's the most certain identification score
|
// If we get an ISBN match, that's the most certain identification score.
|
||||||
if (wantedIsbn is not null && openLibraryEdition.Isbn10.Concat(openLibraryEdition.Isbn13).Any(value => string.Equals(SafeNormalizeIsbn(value), wantedIsbn, StringComparison.OrdinalIgnoreCase)))
|
if (wantedIsbn is not null && openLibraryEdition.Isbn10.Concat(openLibraryEdition.Isbn13).Any(value => string.Equals(SafeNormalizeIsbn(value), wantedIsbn, StringComparison.OrdinalIgnoreCase)))
|
||||||
score += 10_000;
|
score += 10_000;
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -248,7 +248,7 @@ internal static class PdfDocumentParser
|
|||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
// The bookmarks of a malformed PDF are best effort, so the table of contents is skipped instead of failing the book; the pages themselves are still readable
|
// The bookmarks of a malformed PDF are best effort, so the table of contents is skipped instead of failing the book; the pages themselves are still readable.
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
|
||||||
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
|
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else.-->
|
||||||
<ExcludeAssets>runtime</ExcludeAssets>
|
<ExcludeAssets>runtime</ExcludeAssets>
|
||||||
</ProjectReference>
|
</ProjectReference>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
+2
-2
@@ -73,7 +73,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
|||||||
public ReleaseCountry? ReleaseCountry { get; set; }
|
public ReleaseCountry? ReleaseCountry { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0")
|
/// Gets or sets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0").
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? ReleaseVersion { get; set; }
|
public string? ReleaseVersion { get; set; }
|
||||||
|
|
||||||
@@ -141,7 +141,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
|||||||
/// Gets or sets the volume or book number in the series, if applicable.
|
/// Gets or sets the volume or book number in the series, if applicable.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public float? VolumeNumber { get; set; }
|
public float? VolumeNumber { get; set; }
|
||||||
// TODO: uncomment when series is implemented
|
// TODO: uncomment when series is implemented.
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the series id, if the book is part of a series.
|
/// Gets or sets the series id, if the book is part of a series.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
|
|||||||
private readonly List<Func<TProperty, bool>> _predicates = [];
|
private readonly List<Func<TProperty, bool>> _predicates = [];
|
||||||
private readonly List<Error> _predicateErrors = [];
|
private readonly List<Error> _predicateErrors = [];
|
||||||
|
|
||||||
// instance-aware predicates get their own separate pair of lists instead of being merged into the
|
// Instance-aware predicates get their own separate pair of lists instead of being merged into the
|
||||||
// lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
|
// lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
|
||||||
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
|
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
|
||||||
private readonly List<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
|
private readonly List<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
|
||||||
@@ -132,7 +132,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
|
|||||||
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
|
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
|
||||||
public IEnumerable<Error> Validate(TRequest instance)
|
public IEnumerable<Error> Validate(TRequest instance)
|
||||||
{
|
{
|
||||||
// evaluate the condition first, if it returns false, skip validation entirely.
|
// Evaluate the condition first, if it returns false, skip validation entirely.
|
||||||
if (condition is not null && !condition(instance))
|
if (condition is not null && !condition(instance))
|
||||||
yield break;
|
yield break;
|
||||||
|
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
|
|||||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
|
||||||
public IRuleBuilder<TRequest, TItem> WithError(Error error)
|
public IRuleBuilder<TRequest, TItem> WithError(Error error)
|
||||||
{
|
{
|
||||||
// validation rules always produce validation errors, regardless of the error type of the source error
|
// Validation rules always produce validation errors, regardless of the error type of the source error.
|
||||||
Error validationError = Error.Validation(description: error.Description);
|
Error validationError = Error.Validation(description: error.Description);
|
||||||
currentError = validationError;
|
currentError = validationError;
|
||||||
if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0)
|
if (isLastAddedPredicateInstanceAware && _instanceAwarePredicateErrors.Count > 0)
|
||||||
@@ -106,7 +106,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
|
|||||||
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
|
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
|
||||||
public IEnumerable<Error> Validate(TRequest instance)
|
public IEnumerable<Error> Validate(TRequest instance)
|
||||||
{
|
{
|
||||||
// evaluate the condition first, if it returns false, skip validation entirely.
|
// Evaluate the condition first, if it returns false, skip validation entirely.
|
||||||
if (condition is not null && !condition(instance))
|
if (condition is not null && !condition(instance))
|
||||||
yield break;
|
yield break;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -218,7 +218,7 @@ public static class TrackEntityMapping
|
|||||||
repositoryEntity.ReleaseCountry,
|
repositoryEntity.ReleaseCountry,
|
||||||
repositoryEntity.ReleaseVersion
|
repositoryEntity.ReleaseVersion
|
||||||
);
|
);
|
||||||
// language and original language make sense only if their subproperties have values
|
// Language and original language make sense only if their subproperties have values.
|
||||||
LanguageInfoDto? languageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) ||
|
LanguageInfoDto? languageInfo = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) ||
|
||||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
||||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ public static class LibraryMapping
|
|||||||
{
|
{
|
||||||
Id = scanId.Value,
|
Id = scanId.Value,
|
||||||
LibraryId = domainEntity.Id.Value,
|
LibraryId = domainEntity.Id.Value,
|
||||||
UserId = domainEntity.UserId.Value, // rest of properties will be populated by EF Core
|
UserId = domainEntity.UserId.Value, // Rest of properties will be populated by EF Core.
|
||||||
Status = default,
|
Status = default,
|
||||||
User = null!,
|
User = null!,
|
||||||
Library = null!,
|
Library = null!,
|
||||||
|
|||||||
+1
-1
@@ -199,7 +199,7 @@ public static class BookEntityMapping
|
|||||||
repositoryEntity.ReleaseCountry,
|
repositoryEntity.ReleaseCountry,
|
||||||
repositoryEntity.ReleaseVersion
|
repositoryEntity.ReleaseVersion
|
||||||
);
|
);
|
||||||
// language and original language make sense only if their subproperties have values
|
// Language and original language make sense only if their subproperties have values.
|
||||||
LanguageInfoDto? languageInfoEntity = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) ||
|
LanguageInfoDto? languageInfoEntity = !string.IsNullOrWhiteSpace(repositoryEntity.LanguageCode) ||
|
||||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
||||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ internal static class ApplicationHandlerTelemetry
|
|||||||
{
|
{
|
||||||
activity?.SetStatus(ActivityStatusCode.Error, error);
|
activity?.SetStatus(ActivityStatusCode.Error, error);
|
||||||
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
|
RecordOutcome(activity, handlerName, handlerType, duration, isSuccess: false);
|
||||||
// business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers
|
// Business-rule failures are routine outcomes (e.g. failed logins), so log at Debug to avoid noise from high-frequency handlers.
|
||||||
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
|
logger.LogDebug("Failed handling {HandlerType} {HandlerName} in {DurationMs}ms: {Error}", handlerType, handlerName, duration.TotalMilliseconds, error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ public class LibraryScanJobProgressChangedDomainEventHandler : IDomainEventHandl
|
|||||||
public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
_mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress);
|
_mediaLibrariesScanProgressTracker.UpdateScanJobProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId, domainEvent.Progress);
|
||||||
// notify SignalR clients that the library scan progress changed
|
// Notify SignalR clients that the library scan progress changed.
|
||||||
await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -38,7 +38,7 @@ public class LibraryScanProgressChangedDomainEventHandler : IDomainEventHandler<
|
|||||||
public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
_mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId);
|
_mediaLibrariesScanProgressTracker.UpdateScanProgress(domainEvent.LibraryId, domainEvent.MediaLibraryScanCompositeId);
|
||||||
// notify SignalR clients that the library scan progress changed
|
// Notify SignalR clients that the library scan progress changed.
|
||||||
await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
await _debouncedLibraryScanProgressNotifier.SendLibraryProgressUpdateEventAsync(domainEvent.MediaLibraryScanCompositeId, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -63,7 +63,7 @@ public class GetThemeAssetQueryHandler : IQueryHandler<GetThemeAssetQuery, Resul
|
|||||||
Result<ThemeAssetDto> assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
|
Result<ThemeAssetDto> assetResult = await _themeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, cancellationToken).ConfigureAwait(false);
|
||||||
if (assetResult.IsFailure)
|
if (assetResult.IsFailure)
|
||||||
{
|
{
|
||||||
// the stored files of a bundled theme removed externally are restored, so its assets keep being served
|
// The stored files of a bundled theme removed externally are restored, so its assets keep being served.
|
||||||
if (theme.InstallSource == ThemeInstallSource.Bundled)
|
if (theme.InstallSource == ThemeInstallSource.Bundled)
|
||||||
{
|
{
|
||||||
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
|
Result<Success> restoreResult = await _themeService.RestoreBundledThemeAsync(theme.ThemeId, cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+1
-1
@@ -84,7 +84,7 @@ public class RecoverPasswordCommandHandler : ICommandHandler<RecoverPasswordComm
|
|||||||
return Errors.Authentication.InvalidTotpCode;
|
return Errors.Authentication.InvalidTotpCode;
|
||||||
|
|
||||||
// Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes.
|
// Generate the hash of a temporary password and record when it was created, so that the reset flow can expire it after 15 minutes.
|
||||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: Replace the hardcoded password with a randomly generated one.
|
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace the hardcoded password with a randomly generated one.
|
||||||
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||||
|
|
||||||
// Update the user and persist the temporary password.
|
// Update the user and persist the temporary password.
|
||||||
|
|||||||
+1
-1
@@ -116,7 +116,7 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
|||||||
if (saveChangesResult.IsFailure)
|
if (saveChangesResult.IsFailure)
|
||||||
return saveChangesResult.Errors;
|
return saveChangesResult.Errors;
|
||||||
|
|
||||||
// TODO: Insert the default admin profile preferences when they are implemented.
|
// TODO: insert the default admin profile preferences when they are implemented.
|
||||||
// If 2FA was enabled, the TOTP secret needs to be delivered to the client unencrypted, so it can be displayed.
|
// If 2FA was enabled, the TOTP secret needs to be delivered to the client unencrypted, so it can be displayed.
|
||||||
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ public class RegisterUserCommandValidator : AbstractValidator<RegisterUserComman
|
|||||||
.WithError(Errors.Authentication.UsernameCannotBeEmpty)
|
.WithError(Errors.Authentication.UsernameCannotBeEmpty)
|
||||||
.Length(3, 255)
|
.Length(3, 255)
|
||||||
.WithError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong)
|
.WithError(Errors.Authentication.UsernameMustBeBetween3And255CharactersLong)
|
||||||
.Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$") // only allow letters, numbers, dots, underscores and hyphens, and must start and end with letter or number
|
.Matches("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$") // Only allow letters, numbers, dots, underscores and hyphens, and must start and end with letter or number.
|
||||||
.WithError(Errors.Authentication.InvalidUsername);
|
.WithError(Errors.Authentication.InvalidUsername);
|
||||||
|
|
||||||
RuleFor(command => command.Password)
|
RuleFor(command => command.Password)
|
||||||
|
|||||||
+1
-1
@@ -24,7 +24,7 @@ public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator<Up
|
|||||||
.Must(id => id != Guid.Empty)
|
.Must(id => id != Guid.Empty)
|
||||||
.WithError(DomainErrors.Users.UserIdCannotBeEmpty);
|
.WithError(DomainErrors.Users.UserIdCannotBeEmpty);
|
||||||
|
|
||||||
// validate each permission Id when the list is provided
|
// Validate each permission Id when the list is provided.
|
||||||
RuleForEach(command => command.Permissions)
|
RuleForEach(command => command.Permissions)
|
||||||
.NotEmpty()
|
.NotEmpty()
|
||||||
.WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty)
|
.WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty)
|
||||||
|
|||||||
@@ -142,8 +142,8 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
|
|||||||
.HasForeignKey(album => album.ArtistId)
|
.HasForeignKey(album => album.ArtistId)
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
|
||||||
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
// Since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
||||||
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
|
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key.
|
||||||
builder.HasMany(album => album.Tags)
|
builder.HasMany(album => album.Tags)
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.UsingEntity<Dictionary<string, object>>(
|
.UsingEntity<Dictionary<string, object>>(
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class AlbumContributorConfiguration : IEntityTypeConfiguration<AlbumContr
|
|||||||
builder.ToTable("AlbumContributors");
|
builder.ToTable("AlbumContributors");
|
||||||
builder.HasKey(albumContributor => albumContributor.Id);
|
builder.HasKey(albumContributor => albumContributor.Id);
|
||||||
builder.Property(albumContributor => albumContributor.Id)
|
builder.Property(albumContributor => albumContributor.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(albumContributor => albumContributor.AlbumId)
|
builder.Property(albumContributor => albumContributor.AlbumId)
|
||||||
@@ -35,7 +35,7 @@ public class AlbumContributorConfiguration : IEntityTypeConfiguration<AlbumContr
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(albumContributor => albumContributor.CreatedOnUtc)
|
builder.Property(albumContributor => albumContributor.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
|
|||||||
builder.ToTable("Artists");
|
builder.ToTable("Artists");
|
||||||
builder.HasKey(artist => artist.Id);
|
builder.HasKey(artist => artist.Id);
|
||||||
builder.Property(artist => artist.Id)
|
builder.Property(artist => artist.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(artist => artist.LibraryId)
|
builder.Property(artist => artist.LibraryId)
|
||||||
@@ -143,8 +143,8 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
|
|||||||
.HasMaxLength(20);
|
.HasMaxLength(20);
|
||||||
});
|
});
|
||||||
|
|
||||||
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
// Since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
||||||
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
|
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key.
|
||||||
builder.HasMany(artist => artist.Tags)
|
builder.HasMany(artist => artist.Tags)
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.UsingEntity<Dictionary<string, object>>(
|
.UsingEntity<Dictionary<string, object>>(
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class ArtistContributorConfiguration : IEntityTypeConfiguration<ArtistCon
|
|||||||
builder.ToTable("ArtistContributors");
|
builder.ToTable("ArtistContributors");
|
||||||
builder.HasKey(artistContributor => artistContributor.Id);
|
builder.HasKey(artistContributor => artistContributor.Id);
|
||||||
builder.Property(artistContributor => artistContributor.Id)
|
builder.Property(artistContributor => artistContributor.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(artistContributor => artistContributor.ArtistId)
|
builder.Property(artistContributor => artistContributor.ArtistId)
|
||||||
@@ -35,7 +35,7 @@ public class ArtistContributorConfiguration : IEntityTypeConfiguration<ArtistCon
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(artistContributor => artistContributor.CreatedOnUtc)
|
builder.Property(artistContributor => artistContributor.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class BookArtworkConfiguration : IEntityTypeConfiguration<BookArtworkEnti
|
|||||||
builder.ToTable("BookArtwork");
|
builder.ToTable("BookArtwork");
|
||||||
builder.HasKey(bookArtwork => bookArtwork.Id);
|
builder.HasKey(bookArtwork => bookArtwork.Id);
|
||||||
builder.Property(bookArtwork => bookArtwork.Id)
|
builder.Property(bookArtwork => bookArtwork.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(bookArtwork => bookArtwork.BookId)
|
builder.Property(bookArtwork => bookArtwork.BookId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -49,7 +49,7 @@ public class BookArtworkConfiguration : IEntityTypeConfiguration<BookArtworkEnti
|
|||||||
builder.Property(bookArtwork => bookArtwork.LastUpdateUtc)
|
builder.Property(bookArtwork => bookArtwork.LastUpdateUtc)
|
||||||
.HasColumnOrder(8);
|
.HasColumnOrder(8);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(bookArtwork => bookArtwork.CreatedOnUtc)
|
builder.Property(bookArtwork => bookArtwork.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(9);
|
.HasColumnOrder(9);
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
|||||||
builder.ToTable("Books");
|
builder.ToTable("Books");
|
||||||
builder.HasKey(book => book.Id);
|
builder.HasKey(book => book.Id);
|
||||||
builder.Property(book => book.Id)
|
builder.Property(book => book.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(book => book.Title)
|
builder.Property(book => book.Title)
|
||||||
@@ -62,8 +62,8 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
|||||||
.HasColumnOrder(14);
|
.HasColumnOrder(14);
|
||||||
builder.Property(book => book.OriginalLanguageNativeName)
|
builder.Property(book => book.OriginalLanguageNativeName)
|
||||||
.HasColumnOrder(15);
|
.HasColumnOrder(15);
|
||||||
// since Tag is a Domain ValueObject (no identity), but we also don't want to have duplicates,
|
// Since Tag is a Domain ValueObject (no identity), but we also don't want to have duplicates,
|
||||||
// we need to configure it as a many-to-many relationship, where the tag itself is the primary key
|
// we need to configure it as a many-to-many relationship, where the tag itself is the primary key.
|
||||||
builder.HasMany(book => book.Tags)
|
builder.HasMany(book => book.Tags)
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.UsingEntity<Dictionary<string, object>>(
|
.UsingEntity<Dictionary<string, object>>(
|
||||||
@@ -213,7 +213,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
|||||||
.IsRequired();
|
.IsRequired();
|
||||||
});
|
});
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(book => book.CreatedOnUtc)
|
builder.Property(book => book.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(32);
|
.HasColumnOrder(32);
|
||||||
@@ -231,7 +231,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
|||||||
.HasColumnOrder(35);
|
.HasColumnOrder(35);
|
||||||
|
|
||||||
builder.HasIndex(book => new { book.LibraryId, book.Path })
|
builder.HasIndex(book => new { book.LibraryId, book.Path })
|
||||||
.IsUnique(); // the same physical book on disk cannot appear twice in the same library
|
.IsUnique(); // The same physical book on disk cannot appear twice in the same library.
|
||||||
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus });
|
builder.HasIndex(book => new { book.LibraryId, book.MetadataStatus });
|
||||||
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
|
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
|
||||||
// index follows the same order and no temporary B-tree is needed for the sort.
|
// index follows the same order and no temporary B-tree is needed for the sort.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class BookContributorConfiguration : IEntityTypeConfiguration<BookContrib
|
|||||||
builder.ToTable("BookContributors");
|
builder.ToTable("BookContributors");
|
||||||
builder.HasKey(bookContributor => bookContributor.Id);
|
builder.HasKey(bookContributor => bookContributor.Id);
|
||||||
builder.Property(bookContributor => bookContributor.Id)
|
builder.Property(bookContributor => bookContributor.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(bookContributor => bookContributor.BookId)
|
builder.Property(bookContributor => bookContributor.BookId)
|
||||||
@@ -35,7 +35,7 @@ public class BookContributorConfiguration : IEntityTypeConfiguration<BookContrib
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(bookContributor => bookContributor.CreatedOnUtc)
|
builder.Property(bookContributor => bookContributor.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration<Di
|
|||||||
public void Configure(EntityTypeBuilder<DirectoryScanFingerprintEntity> builder)
|
public void Configure(EntityTypeBuilder<DirectoryScanFingerprintEntity> builder)
|
||||||
{
|
{
|
||||||
builder.ToTable("DirectoryScanFingerprints");
|
builder.ToTable("DirectoryScanFingerprints");
|
||||||
// composite key, so that each directory scan fingerprint is uniquely identified within its library by its path
|
// 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 });
|
builder.HasKey(directoryScanFingerprint => new { directoryScanFingerprint.LibraryId, directoryScanFingerprint.Path });
|
||||||
|
|
||||||
// one library with many directory scan fingerprints
|
// One library with many directory scan fingerprints.
|
||||||
builder.HasOne<LibraryEntity>()
|
builder.HasOne<LibraryEntity>()
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey(directoryScanFingerprint => directoryScanFingerprint.LibraryId)
|
.HasForeignKey(directoryScanFingerprint => directoryScanFingerprint.LibraryId)
|
||||||
@@ -41,7 +41,7 @@ public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration<Di
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(2);
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
// enables fast lookups of the directory scan fingerprints of a library
|
// Enables fast lookups of the directory scan fingerprints of a library.
|
||||||
builder.HasIndex(directoryScanFingerprint => directoryScanFingerprint.LibraryId);
|
builder.HasIndex(directoryScanFingerprint => directoryScanFingerprint.LibraryId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ public class FavoriteConfiguration : IEntityTypeConfiguration<FavoriteEntity>
|
|||||||
builder.ToTable("Favorites");
|
builder.ToTable("Favorites");
|
||||||
builder.HasKey(favorite => favorite.Id);
|
builder.HasKey(favorite => favorite.Id);
|
||||||
builder.Property(favorite => favorite.Id)
|
builder.Property(favorite => favorite.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// A favorite belongs to the user that created it, and it is removed with that user.
|
// A favorite belongs to the user that created it, and it is removed with that user.
|
||||||
|
|||||||
+2
-2
@@ -20,7 +20,7 @@ public class LibraryBookReaderConfigurationConfiguration : IEntityTypeConfigurat
|
|||||||
builder.ToTable("LibraryBookReaderConfigurations");
|
builder.ToTable("LibraryBookReaderConfigurations");
|
||||||
builder.HasKey(configuration => configuration.Id);
|
builder.HasKey(configuration => configuration.Id);
|
||||||
builder.Property(configuration => configuration.Id)
|
builder.Property(configuration => configuration.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(configuration => configuration.LibraryId)
|
builder.Property(configuration => configuration.LibraryId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -32,7 +32,7 @@ public class LibraryBookReaderConfigurationConfiguration : IEntityTypeConfigurat
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(configuration => configuration.CreatedOnUtc)
|
builder.Property(configuration => configuration.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
|||||||
builder.ToTable("Libraries");
|
builder.ToTable("Libraries");
|
||||||
builder.HasKey(library => library.Id);
|
builder.HasKey(library => library.Id);
|
||||||
builder.Property(library => library.Id)
|
builder.Property(library => library.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(library => library.Title)
|
builder.Property(library => library.Title)
|
||||||
@@ -83,19 +83,19 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
|||||||
.HasDefaultValue(false)
|
.HasDefaultValue(false)
|
||||||
.HasColumnOrder(18);
|
.HasColumnOrder(18);
|
||||||
|
|
||||||
// one user with many libraries
|
// One user with many libraries.
|
||||||
builder.HasOne(library => library.User)
|
builder.HasOne(library => library.User)
|
||||||
.WithMany(user => user.Libraries)
|
.WithMany(user => user.Libraries)
|
||||||
.HasForeignKey(library => library.UserId)
|
.HasForeignKey(library => library.UserId)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
// one library with many scans
|
// One library with many scans.
|
||||||
builder.HasMany(library => library.LibraryScans)
|
builder.HasMany(library => library.LibraryScans)
|
||||||
.WithOne(libraryScan => libraryScan.Library)
|
.WithOne(libraryScan => libraryScan.Library)
|
||||||
.HasForeignKey(libraryScan => libraryScan.LibraryId)
|
.HasForeignKey(libraryScan => libraryScan.LibraryId)
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a library deletes library scans
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a library deletes library scans.
|
||||||
|
|
||||||
// using OwnsMany because paths are domain Value Objects, thus they have no independent identity, and their lifecycle is bound to the Library
|
// Using OwnsMany because paths are domain Value Objects, thus they have no independent identity, and their lifecycle is bound to the Library.
|
||||||
builder.OwnsMany(library => library.ContentLocations, contentLocationBuilder =>
|
builder.OwnsMany(library => library.ContentLocations, contentLocationBuilder =>
|
||||||
{
|
{
|
||||||
contentLocationBuilder.ToTable("LibraryContentLocations");
|
contentLocationBuilder.ToTable("LibraryContentLocations");
|
||||||
@@ -112,7 +112,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
|||||||
.IsRequired();
|
.IsRequired();
|
||||||
});
|
});
|
||||||
|
|
||||||
// the path template parts are ordered, so their position is stored explicitly and part of a unique index together with the library
|
// The path template parts are ordered, so their position is stored explicitly and part of a unique index together with the library.
|
||||||
builder.OwnsMany(library => library.PathTemplateParts, partBuilder =>
|
builder.OwnsMany(library => library.PathTemplateParts, partBuilder =>
|
||||||
{
|
{
|
||||||
partBuilder.ToTable("LibraryPathTemplateParts");
|
partBuilder.ToTable("LibraryPathTemplateParts");
|
||||||
@@ -139,7 +139,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
|||||||
.IsRequired();
|
.IsRequired();
|
||||||
});
|
});
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(library => library.CreatedOnUtc)
|
builder.Property(library => library.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(12);
|
.HasColumnOrder(12);
|
||||||
|
|||||||
@@ -21,16 +21,16 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
|||||||
builder.ToTable("LibraryScans");
|
builder.ToTable("LibraryScans");
|
||||||
builder.HasKey(library => library.Id);
|
builder.HasKey(library => library.Id);
|
||||||
builder.Property(library => library.Id)
|
builder.Property(library => library.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// one user with many library scans
|
// One user with many library scans.
|
||||||
builder.HasOne(libraryScan => libraryScan.User)
|
builder.HasOne(libraryScan => libraryScan.User)
|
||||||
.WithMany(user => user.LibraryScans)
|
.WithMany(user => user.LibraryScans)
|
||||||
.HasForeignKey(libraryScan => libraryScan.UserId)
|
.HasForeignKey(libraryScan => libraryScan.UserId)
|
||||||
.IsRequired();
|
.IsRequired();
|
||||||
|
|
||||||
// one library with many library scans
|
// One library with many library scans.
|
||||||
builder.HasOne(libraryScan => libraryScan.Library)
|
builder.HasOne(libraryScan => libraryScan.Library)
|
||||||
.WithMany(library => library.LibraryScans)
|
.WithMany(library => library.LibraryScans)
|
||||||
.HasForeignKey(libraryScan => libraryScan.LibraryId)
|
.HasForeignKey(libraryScan => libraryScan.LibraryId)
|
||||||
@@ -41,7 +41,7 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
|||||||
.HasConversion<string>()
|
.HasConversion<string>()
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(libraryScan => libraryScan.CreatedOnUtc)
|
builder.Property(libraryScan => libraryScan.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(2);
|
.HasColumnOrder(2);
|
||||||
@@ -58,10 +58,10 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
// Indexes
|
// Indexes.
|
||||||
|
|
||||||
// enables fast lookup of latest non-running scans per library
|
// Enables fast lookup of latest non-running scans per library.
|
||||||
builder.HasIndex(libraryScan => new { libraryScan.LibraryId, libraryScan.Status, libraryScan.CreatedOnUtc })
|
builder.HasIndex(libraryScan => new { libraryScan.LibraryId, libraryScan.Status, libraryScan.CreatedOnUtc })
|
||||||
.IsDescending(true, false, true); // CreatedOnUtc DESC
|
.IsDescending(true, false, true); // CreatedOnUtc DESC.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,10 +18,10 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
|||||||
public void Configure(EntityTypeBuilder<LibraryScanResultEntity> builder)
|
public void Configure(EntityTypeBuilder<LibraryScanResultEntity> builder)
|
||||||
{
|
{
|
||||||
builder.ToTable("LibraryScanResults");
|
builder.ToTable("LibraryScanResults");
|
||||||
// composite key for efficient scan-specific lookups (paths are enforced as UNIQUE within the same scan)
|
// Composite key for efficient scan-specific lookups (paths are enforced as UNIQUE within the same scan).
|
||||||
builder.HasKey(libraryScanResult => new { libraryScanResult.LibraryScanId, libraryScanResult.Path });
|
builder.HasKey(libraryScanResult => new { libraryScanResult.LibraryScanId, libraryScanResult.Path });
|
||||||
|
|
||||||
// one library scan with many library scan results
|
// One library scan with many library scan results.
|
||||||
builder.HasOne(libraryScanResult => libraryScanResult.LibraryScan)
|
builder.HasOne(libraryScanResult => libraryScanResult.LibraryScan)
|
||||||
.WithMany(libraryScan => libraryScan.LibraryScanResults)
|
.WithMany(libraryScan => libraryScan.LibraryScanResults)
|
||||||
.HasForeignKey(libraryScanResult => libraryScanResult.LibraryScanId)
|
.HasForeignKey(libraryScanResult => libraryScanResult.LibraryScanId)
|
||||||
@@ -38,7 +38,7 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
|||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
builder.Property(libraryScanResult => libraryScanResult.ContentHash)
|
builder.Property(libraryScanResult => libraryScanResult.ContentHash)
|
||||||
.HasMaxLength(24) // xxHash128 as Base64
|
.HasMaxLength(24) // xxHash128 as Base64.
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(2);
|
.HasColumnOrder(2);
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
|||||||
.HasMaxLength(10)
|
.HasMaxLength(10)
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
// Indexes
|
// Indexes.
|
||||||
builder.HasIndex(libraryScanResult => new { libraryScanResult.ContentHash, libraryScanResult.FileSize, libraryScanResult.Path });
|
builder.HasIndex(libraryScanResult => new { libraryScanResult.ContentHash, libraryScanResult.FileSize, libraryScanResult.Path });
|
||||||
|
|
||||||
builder.HasIndex(libraryScanResult => libraryScanResult.Path);
|
builder.HasIndex(libraryScanResult => libraryScanResult.Path);
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
|||||||
public void Configure(EntityTypeBuilder<LibraryScanSnapshotEntity> builder)
|
public void Configure(EntityTypeBuilder<LibraryScanSnapshotEntity> builder)
|
||||||
{
|
{
|
||||||
builder.ToTable("LibraryScanSnapshots");
|
builder.ToTable("LibraryScanSnapshots");
|
||||||
// composite key, so that each media library scan snapshot item is uniquely identified within its library by its path
|
// 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 });
|
builder.HasKey(libraryScanSnapshot => new { libraryScanSnapshot.LibraryId, libraryScanSnapshot.Path });
|
||||||
|
|
||||||
// one library with many media library scan snapshot items
|
// One library with many media library scan snapshot items.
|
||||||
builder.HasOne(libraryScanSnapshot => libraryScanSnapshot.Library)
|
builder.HasOne(libraryScanSnapshot => libraryScanSnapshot.Library)
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey(libraryScanSnapshot => libraryScanSnapshot.LibraryId)
|
.HasForeignKey(libraryScanSnapshot => libraryScanSnapshot.LibraryId)
|
||||||
@@ -49,7 +49,7 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.CreatedOnUtc)
|
builder.Property(libraryScanSnapshot => libraryScanSnapshot.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
@@ -66,7 +66,7 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(8);
|
.HasColumnOrder(8);
|
||||||
|
|
||||||
// enables fast lookups of the media library scan snapshot items of a library
|
// Enables fast lookups of the media library scan snapshot items of a library.
|
||||||
builder.HasIndex(libraryScanSnapshot => libraryScanSnapshot.LibraryId);
|
builder.HasIndex(libraryScanSnapshot => libraryScanSnapshot.LibraryId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+3
-3
@@ -18,10 +18,10 @@ public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration<L
|
|||||||
public void Configure(EntityTypeBuilder<LibraryScanStagingResultsEntity> builder)
|
public void Configure(EntityTypeBuilder<LibraryScanStagingResultsEntity> builder)
|
||||||
{
|
{
|
||||||
builder.ToTable("LibraryScanStagingResults");
|
builder.ToTable("LibraryScanStagingResults");
|
||||||
// composite key, so that each media library scan staging result is uniquely identified within its scan by its path
|
// 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 });
|
builder.HasKey(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.Path });
|
||||||
|
|
||||||
// one media library scan with many media library scan staging results
|
// One media library scan with many media library scan staging results.
|
||||||
builder.HasOne<LibraryScanEntity>()
|
builder.HasOne<LibraryScanEntity>()
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey(libraryScanStagingResult => libraryScanStagingResult.LibraryScanId)
|
.HasForeignKey(libraryScanStagingResult => libraryScanStagingResult.LibraryScanId)
|
||||||
@@ -61,7 +61,7 @@ public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration<L
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(7);
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
// enables fast lookups of the staging results of a scan that need their content hashed
|
// Enables fast lookups of the staging results of a scan that need their content hashed.
|
||||||
builder.HasIndex(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.NeedsRehash });
|
builder.HasIndex(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.NeedsRehash });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration<Medi
|
|||||||
builder.ToTable("MediaConsumptionRecords");
|
builder.ToTable("MediaConsumptionRecords");
|
||||||
builder.HasKey(record => record.Id);
|
builder.HasKey(record => record.Id);
|
||||||
builder.Property(record => record.Id)
|
builder.Property(record => record.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// A consumption record belongs to the user that started it, and it is removed with that user.
|
// A consumption record belongs to the user that started it, and it is removed with that user.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class MediaContributorConfiguration : IEntityTypeConfiguration<MediaContr
|
|||||||
builder.ToTable("MediaContributors");
|
builder.ToTable("MediaContributors");
|
||||||
builder.HasKey(contributor => contributor.Id);
|
builder.HasKey(contributor => contributor.Id);
|
||||||
builder.Property(contributor => contributor.Id)
|
builder.Property(contributor => contributor.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(contributor => contributor.DisplayName)
|
builder.Property(contributor => contributor.DisplayName)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -38,7 +38,7 @@ public class MediaContributorConfiguration : IEntityTypeConfiguration<MediaContr
|
|||||||
builder.Property(contributor => contributor.DateOfDeath)
|
builder.Property(contributor => contributor.DateOfDeath)
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(contributor => contributor.CreatedOnUtc)
|
builder.Property(contributor => contributor.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(6);
|
.HasColumnOrder(6);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public class MediaResumePointConfiguration : IEntityTypeConfiguration<MediaResum
|
|||||||
builder.ToTable("MediaResumePoints");
|
builder.ToTable("MediaResumePoints");
|
||||||
builder.HasKey(resumePoint => resumePoint.Id);
|
builder.HasKey(resumePoint => resumePoint.Id);
|
||||||
builder.Property(resumePoint => resumePoint.Id)
|
builder.Property(resumePoint => resumePoint.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// A resume point belongs to the user that owns it, and it is removed with that user.
|
// A resume point belongs to the user that owns it, and it is removed with that user.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class MusicArtworkConfiguration : IEntityTypeConfiguration<MusicArtworkEn
|
|||||||
builder.ToTable("MusicArtwork");
|
builder.ToTable("MusicArtwork");
|
||||||
builder.HasKey(musicArtwork => musicArtwork.Id);
|
builder.HasKey(musicArtwork => musicArtwork.Id);
|
||||||
builder.Property(musicArtwork => musicArtwork.Id)
|
builder.Property(musicArtwork => musicArtwork.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(musicArtwork => musicArtwork.OwnerType)
|
builder.Property(musicArtwork => musicArtwork.OwnerType)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -54,7 +54,7 @@ public class MusicArtworkConfiguration : IEntityTypeConfiguration<MusicArtworkEn
|
|||||||
builder.Property(musicArtwork => musicArtwork.LastUpdateUtc)
|
builder.Property(musicArtwork => musicArtwork.LastUpdateUtc)
|
||||||
.HasColumnOrder(9);
|
.HasColumnOrder(9);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(musicArtwork => musicArtwork.CreatedOnUtc)
|
builder.Property(musicArtwork => musicArtwork.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(10);
|
.HasColumnOrder(10);
|
||||||
|
|||||||
+2
-2
@@ -20,7 +20,7 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio
|
|||||||
builder.ToTable("MusicLibraryScanItemMetadata");
|
builder.ToTable("MusicLibraryScanItemMetadata");
|
||||||
builder.HasKey(musicMetadata => musicMetadata.Id);
|
builder.HasKey(musicMetadata => musicMetadata.Id);
|
||||||
builder.Property(musicMetadata => musicMetadata.Id)
|
builder.Property(musicMetadata => musicMetadata.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(musicMetadata => musicMetadata.LibraryScanId)
|
builder.Property(musicMetadata => musicMetadata.LibraryScanId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -103,6 +103,6 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio
|
|||||||
.HasColumnOrder(31);
|
.HasColumnOrder(31);
|
||||||
|
|
||||||
builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path })
|
builder.HasIndex(musicMetadata => new { musicMetadata.LibraryScanId, musicMetadata.Path })
|
||||||
.IsUnique(); // the metadata of the same physical file cannot be staged twice during the same scan
|
.IsUnique(); // The metadata of the same physical file cannot be staged twice during the same scan.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ public class PermissionConfiguration : IEntityTypeConfiguration<PermissionEntity
|
|||||||
.HasMaxLength(100)
|
.HasMaxLength(100)
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(permission => permission.CreatedOnUtc)
|
builder.Property(permission => permission.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public class PlaylistConfiguration : IEntityTypeConfiguration<PlaylistEntity>
|
|||||||
builder.ToTable("Playlists");
|
builder.ToTable("Playlists");
|
||||||
builder.HasKey(playlist => playlist.Id);
|
builder.HasKey(playlist => playlist.Id);
|
||||||
builder.Property(playlist => playlist.Id)
|
builder.Property(playlist => playlist.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// A playlist belongs to the user that created it, and it is removed with that user.
|
// A playlist belongs to the user that created it, and it is removed with that user.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class PluginConfiguration : IEntityTypeConfiguration<PluginEntity>
|
|||||||
builder.ToTable("Plugins");
|
builder.ToTable("Plugins");
|
||||||
builder.HasKey(plugin => plugin.Id);
|
builder.HasKey(plugin => plugin.Id);
|
||||||
builder.Property(plugin => plugin.Id)
|
builder.Property(plugin => plugin.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
builder.Property(plugin => plugin.Name)
|
builder.Property(plugin => plugin.Name)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
@@ -51,7 +51,7 @@ public class PluginConfiguration : IEntityTypeConfiguration<PluginEntity>
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(8);
|
.HasColumnOrder(8);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(plugin => plugin.CreatedBy)
|
builder.Property(plugin => plugin.CreatedBy)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(9);
|
.HasColumnOrder(9);
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ public class RoleConfiguration : IEntityTypeConfiguration<RoleEntity>
|
|||||||
.HasMaxLength(100)
|
.HasMaxLength(100)
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(role => role.CreatedOnUtc)
|
builder.Property(role => role.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|||||||
@@ -19,26 +19,26 @@ public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissi
|
|||||||
{
|
{
|
||||||
builder.ToTable("RolePermissions");
|
builder.ToTable("RolePermissions");
|
||||||
|
|
||||||
// composite primary key
|
// Composite primary key.
|
||||||
builder.HasKey(rolePermission => new { rolePermission.RoleId, rolePermission.PermissionId });
|
builder.HasKey(rolePermission => new { rolePermission.RoleId, rolePermission.PermissionId });
|
||||||
|
|
||||||
builder.Ignore(rolePermission => rolePermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
|
builder.Ignore(rolePermission => rolePermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id.
|
||||||
|
|
||||||
// foreign key: Role
|
// Foreign key: Role.
|
||||||
builder.HasOne(rolePermission => rolePermission.Role)
|
builder.HasOne(rolePermission => rolePermission.Role)
|
||||||
.WithMany(user => user.RolePermissions)
|
.WithMany(user => user.RolePermissions)
|
||||||
.HasForeignKey(rolePermission => rolePermission.RoleId)
|
.HasForeignKey(rolePermission => rolePermission.RoleId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a Role deletes associated RolePermission
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a Role deletes associated RolePermission.
|
||||||
|
|
||||||
// foreign key: Permission
|
// Foreign key: Permission.
|
||||||
builder.HasOne(rolePermission => rolePermission.Permission)
|
builder.HasOne(rolePermission => rolePermission.Permission)
|
||||||
.WithMany(role => role.RolePermissions)
|
.WithMany(role => role.RolePermissions)
|
||||||
.HasForeignKey(rolePermission => rolePermission.PermissionId)
|
.HasForeignKey(rolePermission => rolePermission.PermissionId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a Permission deletes associated RolePermission
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a Permission deletes associated RolePermission.
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(rolePermission => rolePermission.CreatedOnUtc)
|
builder.Property(rolePermission => rolePermission.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
@@ -55,7 +55,7 @@ public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissi
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
// indexes
|
// Indexes.
|
||||||
builder.HasIndex(userRole => new { userRole.RoleId, userRole.PermissionId })
|
builder.HasIndex(userRole => new { userRole.RoleId, userRole.PermissionId })
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public class ScheduledJobConfiguration : IEntityTypeConfiguration<ScheduledJobEn
|
|||||||
builder.ToTable("ScheduledJobs");
|
builder.ToTable("ScheduledJobs");
|
||||||
builder.HasKey(scheduledJob => scheduledJob.Id);
|
builder.HasKey(scheduledJob => scheduledJob.Id);
|
||||||
builder.Property(scheduledJob => scheduledJob.Id)
|
builder.Property(scheduledJob => scheduledJob.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(scheduledJob => scheduledJob.Name)
|
builder.Property(scheduledJob => scheduledJob.Name)
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ public class SchedulerDisplayPreferencesConfiguration : IEntityTypeConfiguration
|
|||||||
builder.ToTable("SchedulerDisplayPreferences");
|
builder.ToTable("SchedulerDisplayPreferences");
|
||||||
builder.HasKey(preferences => preferences.Id);
|
builder.HasKey(preferences => preferences.Id);
|
||||||
builder.Property(preferences => preferences.Id)
|
builder.Property(preferences => preferences.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(preferences => preferences.UserId)
|
builder.Property(preferences => preferences.UserId)
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
|||||||
builder.ToTable("Themes");
|
builder.ToTable("Themes");
|
||||||
builder.HasKey(theme => theme.Id);
|
builder.HasKey(theme => theme.Id);
|
||||||
builder.Property(theme => theme.Id)
|
builder.Property(theme => theme.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the install, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the install, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// the manifest id is the business key used by the clients, so it must be unique
|
// The manifest id is the business key used by the clients, so it must be unique.
|
||||||
builder.HasIndex(theme => theme.ThemeId)
|
builder.HasIndex(theme => theme.ThemeId)
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
|||||||
.HasConversion<string>()
|
.HasConversion<string>()
|
||||||
.HasColumnOrder(7);
|
.HasColumnOrder(7);
|
||||||
|
|
||||||
// at most one theme can be current: the filtered unique index guarantees it at the database level, since every row that is not current has a null value here, and nulls are allowed to repeat
|
// At most one theme can be current: the filtered unique index guarantees it at the database level, since every row that is not current has a null value here, and nulls are allowed to repeat.
|
||||||
builder.HasIndex(theme => theme.IsCurrent)
|
builder.HasIndex(theme => theme.IsCurrent)
|
||||||
.IsUnique()
|
.IsUnique()
|
||||||
.HasFilter("IsCurrent = 1");
|
.HasFilter("IsCurrent = 1");
|
||||||
@@ -80,7 +80,7 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(10);
|
.HasColumnOrder(10);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(theme => theme.CreatedOnUtc)
|
builder.Property(theme => theme.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(11);
|
.HasColumnOrder(11);
|
||||||
|
|||||||
@@ -167,8 +167,8 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
|
|||||||
.HasForeignKey(track => track.AlbumId)
|
.HasForeignKey(track => track.AlbumId)
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
|
||||||
// since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
// Since Tag and Genre are Domain ValueObjects (no identity), but we also don't want to have duplicates,
|
||||||
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key
|
// we need to configure them as many-to-many relationships, where the tag/genre itself is the primary key.
|
||||||
builder.HasMany(track => track.Tags)
|
builder.HasMany(track => track.Tags)
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.UsingEntity<Dictionary<string, object>>(
|
.UsingEntity<Dictionary<string, object>>(
|
||||||
@@ -296,7 +296,7 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
|
|||||||
|
|
||||||
builder.HasIndex(track => new { track.AlbumId, track.TrackNumber });
|
builder.HasIndex(track => new { track.AlbumId, track.TrackNumber });
|
||||||
builder.HasIndex(track => new { track.LibraryId, track.Path })
|
builder.HasIndex(track => new { track.LibraryId, track.Path })
|
||||||
.IsUnique(); // the same physical track file cannot appear twice in the same library
|
.IsUnique(); // The same physical track file cannot appear twice in the same library.
|
||||||
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
|
// The deleted items page filters by library and deletion state, and orders by the stored deletion time, the title and the Id, so the
|
||||||
// filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it.
|
// filtered index follows the same order and no temporary B-tree is needed for the sort, while visible rows add no entries to it.
|
||||||
builder.HasIndex(track => new { track.LibraryId, track.IsDeleted, track.DeletedOnUtc, track.Title, track.Id })
|
builder.HasIndex(track => new { track.LibraryId, track.IsDeleted, track.DeletedOnUtc, track.Title, track.Id })
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public class TrackContributorConfiguration : IEntityTypeConfiguration<TrackContr
|
|||||||
builder.ToTable("TrackContributors");
|
builder.ToTable("TrackContributors");
|
||||||
builder.HasKey(trackContributor => trackContributor.Id);
|
builder.HasKey(trackContributor => trackContributor.Id);
|
||||||
builder.Property(trackContributor => trackContributor.Id)
|
builder.Property(trackContributor => trackContributor.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(trackContributor => trackContributor.TrackId)
|
builder.Property(trackContributor => trackContributor.TrackId)
|
||||||
@@ -35,7 +35,7 @@ public class TrackContributorConfiguration : IEntityTypeConfiguration<TrackContr
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(3);
|
.HasColumnOrder(3);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(trackContributor => trackContributor.CreatedOnUtc)
|
builder.Property(trackContributor => trackContributor.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
|||||||
builder.ToTable("Users");
|
builder.ToTable("Users");
|
||||||
builder.HasKey(user => user.Id);
|
builder.HasKey(user => user.Id);
|
||||||
builder.Property(user => user.Id)
|
builder.Property(user => user.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
builder.Property(user => user.Username)
|
builder.Property(user => user.Username)
|
||||||
@@ -45,11 +45,11 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
|
|
||||||
// relationships
|
// Relationships.
|
||||||
builder.HasMany(user => user.Libraries)
|
builder.HasMany(user => user.Libraries)
|
||||||
.WithOne(library => library.User)
|
.WithOne(library => library.User)
|
||||||
.HasForeignKey(library => library.UserId)
|
.HasForeignKey(library => library.UserId)
|
||||||
.IsRequired() // a library must have a user
|
.IsRequired() // A library must have a user.
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
|
||||||
builder.HasOne(user => user.UserRole)
|
builder.HasOne(user => user.UserRole)
|
||||||
@@ -63,7 +63,7 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
|||||||
.HasForeignKey(userPermission => userPermission.UserId)
|
.HasForeignKey(userPermission => userPermission.UserId)
|
||||||
.OnDelete(DeleteBehavior.Cascade);
|
.OnDelete(DeleteBehavior.Cascade);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(user => user.CreatedOnUtc)
|
builder.Property(user => user.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(6);
|
.HasColumnOrder(6);
|
||||||
@@ -80,8 +80,8 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(9);
|
.HasColumnOrder(9);
|
||||||
|
|
||||||
// indexes
|
// Indexes.
|
||||||
builder.HasIndex(user => user.Username)
|
builder.HasIndex(user => user.Username)
|
||||||
.IsUnique(); // queried frequently
|
.IsUnique(); // Queried frequently.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,26 +19,26 @@ public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissi
|
|||||||
{
|
{
|
||||||
builder.ToTable("UserPermissions");
|
builder.ToTable("UserPermissions");
|
||||||
|
|
||||||
// composite primary key
|
// Composite primary key.
|
||||||
builder.HasKey(userPermission => new { userPermission.UserId, userPermission.PermissionId });
|
builder.HasKey(userPermission => new { userPermission.UserId, userPermission.PermissionId });
|
||||||
|
|
||||||
builder.Ignore(userPermission => userPermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
|
builder.Ignore(userPermission => userPermission.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id.
|
||||||
|
|
||||||
// foreign key: User
|
// Foreign key: User.
|
||||||
builder.HasOne(userPermission => userPermission.User)
|
builder.HasOne(userPermission => userPermission.User)
|
||||||
.WithMany(user => user.UserPermissions)
|
.WithMany(user => user.UserPermissions)
|
||||||
.HasForeignKey(userPermission => userPermission.UserId)
|
.HasForeignKey(userPermission => userPermission.UserId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserPermissions
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a User deletes associated UserPermissions.
|
||||||
|
|
||||||
// foreign key: Permission
|
// Foreign key: Permission.
|
||||||
builder.HasOne(userPermission => userPermission.Permission)
|
builder.HasOne(userPermission => userPermission.Permission)
|
||||||
.WithMany(role => role.UserPermissions)
|
.WithMany(role => role.UserPermissions)
|
||||||
.HasForeignKey(userPermission => userPermission.PermissionId)
|
.HasForeignKey(userPermission => userPermission.PermissionId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a Permission deletes associated UserPermissions
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a Permission deletes associated UserPermissions.
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(userPermission => userPermission.CreatedOnUtc)
|
builder.Property(userPermission => userPermission.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
@@ -55,7 +55,7 @@ public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissi
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
// indexes
|
// Indexes.
|
||||||
builder.HasIndex(userRole => new { userRole.UserId, userRole.PermissionId })
|
builder.HasIndex(userRole => new { userRole.UserId, userRole.PermissionId })
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,26 +19,26 @@ public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
|
|||||||
{
|
{
|
||||||
builder.ToTable("UserRoles");
|
builder.ToTable("UserRoles");
|
||||||
|
|
||||||
// primary key
|
// Primary key.
|
||||||
builder.HasKey(userRole => userRole.UserId );
|
builder.HasKey(userRole => userRole.UserId );
|
||||||
|
|
||||||
builder.Ignore(userRole => userRole.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id
|
builder.Ignore(userRole => userRole.Id); // Id is only needed as a generic constraint for the repository, but this entity uses a composite key as Id.
|
||||||
|
|
||||||
// foreign key: User (one-to-one relationship)
|
// Foreign key: User (one-to-one relationship).
|
||||||
builder.HasOne(userRole => userRole.User)
|
builder.HasOne(userRole => userRole.User)
|
||||||
.WithOne(user => user.UserRole)
|
.WithOne(user => user.UserRole)
|
||||||
.HasForeignKey<UserRoleEntity>(userRole => userRole.UserId)
|
.HasForeignKey<UserRoleEntity>(userRole => userRole.UserId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a User deletes associated UserRole
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a User deletes associated UserRole.
|
||||||
|
|
||||||
// foreign key: Role (many-to-one relationship)
|
// Foreign key: Role (many-to-one relationship).
|
||||||
builder.HasOne(userRole => userRole.Role)
|
builder.HasOne(userRole => userRole.Role)
|
||||||
.WithMany(role => role.UserRoles)
|
.WithMany(role => role.UserRoles)
|
||||||
.HasForeignKey(userRole => userRole.RoleId)
|
.HasForeignKey(userRole => userRole.RoleId)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.OnDelete(DeleteBehavior.Cascade); // deleting a Role deletes associated UserRoles
|
.OnDelete(DeleteBehavior.Cascade); // Deleting a Role deletes associated UserRoles.
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(userRole => userRole.CreatedOnUtc)
|
builder.Property(userRole => userRole.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(1);
|
.HasColumnOrder(1);
|
||||||
@@ -55,7 +55,7 @@ public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(4);
|
.HasColumnOrder(4);
|
||||||
|
|
||||||
// indexes
|
// Indexes.
|
||||||
builder.HasIndex(userRole => new { userRole.UserId, userRole.RoleId })
|
builder.HasIndex(userRole => new { userRole.UserId, userRole.RoleId })
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
|||||||
builder.ToTable("UserSettings");
|
builder.ToTable("UserSettings");
|
||||||
builder.HasKey(settings => settings.Id);
|
builder.HasKey(settings => settings.Id);
|
||||||
builder.Property(settings => settings.Id)
|
builder.Property(settings => settings.Id)
|
||||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||||
.HasColumnOrder(0);
|
.HasColumnOrder(0);
|
||||||
|
|
||||||
// one user with one set of settings
|
// One user with one set of settings.
|
||||||
builder.HasOne<UserEntity>()
|
builder.HasOne<UserEntity>()
|
||||||
.WithOne()
|
.WithOne()
|
||||||
.HasForeignKey<UserSettingsEntity>(settings => settings.UserId)
|
.HasForeignKey<UserSettingsEntity>(settings => settings.UserId)
|
||||||
@@ -130,7 +130,7 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
|||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(29);
|
.HasColumnOrder(29);
|
||||||
|
|
||||||
// audit
|
// Audit.
|
||||||
builder.Property(settings => settings.CreatedOnUtc)
|
builder.Property(settings => settings.CreatedOnUtc)
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnOrder(5);
|
.HasColumnOrder(5);
|
||||||
@@ -147,7 +147,7 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
|||||||
.HasDefaultValue(null)
|
.HasDefaultValue(null)
|
||||||
.HasColumnOrder(8);
|
.HasColumnOrder(8);
|
||||||
|
|
||||||
// one user can have at most one set of settings
|
// One user can have at most one set of settings.
|
||||||
builder.HasIndex(settings => settings.UserId)
|
builder.HasIndex(settings => settings.UserId)
|
||||||
.IsUnique();
|
.IsUnique();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ using System.Reflection;
|
|||||||
namespace Lumina.DataAccess.Common.DependencyInjection;
|
namespace Lumina.DataAccess.Common.DependencyInjection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Utility class for registering the services of the Data Access layer into the Dependency Injection container..
|
/// Utility class for registering the services of the Data Access layer into the Dependency Injection container.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[ExcludeFromCodeCoverage]
|
[ExcludeFromCodeCoverage]
|
||||||
public static class DataAccessLayerServices
|
public static class DataAccessLayerServices
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
|||||||
Guid? userId = _currentUserService.UserId;
|
Guid? userId = _currentUserService.UserId;
|
||||||
DateTime utcNow = _dateTimeProvider.UtcNow;
|
DateTime utcNow = _dateTimeProvider.UtcNow;
|
||||||
|
|
||||||
// retrieve all entities implementing IAuditableEntity that are being tracked and have either Added or Modified state
|
// Retrieve all entities implementing IAuditableEntity that are being tracked and have either Added or Modified state.
|
||||||
foreach (EntityEntry<IAuditableEntity> entry in context.ChangeTracker.Entries<IAuditableEntity>())
|
foreach (EntityEntry<IAuditableEntity> entry in context.ChangeTracker.Entries<IAuditableEntity>())
|
||||||
{
|
{
|
||||||
if (entry.State == EntityState.Added)
|
if (entry.State == EntityState.Added)
|
||||||
@@ -100,12 +100,12 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
|||||||
/// <param name="utcNow">The current UTC timestamp.</param>
|
/// <param name="utcNow">The current UTC timestamp.</param>
|
||||||
private static void SetModificationProperties(EntityEntry<IAuditableEntity> entry, Guid? userId, DateTime utcNow)
|
private static void SetModificationProperties(EntityEntry<IAuditableEntity> entry, Guid? userId, DateTime utcNow)
|
||||||
{
|
{
|
||||||
// prevent modification of creation properties
|
// Prevent modification of creation properties.
|
||||||
entry.Property(auditableEntity => auditableEntity.CreatedOnUtc).IsModified = false;
|
entry.Property(auditableEntity => auditableEntity.CreatedOnUtc).IsModified = false;
|
||||||
entry.Property(auditableEntity => auditableEntity.CreatedBy).IsModified = false;
|
entry.Property(auditableEntity => auditableEntity.CreatedBy).IsModified = false;
|
||||||
|
|
||||||
// set modification properties
|
// Set modification properties.
|
||||||
entry.Entity.UpdatedOnUtc = utcNow;
|
entry.Entity.UpdatedOnUtc = utcNow;
|
||||||
entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id
|
entry.Entity.UpdatedBy = userId ?? Guid.Parse("11111111-1111-1111-1111-111111111111"); // "SYSTEM" user Id.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -98,8 +98,8 @@ namespace Lumina.DataAccess.Common.Migrations
|
|||||||
onDelete: ReferentialAction.Cascade);
|
onDelete: ReferentialAction.Cascade);
|
||||||
});
|
});
|
||||||
|
|
||||||
// backfill the artwork of the books that already had a cover, so that the stored covers are preserved as enriched cover artwork
|
// Backfill the artwork of the books that already had a cover, so that the stored covers are preserved as enriched cover artwork
|
||||||
// before the CoverImagePath column is dropped
|
// before the CoverImagePath column is dropped.
|
||||||
migrationBuilder.Sql("""
|
migrationBuilder.Sql("""
|
||||||
INSERT INTO BookArtwork (Id, BookId, ArtworkType, Ordinal, FileName, ContentHash, Status, Provider, LastUpdateUtc, CreatedOnUtc, CreatedBy, UpdatedOnUtc, UpdatedBy)
|
INSERT INTO BookArtwork (Id, BookId, ArtworkType, Ordinal, FileName, ContentHash, Status, Provider, LastUpdateUtc, CreatedOnUtc, CreatedBy, UpdatedOnUtc, UpdatedBy)
|
||||||
SELECT lower(hex(randomblob(16))), Id, 'Cover', 0, CoverImagePath, 0, 'Enriched', NULL, NULL, datetime('now'), '00000000-0000-0000-0000-000000000000', NULL, NULL
|
SELECT lower(hex(randomblob(16))), Id, 'Cover', 0, CoverImagePath, 0, 'Enriched', NULL, NULL, datetime('now'), '00000000-0000-0000-0000-000000000000', NULL, NULL
|
||||||
|
|||||||
+3
-3
@@ -22,7 +22,7 @@ namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerprintRepository
|
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 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;
|
private readonly LuminaDbContext _luminaDbContext;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -63,14 +63,14 @@ internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerp
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Updated>> UpsertRangeAsync(IReadOnlyCollection<DirectoryScanFingerprintEntity> entities, CancellationToken cancellationToken)
|
public async Task<Result<Updated>> UpsertRangeAsync(IReadOnlyCollection<DirectoryScanFingerprintEntity> entities, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// nothing to upsert for an empty collection
|
// Nothing to upsert for an empty collection.
|
||||||
if (entities.Count == 0)
|
if (entities.Count == 0)
|
||||||
return Result.Updated;
|
return Result.Updated;
|
||||||
|
|
||||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||||
List<DirectoryScanFingerprintEntity> remainingEntities = [.. entities];
|
List<DirectoryScanFingerprintEntity> remainingEntities = [.. entities];
|
||||||
// upsert the entities in batches, to keep the number of bound parameters of a single UPSERT statement under the SQLite parameter limit
|
// 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)
|
while (remainingEntities.Count > 0)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|||||||
@@ -103,10 +103,10 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
|||||||
DateTime nowUtc = DateTime.UtcNow;
|
DateTime nowUtc = DateTime.UtcNow;
|
||||||
object parameters = new { libraryId, scanId, userId, nowUtc };
|
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 upper case hex (hex(randomblob(16))), which the storage layer parses as a Guid;
|
// The Id of the inserted rows is generated in SQL as a random 16 byte value formatted as upper case 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
|
// 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
|
// 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 = """
|
const string AUDIT_DELETED_SQL = """
|
||||||
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, Ticks)
|
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, Ticks)
|
||||||
SELECT hex(randomblob(16)), @scanId, 'Deleted', snapshot.Path, snapshot.ContentHash, snapshot.FileSize, snapshot.Ticks
|
SELECT hex(randomblob(16)), @scanId, 'Deleted', snapshot.Path, snapshot.ContentHash, snapshot.FileSize, snapshot.Ticks
|
||||||
@@ -124,7 +124,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
|||||||
|
|
||||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||||
|
|
||||||
// add an audit entry for every new or changed media library scan staging result
|
// Add an audit entry for every new or changed media library scan staging result.
|
||||||
const string AUDIT_CHANGED_SQL = """
|
const string AUDIT_CHANGED_SQL = """
|
||||||
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, Ticks)
|
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
|
SELECT hex(randomblob(16)), @scanId, CASE WHEN staging.IsNew = 1 THEN 'New' ELSE 'Modified' END, staging.Path, staging.ContentHash, staging.Size, staging.Ticks
|
||||||
@@ -137,7 +137,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
|||||||
|
|
||||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
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
|
// 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 = """
|
const string DELETE_MISSING_SQL = """
|
||||||
DELETE FROM LibraryScanSnapshots
|
DELETE FROM LibraryScanSnapshots
|
||||||
WHERE LibraryId = @libraryId
|
WHERE LibraryId = @libraryId
|
||||||
@@ -153,7 +153,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
|||||||
|
|
||||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
||||||
|
|
||||||
// upsert the new and changed media library scan staging results into the media library scan snapshot
|
// Upsert the new and changed media library scan staging results into the media library scan snapshot.
|
||||||
const string UPSERT_SQL = """
|
const string UPSERT_SQL = """
|
||||||
INSERT INTO LibraryScanSnapshots (Id, LibraryId, Path, ContentHash, FileSize, Ticks, CreatedOnUtc, CreatedBy, UpdatedOnUtc, UpdatedBy)
|
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
|
SELECT hex(randomblob(16)), @libraryId, staging.Path, staging.ContentHash, staging.Size, staging.Ticks, @nowUtc, @userId, NULL, NULL
|
||||||
@@ -172,7 +172,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
|||||||
|
|
||||||
await connection.ExecuteAsync(command).ConfigureAwait(false);
|
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
|
// 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;";
|
const string CLEAR_STAGING_SQL = "DELETE FROM LibraryScanStagingResults WHERE LibraryScanId = @scanId;";
|
||||||
|
|
||||||
command = new(CLEAR_STAGING_SQL, parameters, transaction);
|
command = new(CLEAR_STAGING_SQL, parameters, transaction);
|
||||||
|
|||||||
+5
-5
@@ -23,7 +23,7 @@ namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingResultsRepository
|
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 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;
|
private readonly LuminaDbContext _luminaDbContext;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -43,14 +43,14 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||||
public async Task<Result<Created>> InsertRangeAsync(IReadOnlyCollection<LibraryScanStagingResultsEntity> entities, CancellationToken cancellationToken)
|
public async Task<Result<Created>> InsertRangeAsync(IReadOnlyCollection<LibraryScanStagingResultsEntity> entities, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// nothing to insert for an empty collection
|
// Nothing to insert for an empty collection.
|
||||||
if (entities.Count == 0)
|
if (entities.Count == 0)
|
||||||
return Result.Created;
|
return Result.Created;
|
||||||
|
|
||||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||||
List<LibraryScanStagingResultsEntity> remainingEntities = [.. entities];
|
List<LibraryScanStagingResultsEntity> remainingEntities = [.. entities];
|
||||||
// insert the entities in batches, to keep the number of bound parameters of a single INSERT statement under the SQLite parameter limit
|
// 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)
|
while (remainingEntities.Count > 0)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -73,8 +73,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
|
|||||||
public async Task<Result<Updated>> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken)
|
public async Task<Result<Updated>> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
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:
|
// 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
|
// 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 = """
|
const string MARK_CHANGES_SQL = """
|
||||||
UPDATE LibraryScanStagingResults AS staging
|
UPDATE LibraryScanStagingResults AS staging
|
||||||
SET ContentHash = COALESCE(snapshot.ContentHash, 0),
|
SET ContentHash = COALESCE(snapshot.ContentHash, 0),
|
||||||
|
|||||||
+1
-1
@@ -65,7 +65,7 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
|
|||||||
/// <returns>An <see cref="Result{TValue}"/> containing either the existing or newly created <see cref="MediaContributorEntity"/>, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> containing either the existing or newly created <see cref="MediaContributorEntity"/>, or an error.</returns>
|
||||||
public async Task<Result<MediaContributorEntity>> FindOrCreateByDisplayNameAsync(string displayName, string? legalName, CancellationToken cancellationToken)
|
public async Task<Result<MediaContributorEntity>> FindOrCreateByDisplayNameAsync(string displayName, string? legalName, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// the comparison is case-insensitive, so that "Stephen King" and "stephen king" are never treated as distinct contributors
|
// The comparison is case-insensitive, so that "Stephen King" and "stephen king" are never treated as distinct contributors.
|
||||||
string normalizedDisplayName = displayName.ToLowerInvariant();
|
string normalizedDisplayName = displayName.ToLowerInvariant();
|
||||||
|
|
||||||
// Contributors added earlier in the same unit of work are not returned by a database query, so the change tracker is consulted
|
// Contributors added earlier in the same unit of work are not returned by a database query, so the change tracker is consulted
|
||||||
|
|||||||
@@ -997,7 +997,7 @@ internal sealed class PlaylistRepository : IPlaylistRepository
|
|||||||
/// <returns><see langword="true"/> for a unique constraint violation, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> for a unique constraint violation, <see langword="false"/> otherwise.</returns>
|
||||||
private static bool IsUniqueConstraintViolation(SqliteException exception)
|
private static bool IsUniqueConstraintViolation(SqliteException exception)
|
||||||
{
|
{
|
||||||
return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE.
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -1007,7 +1007,7 @@ internal sealed class PlaylistRepository : IPlaylistRepository
|
|||||||
/// <returns><see langword="true"/> for a busy or locked database, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> for a busy or locked database, <see langword="false"/> otherwise.</returns>
|
||||||
private static bool IsConcurrencyConflict(SqliteException exception)
|
private static bool IsConcurrencyConflict(SqliteException exception)
|
||||||
{
|
{
|
||||||
return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED
|
return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED.
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+1
-1
@@ -69,7 +69,7 @@ internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderC
|
|||||||
_luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
_luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// update only the mutable fields, preserving the Id of the existing configuration
|
// Update only the mutable fields, preserving the Id of the existing configuration.
|
||||||
existingConfiguration.LibraryId = configuration.LibraryId;
|
existingConfiguration.LibraryId = configuration.LibraryId;
|
||||||
existingConfiguration.PluginId = configuration.PluginId;
|
existingConfiguration.PluginId = configuration.PluginId;
|
||||||
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
||||||
|
|||||||
+1
-1
@@ -69,7 +69,7 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM
|
|||||||
_luminaDbContext.LibraryMetadataProviderConfigurations.Add(configuration);
|
_luminaDbContext.LibraryMetadataProviderConfigurations.Add(configuration);
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// update only the mutable fields, preserving the Id of the existing configuration
|
// Update only the mutable fields, preserving the Id of the existing configuration.
|
||||||
existingConfiguration.LibraryId = configuration.LibraryId;
|
existingConfiguration.LibraryId = configuration.LibraryId;
|
||||||
existingConfiguration.PluginId = configuration.PluginId;
|
existingConfiguration.PluginId = configuration.PluginId;
|
||||||
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
||||||
|
|||||||
@@ -503,7 +503,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
|||||||
{
|
{
|
||||||
// SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart.
|
// SQLite reports a generic constraint failure code for several constraints, so the extended code is used to tell a unique violation apart.
|
||||||
return exception.InnerException is SqliteException sqliteException
|
return exception.InnerException is SqliteException sqliteException
|
||||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE.
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -523,7 +523,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
|||||||
/// <returns><see langword="true"/> if the database is busy or locked, <see langword="false"/> otherwise.</returns>
|
/// <returns><see langword="true"/> if the database is busy or locked, <see langword="false"/> otherwise.</returns>
|
||||||
private static bool IsSqliteBusyOrLocked(SqliteException exception)
|
private static bool IsSqliteBusyOrLocked(SqliteException exception)
|
||||||
{
|
{
|
||||||
return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED
|
return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED.
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -7,13 +7,13 @@ public enum IsbnFormat
|
|||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The 10-digit ISBN format used for books published before 2007.
|
/// The 10-digit ISBN format used for books published before 2007.
|
||||||
/// Example: 0-306-40615-2
|
/// Example: 0-306-40615-2.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Isbn10,
|
Isbn10,
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The 13-digit ISBN format introduced in 2007, now the standard for all new books.
|
/// The 13-digit ISBN format introduced in 2007, now the standard for all new books.
|
||||||
/// Example: 978-0-306-40615-7
|
/// Example: 978-0-306-40615-7.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Isbn13
|
Isbn13
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Common;
|
namespace Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Enumeration for the sort order
|
/// Enumeration for the sort order.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public enum SortOrder
|
public enum SortOrder
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ public class ReleaseInfo : ValueObject
|
|||||||
public Optional<ReleaseCountry> ReleaseCountry { get; }
|
public Optional<ReleaseCountry> ReleaseCountry { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0")
|
/// Gets the optional release version or edition. (e.g. "Original", "Director's Cut", "2.0").
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Optional<string> ReleaseVersion { get; }
|
public Optional<string> ReleaseVersion { get; }
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -214,7 +214,7 @@ public sealed class Album : Entity<AlbumId>
|
|||||||
contributors,
|
contributors,
|
||||||
ratings,
|
ratings,
|
||||||
tracks,
|
tracks,
|
||||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider
|
DateTime.UtcNow, // TODO: should be IDateTimeProvider.
|
||||||
Optional<DateTime>.None());
|
Optional<DateTime>.None());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +315,7 @@ public sealed class Album : Entity<AlbumId>
|
|||||||
/// <param name="contributors">The media contributors of the album.</param>
|
/// <param name="contributors">The media contributors of the album.</param>
|
||||||
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_contributors.Clear();
|
_contributors.Clear();
|
||||||
_contributors.AddRange(contributors);
|
_contributors.AddRange(contributors);
|
||||||
}
|
}
|
||||||
@@ -326,7 +326,7 @@ public sealed class Album : Entity<AlbumId>
|
|||||||
/// <param name="ratings">The ratings of the album.</param>
|
/// <param name="ratings">The ratings of the album.</param>
|
||||||
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_ratings.Clear();
|
_ratings.Clear();
|
||||||
_ratings.AddRange(ratings);
|
_ratings.AddRange(ratings);
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -226,7 +226,7 @@ public sealed class Track : Entity<TrackId>
|
|||||||
musicBrainzTrackId,
|
musicBrainzTrackId,
|
||||||
contributors,
|
contributors,
|
||||||
ratings,
|
ratings,
|
||||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider
|
DateTime.UtcNow, // TODO: should be IDateTimeProvider.
|
||||||
Optional<DateTime>.None());
|
Optional<DateTime>.None());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,7 +304,7 @@ public sealed class Track : Entity<TrackId>
|
|||||||
/// <param name="moods">The moods of the track.</param>
|
/// <param name="moods">The moods of the track.</param>
|
||||||
internal void UpdateMoods(IReadOnlyCollection<Mood> moods)
|
internal void UpdateMoods(IReadOnlyCollection<Mood> moods)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_moods.Clear();
|
_moods.Clear();
|
||||||
_moods.AddRange(moods);
|
_moods.AddRange(moods);
|
||||||
}
|
}
|
||||||
@@ -315,7 +315,7 @@ public sealed class Track : Entity<TrackId>
|
|||||||
/// <param name="isrcs">The ISRCs of the track.</param>
|
/// <param name="isrcs">The ISRCs of the track.</param>
|
||||||
internal void UpdateIsrcs(IReadOnlyCollection<Isrc> isrcs)
|
internal void UpdateIsrcs(IReadOnlyCollection<Isrc> isrcs)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_isrcs.Clear();
|
_isrcs.Clear();
|
||||||
_isrcs.AddRange(isrcs);
|
_isrcs.AddRange(isrcs);
|
||||||
}
|
}
|
||||||
@@ -326,7 +326,7 @@ public sealed class Track : Entity<TrackId>
|
|||||||
/// <param name="contributors">The media contributors of the track.</param>
|
/// <param name="contributors">The media contributors of the track.</param>
|
||||||
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
internal void UpdateContributors(IReadOnlyCollection<MusicMediaContributor> contributors)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_contributors.Clear();
|
_contributors.Clear();
|
||||||
_contributors.AddRange(contributors);
|
_contributors.AddRange(contributors);
|
||||||
}
|
}
|
||||||
@@ -337,7 +337,7 @@ public sealed class Track : Entity<TrackId>
|
|||||||
/// <param name="ratings">The ratings of the track.</param>
|
/// <param name="ratings">The ratings of the track.</param>
|
||||||
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
internal void UpdateRatings(IReadOnlyCollection<AudioRating> ratings)
|
||||||
{
|
{
|
||||||
// replace the contents of the collection in place, preserving the readonly reference invariants of the entity
|
// Replace the contents of the collection in place, preserving the readonly reference invariants of the entity.
|
||||||
_ratings.Clear();
|
_ratings.Clear();
|
||||||
_ratings.AddRange(ratings);
|
_ratings.AddRange(ratings);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -67,7 +67,7 @@ public sealed class File : FileSystemItem
|
|||||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
||||||
bool isHidden = false)
|
bool isHidden = false)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
||||||
if (createPathResult.IsFailure)
|
if (createPathResult.IsFailure)
|
||||||
return createPathResult.Errors;
|
return createPathResult.Errors;
|
||||||
@@ -108,7 +108,7 @@ public sealed class File : FileSystemItem
|
|||||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
||||||
bool isHidden = false)
|
bool isHidden = false)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
File newFile = new(
|
File newFile = new(
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
|
|||||||
+2
-2
@@ -45,7 +45,7 @@ public sealed class WindowsRootItem : FileSystemItem
|
|||||||
string name,
|
string name,
|
||||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
||||||
if (createPathResult.IsFailure)
|
if (createPathResult.IsFailure)
|
||||||
return createPathResult.Errors;
|
return createPathResult.Errors;
|
||||||
@@ -72,7 +72,7 @@ public sealed class WindowsRootItem : FileSystemItem
|
|||||||
string name,
|
string name,
|
||||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
WindowsRootItem newFile = new(
|
WindowsRootItem newFile = new(
|
||||||
id,
|
id,
|
||||||
name);
|
name);
|
||||||
|
|||||||
+1
-1
@@ -136,7 +136,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates a new directory with the specified name, at the specified path.
|
/// Creates a new directory with the specified name, at the specified path.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="path">The path where the directory will be created..</param>
|
/// <param name="path">The path where the directory will be created.</param>
|
||||||
/// <param name="name">The name of the directory that will be created.</param>
|
/// <param name="name">The name of the directory that will be created.</param>
|
||||||
/// <returns>An <see cref="Result{TValue}"/> containing either the path of a created directory, or an error.</returns>
|
/// <returns>An <see cref="Result{TValue}"/> containing either the path of a created directory, or an error.</returns>
|
||||||
public Result<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name)
|
public Result<FileSystemPathId> CreateDirectory(FileSystemPathId path, string name)
|
||||||
|
|||||||
+3
-3
@@ -15,7 +15,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Service for file system permissions.
|
/// Service for file system permissions.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: Refactor towards abstractions that would allow testing.
|
internal class FileSystemPermissionsService : IFileSystemPermissionsService // TODO: refactor towards abstractions that would allow testing.
|
||||||
{
|
{
|
||||||
private readonly IPlatformContextManager _platformContextManager;
|
private readonly IPlatformContextManager _platformContextManager;
|
||||||
|
|
||||||
@@ -41,9 +41,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T
|
|||||||
if (platformType == PlatformType.Unix)
|
if (platformType == PlatformType.Unix)
|
||||||
return CanAccessPathUnix(path.Path, accessMode);
|
return CanAccessPathUnix(path.Path, accessMode);
|
||||||
else if (platformType == PlatformType.Windows)
|
else if (platformType == PlatformType.Windows)
|
||||||
#pragma warning disable CA1416 // Validate platform compatibility
|
#pragma warning disable CA1416 // Validate platform compatibility.
|
||||||
return CanAccessPathWindows(path.Path, accessMode, isFile);
|
return CanAccessPathWindows(path.Path, accessMode, isFile);
|
||||||
#pragma warning restore CA1416 // Validate platform compatibility
|
#pragma warning restore CA1416 // Validate platform compatibility.
|
||||||
else
|
else
|
||||||
throw new PlatformNotSupportedException("Support for this platform is not compiled into this assembly.");
|
throw new PlatformNotSupportedException("Support for this platform is not compiled into this assembly.");
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-16
@@ -22,7 +22,7 @@ public class FileTypeService : IFileTypeService
|
|||||||
{
|
{
|
||||||
private readonly IFileSystem _fileSystem;
|
private readonly IFileSystem _fileSystem;
|
||||||
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
|
private readonly IFileSystemPermissionsService _fileSystemPermissionsService;
|
||||||
private const int BUFFER_SIZE = 18; // 18 bytes should be more than enough for common images header types
|
private const int BUFFER_SIZE = 18; // 18 bytes should be more than enough for common images header types.
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="FileTypeService"/> class.
|
/// Initializes a new instance of the <see cref="FileTypeService"/> class.
|
||||||
@@ -96,9 +96,9 @@ public class FileTypeService : IFileTypeService
|
|||||||
// Read more content from the file.
|
// Read more content from the file.
|
||||||
using FileSystemStream stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
using FileSystemStream stream = _fileSystem.FileStream.New(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
|
||||||
byte[] svgBuffer = new byte[1000];
|
byte[] svgBuffer = new byte[1000];
|
||||||
#pragma warning disable CA2022 // Avoid inexact read with 'Stream.Read'
|
#pragma warning disable CA2022 // Avoid inexact read with 'Stream.Read'.
|
||||||
stream.Read(svgBuffer, 0, 1000);
|
stream.Read(svgBuffer, 0, 1000);
|
||||||
#pragma warning restore CA2022 // Avoid inexact read with 'Stream.Read'
|
#pragma warning restore CA2022 // Avoid inexact read with 'Stream.Read'.
|
||||||
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
|
string extendedContent = Encoding.UTF8.GetString(svgBuffer);
|
||||||
// Check if the extended content contains <svg.
|
// Check if the extended content contains <svg.
|
||||||
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
|
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
|
||||||
@@ -127,13 +127,13 @@ public class FileTypeService : IFileTypeService
|
|||||||
private static ImageType IdentifyHeader(byte[] firstBytes)
|
private static ImageType IdentifyHeader(byte[] firstBytes)
|
||||||
{
|
{
|
||||||
if (Encoding.ASCII.GetBytes("BM").SequenceEqual(firstBytes[..2]))
|
if (Encoding.ASCII.GetBytes("BM").SequenceEqual(firstBytes[..2]))
|
||||||
return ImageType.BMP; // BMP
|
return ImageType.BMP; // BMP.
|
||||||
if (Encoding.ASCII.GetBytes("GIF").SequenceEqual(firstBytes[..3]))
|
if (Encoding.ASCII.GetBytes("GIF").SequenceEqual(firstBytes[..3]))
|
||||||
return ImageType.GIF; // GIF
|
return ImageType.GIF; // GIF.
|
||||||
if (new byte[] { 137, 80, 78, 71 }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 137, 80, 78, 71 }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.PNG; // PNG
|
return ImageType.PNG; // PNG.
|
||||||
if (new byte[] { 73, 73, 42 }.SequenceEqual(firstBytes[..3]) || new byte[] { 77, 77, 42 }.SequenceEqual(firstBytes[..3]))
|
if (new byte[] { 73, 73, 42 }.SequenceEqual(firstBytes[..3]) || new byte[] { 77, 77, 42 }.SequenceEqual(firstBytes[..3]))
|
||||||
return ImageType.TIFF; // TIFF
|
return ImageType.TIFF; // TIFF.
|
||||||
if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.JPEG; // JPEG
|
return ImageType.JPEG; // JPEG
|
||||||
// Any JPEG starts with the start-of-image marker FF D8 followed by FF and a marker byte. The marker that follows varies
|
// Any JPEG starts with the start-of-image marker FF D8 followed by FF and a marker byte. The marker that follows varies
|
||||||
@@ -142,23 +142,23 @@ public class FileTypeService : IFileTypeService
|
|||||||
if (firstBytes[0] == 255 && firstBytes[1] == 216 && firstBytes[2] == 255)
|
if (firstBytes[0] == 255 && firstBytes[1] == 216 && firstBytes[2] == 255)
|
||||||
{
|
{
|
||||||
if (firstBytes[3] == 225)
|
if (firstBytes[3] == 225)
|
||||||
return ImageType.JPEG_CANON; // JPEG CANON
|
return ImageType.JPEG_CANON; // JPEG CANON.
|
||||||
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN
|
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN.
|
||||||
}
|
}
|
||||||
if (new byte[] { 0x00, 0x11, 0x02, 0xFF }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 0x00, 0x11, 0x02, 0xFF }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.PICT; // PICT
|
return ImageType.PICT; // PICT.
|
||||||
if (new byte[] { 0x00, 0x00, 0x01, 0x00 }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 0x00, 0x00, 0x01, 0x00 }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.ICO; // ICO
|
return ImageType.ICO; // ICO.
|
||||||
if (new byte[] { 0x38, 0x42, 0x50, 0x53 }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 0x38, 0x42, 0x50, 0x53 }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.PSD; // PSD
|
return ImageType.PSD; // PSD.
|
||||||
if (new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }.SequenceEqual(firstBytes[..4]))
|
if (new byte[] { 0xFF, 0x4F, 0xFF, 0x51 }.SequenceEqual(firstBytes[..4]))
|
||||||
return ImageType.JPEG2000; // JPEG 2000
|
return ImageType.JPEG2000; // JPEG 2000.
|
||||||
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
|
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x70, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
|
||||||
return ImageType.AVIF; // AVIF
|
return ImageType.AVIF; // AVIF.
|
||||||
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
|
if (new byte[] { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20 }.SequenceEqual(firstBytes[..8]))
|
||||||
return ImageType.JPEG2000; // JPEG 2000 (variant)
|
return ImageType.JPEG2000; // JPEG 2000 (variant).
|
||||||
if (new byte[] { 0x52, 0x49, 0x46, 0x46 }.SequenceEqual(firstBytes[..4]) && new byte[] { 0x57, 0x45, 0x42, 0x50 }.SequenceEqual(firstBytes[8..12]))
|
if (new byte[] { 0x52, 0x49, 0x46, 0x46 }.SequenceEqual(firstBytes[..4]) && new byte[] { 0x57, 0x45, 0x42, 0x50 }.SequenceEqual(firstBytes[8..12]))
|
||||||
return ImageType.WEBP; // WEBP
|
return ImageType.WEBP; // WEBP.
|
||||||
return ImageType.None;
|
return ImageType.None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -53,7 +53,7 @@ public interface IPathStrategy
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns a collection of characters that are invalid for paths.
|
/// Returns a collection of characters that are invalid for paths.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>A collection of characters that are invalid in the context of paths</returns>
|
/// <returns>A collection of characters that are invalid in the context of paths.</returns>
|
||||||
char[] GetInvalidPathCharsForPlatform();
|
char[] GetInvalidPathCharsForPlatform();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
+1
-1
@@ -314,7 +314,7 @@ public class Library : AggregateRoot<LibraryId>
|
|||||||
if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent))
|
if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent))
|
||||||
_domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
|
_domainEvents.Add(new LibraryDeletedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
|
||||||
|
|
||||||
// TODO: Perhaps trigger events for removing content related to the removed library (media metadata, etc.).
|
// TODO: perhaps trigger events for removing content related to the removed library (media metadata, etc.).
|
||||||
return Result.Deleted;
|
return Result.Deleted;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -64,14 +64,14 @@ public class LibraryPathPart : ValueObject
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public static Result<LibraryPathPart> Create(LibraryPathPartKind kind, string? representation, bool isOptional)
|
public static Result<LibraryPathPart> Create(LibraryPathPartKind kind, string? representation, bool isOptional)
|
||||||
{
|
{
|
||||||
// a separator carries no representation, it always renders the platform path separator.
|
// A separator carries no representation, it always renders the platform path separator.
|
||||||
if (kind == LibraryPathPartKind.Separator)
|
if (kind == LibraryPathPartKind.Separator)
|
||||||
return new LibraryPathPart(kind, string.Empty, isOptional);
|
return new LibraryPathPart(kind, string.Empty, isOptional);
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(representation))
|
if (string.IsNullOrWhiteSpace(representation))
|
||||||
return DomainErrors.Library.PathTemplateLiteralCannotBeEmpty;
|
return DomainErrors.Library.PathTemplateLiteralCannotBeEmpty;
|
||||||
|
|
||||||
// typed parts must carry exactly one value placeholder, so that the position of the captured value is unambiguous.
|
// Typed parts must carry exactly one value placeholder, so that the position of the captured value is unambiguous.
|
||||||
if (kind != LibraryPathPartKind.Literal && s_placeholderRegex.Matches(representation).Count != 1)
|
if (kind != LibraryPathPartKind.Literal && s_placeholderRegex.Matches(representation).Count != 1)
|
||||||
return DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder;
|
return DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ internal class MediaLibraryScanJobFactory : IMediaLibraryScanJobFactory
|
|||||||
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
|
/// <exception cref="ArgumentException">Thrown when the type of the requested media library scan job has not been registered.</exception>
|
||||||
public TJob CreateJob<TJob>(LibraryId libraryId) where TJob : IMediaLibraryScanJob
|
public TJob CreateJob<TJob>(LibraryId libraryId) where TJob : IMediaLibraryScanJob
|
||||||
{
|
{
|
||||||
// resolve the job from DI
|
// Resolve the job from DI.
|
||||||
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException("Job type not registered in the DI system.");
|
TJob job = _serviceProvider.GetRequiredService<TJob>() ?? throw new ArgumentException("Job type not registered in the DI system.");
|
||||||
job.LibraryId = libraryId;
|
job.LibraryId = libraryId;
|
||||||
return job;
|
return job;
|
||||||
|
|||||||
+1
-1
@@ -79,7 +79,7 @@ public class ParsedLibraryPath : ValueObject
|
|||||||
/// <returns>A list of items defining the equality.</returns>
|
/// <returns>A list of items defining the equality.</returns>
|
||||||
public override IEnumerable<object?> GetEqualityComponents()
|
public override IEnumerable<object?> GetEqualityComponents()
|
||||||
{
|
{
|
||||||
// the captured values are stored in a dictionary, so they are ordered by their kind to keep equality independent of insertion order.
|
// The captured values are stored in a dictionary, so they are ordered by their kind to keep equality independent of insertion order.
|
||||||
foreach (KeyValuePair<LibraryPathPartKind, string> capturedValue in _values.OrderBy(capturedValue => capturedValue.Key))
|
foreach (KeyValuePair<LibraryPathPartKind, string> capturedValue in _values.OrderBy(capturedValue => capturedValue.Key))
|
||||||
{
|
{
|
||||||
yield return capturedValue.Key;
|
yield return capturedValue.Key;
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class MediaContributorId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
||||||
public static MediaContributorId CreateUnique()
|
public static MediaContributorId CreateUnique()
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new MediaContributorId(Guid.NewGuid());
|
return new MediaContributorId(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public sealed class MediaContributorId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
||||||
public static MediaContributorId Create(Guid value)
|
public static MediaContributorId Create(Guid value)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new MediaContributorId(value);
|
return new MediaContributorId(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -58,7 +58,7 @@ public sealed class Movie : Entity<MovieId>
|
|||||||
/// <returns>The created <see cref="Movie"/>.</returns>
|
/// <returns>The created <see cref="Movie"/>.</returns>
|
||||||
public static Result<Movie> Create(VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
|
public static Result<Movie> Create(VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new Movie(MovieId.CreateUnique(), metadata, contributors, ratings);
|
return new Movie(MovieId.CreateUnique(), metadata, contributors, ratings);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +72,7 @@ public sealed class Movie : Entity<MovieId>
|
|||||||
/// <returns>The created <see cref="Movie"/>.</returns>
|
/// <returns>The created <see cref="Movie"/>.</returns>
|
||||||
public static Result<Movie> Create(MovieId id, VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
|
public static Result<Movie> Create(MovieId id, VideoMetadata metadata, List<MediaContributorId> contributors, List<Rating> ratings)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new Movie(id, metadata, contributors, ratings);
|
return new Movie(id, metadata, contributors, ratings);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -27,7 +27,7 @@ public sealed class MovieId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
||||||
public static MovieId CreateUnique()
|
public static MovieId CreateUnique()
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new MovieId(Guid.NewGuid());
|
return new MovieId(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ public sealed class MovieId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
||||||
public static MovieId Create(Guid value)
|
public static MovieId Create(Guid value)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new MovieId(value);
|
return new MovieId(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class EpisodeId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
||||||
public static EpisodeId CreateUnique()
|
public static EpisodeId CreateUnique()
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new EpisodeId(Guid.NewGuid());
|
return new EpisodeId(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public sealed class EpisodeId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
||||||
public static EpisodeId Create(Guid value)
|
public static EpisodeId Create(Guid value)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new EpisodeId(value);
|
return new EpisodeId(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class SeasonId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
||||||
public static SeasonId CreateUnique()
|
public static SeasonId CreateUnique()
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new SeasonId(Guid.NewGuid());
|
return new SeasonId(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public sealed class SeasonId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
||||||
public static SeasonId Create(Guid value)
|
public static SeasonId Create(Guid value)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new SeasonId(value);
|
return new SeasonId(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class TvShowId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
||||||
public static TvShowId CreateUnique()
|
public static TvShowId CreateUnique()
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new TvShowId(Guid.NewGuid());
|
return new TvShowId(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ public sealed class TvShowId : EntityId<Guid>
|
|||||||
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
||||||
public static TvShowId Create(Guid value)
|
public static TvShowId Create(Guid value)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new TvShowId(value);
|
return new TvShowId(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -64,7 +64,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
|
|||||||
bool isComplete,
|
bool isComplete,
|
||||||
List<Book> books)
|
List<Book> books)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new BookSeries(
|
return new BookSeries(
|
||||||
id,
|
id,
|
||||||
metadata,
|
metadata,
|
||||||
@@ -87,7 +87,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
|
|||||||
bool isComplete,
|
bool isComplete,
|
||||||
List<Book> books)
|
List<Book> books)
|
||||||
{
|
{
|
||||||
// TODO: enforce invariants
|
// TODO: enforce invariants.
|
||||||
return new BookSeries(
|
return new BookSeries(
|
||||||
BookSeriesId.CreateUnique(),
|
BookSeriesId.CreateUnique(),
|
||||||
metadata,
|
metadata,
|
||||||
|
|||||||
@@ -32,9 +32,9 @@ public static class SharedConfiguration
|
|||||||
configuration.SetBasePath(basePath);
|
configuration.SetBasePath(basePath);
|
||||||
configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true);
|
configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true);
|
||||||
configuration.AddJsonFile("appsettings.shared.development.json", optional: true, reloadOnChange: true);
|
configuration.AddJsonFile("appsettings.shared.development.json", optional: true, reloadOnChange: true);
|
||||||
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
|
configuration.AddEnvironmentVariables(); // Environment variables should override the configuration files.
|
||||||
|
|
||||||
// bind the appsettings sections
|
// Bind the appsettings sections.
|
||||||
services.AddOptions<DatabaseSettingsDto>()
|
services.AddOptions<DatabaseSettingsDto>()
|
||||||
.Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
|
.Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
|
||||||
.ValidateFluently()
|
.ValidateFluently()
|
||||||
|
|||||||
@@ -33,16 +33,16 @@ public static class ExceptionUtilities
|
|||||||
/// <returns>A list of exceptions representing the list of inner exception(s) of <paramref name="exception"/>.</returns>
|
/// <returns>A list of exceptions representing the list of inner exception(s) of <paramref name="exception"/>.</returns>
|
||||||
public static IEnumerable<Exception> GetInnerExceptions(this Exception exception, int maximumDepth = 5)
|
public static IEnumerable<Exception> GetInnerExceptions(this Exception exception, int maximumDepth = 5)
|
||||||
{
|
{
|
||||||
// check if there are any more inner exceptions to return
|
// Check if there are any more inner exceptions to return.
|
||||||
if (exception == null || maximumDepth <= 0)
|
if (exception == null || maximumDepth <= 0)
|
||||||
yield break;
|
yield break;
|
||||||
// yield the current level exception itself
|
// Yield the current level exception itself.
|
||||||
yield return exception;
|
yield return exception;
|
||||||
// if the exception is an AggregateException, treat it differently and get its all exceptions
|
// If the exception is an AggregateException, treat it differently and get its all exceptions.
|
||||||
if (exception is AggregateException aggregateException)
|
if (exception is AggregateException aggregateException)
|
||||||
foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1)))
|
foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1)))
|
||||||
yield return innerException;
|
yield return innerException;
|
||||||
// if it's a normal exception, recursively get its list of inner exceptions and yield them
|
// If it's a normal exception, recursively get its list of inner exceptions and yield them.
|
||||||
foreach (Exception innerException in exception.InnerException?.GetInnerExceptions(maximumDepth - 1) ?? [])
|
foreach (Exception innerException in exception.InnerException?.GetInnerExceptions(maximumDepth - 1) ?? [])
|
||||||
yield return innerException;
|
yield return innerException;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ public static class OptionsBuilderValidationUtilities
|
|||||||
/// <returns>The same <see cref="OptionsBuilder{TOptions}"/> instance, to allow for chaining.</returns>
|
/// <returns>The same <see cref="OptionsBuilder{TOptions}"/> instance, to allow for chaining.</returns>
|
||||||
public static OptionsBuilder<TOptions> ValidateFluently<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
|
public static OptionsBuilder<TOptions> ValidateFluently<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
|
||||||
{
|
{
|
||||||
// register a singleton instance of IValidateOptions<TOptions> using the validator
|
// Register a singleton instance of IValidateOptions<TOptions> using the validator.
|
||||||
optionsBuilder.Services.AddSingleton<IValidateOptions<TOptions>>(
|
optionsBuilder.Services.AddSingleton<IValidateOptions<TOptions>>(
|
||||||
serviceProvider => new ValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
|
serviceProvider => new ValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
|
||||||
return optionsBuilder;
|
return optionsBuilder;
|
||||||
|
|||||||
@@ -41,22 +41,22 @@ public class ValidationOptions<TOptions> : IValidateOptions<TOptions> where TOpt
|
|||||||
/// <returns>A <see cref="ValidateOptionsResult"/> that indicates whether the validation was successful or not.</returns>
|
/// <returns>A <see cref="ValidateOptionsResult"/> that indicates whether the validation was successful or not.</returns>
|
||||||
public ValidateOptionsResult Validate(string? name, TOptions options)
|
public ValidateOptionsResult Validate(string? name, TOptions options)
|
||||||
{
|
{
|
||||||
// check if the name of the options is specified and matches the provided one
|
// Check if the name of the options is specified and matches the provided one.
|
||||||
if (Name is not null && Name != name)
|
if (Name is not null && Name != name)
|
||||||
return ValidateOptionsResult.Skip;
|
return ValidateOptionsResult.Skip;
|
||||||
|
|
||||||
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
|
ArgumentNullException.ThrowIfNull(options, nameof(options)); // Don't go further if the options are null.
|
||||||
|
|
||||||
List<Error> validationResult = _validator.Validate(options); // validate the options using the validator
|
List<Error> validationResult = _validator.Validate(options); // Validate the options using the validator.
|
||||||
|
|
||||||
// return a response based on the validation result
|
// Return a response based on the validation result.
|
||||||
if (validationResult.Count == 0)
|
if (validationResult.Count == 0)
|
||||||
return ValidateOptionsResult.Success;
|
return ValidateOptionsResult.Success;
|
||||||
|
|
||||||
// if the validation fails, collect the error messages
|
// If the validation fails, collect the error messages.
|
||||||
string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")];
|
string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")];
|
||||||
|
|
||||||
// and return them with a failure result
|
// And return them with a failure result.
|
||||||
return ValidateOptionsResult.Fail(errors);
|
return ValidateOptionsResult.Fail(errors);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loaded 100 of 712 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user