mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Formats code comments as sentences in the production sources.
Capitalizes the first word and adds the terminal period across the domain, application, data access, infrastructure, API and web layers and the plugins. No comment is reworded. The change also normalizes the TODO bodies to lowercase, leaves commented-out code untouched, corrects the Threat/Treat typo and the dangling hyphen in the exception middleware, and collapses two accidental repeated terminal periods.
This commit is contained in:
1 parent
88455fec9c
commit
727aa33318
142 files changed
+403
-403
No files matched your search
@@ -53,7 +53,7 @@ internal sealed class CalibreArtworkProvider : IArtworkProvider<BookMetadataLook
|
||||
if (string.IsNullOrWhiteSpace(document.CoverHref))
|
||||
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);
|
||||
if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref))
|
||||
return Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
|
||||
|
||||
@@ -34,7 +34,7 @@ internal static class OpfReader
|
||||
try
|
||||
{
|
||||
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()
|
||||
{
|
||||
DtdProcessing = DtdProcessing.Prohibit,
|
||||
@@ -48,7 +48,7 @@ internal static class OpfReader
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -104,7 +104,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
||||
OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null;
|
||||
string? openLibraryId = bookMetadataLookup.OpenLibraryId;
|
||||
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))
|
||||
{
|
||||
string olid = NormalizeOlid(openLibraryId);
|
||||
@@ -123,10 +123,10 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
||||
if (openLibraryEditionResponse is null && openLibraryWorkResponse is 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))
|
||||
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)
|
||||
{
|
||||
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)
|
||||
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)
|
||||
return null;
|
||||
|
||||
@@ -208,7 +208,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider<BookMe
|
||||
private static int ScoreEdition(OpenLibraryEditionResponse openLibraryEdition, string? wantedIsbn, string? wantedLanguage)
|
||||
{
|
||||
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)))
|
||||
score += 10_000;
|
||||
|
||||
|
||||
@@ -248,7 +248,7 @@ internal static class PdfDocumentParser
|
||||
}
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -73,7 +73,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity
|
||||
public ReleaseCountry? ReleaseCountry { get; set; }
|
||||
|
||||
/// <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>
|
||||
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.
|
||||
/// </summary>
|
||||
public float? VolumeNumber { get; set; }
|
||||
// TODO: uncomment when series is implemented
|
||||
// TODO: uncomment when series is implemented.
|
||||
/// <summary>
|
||||
/// Gets or sets the series id, if the book is part of a series.
|
||||
/// </summary>
|
||||
|
||||
@@ -21,7 +21,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
|
||||
private readonly List<Func<TProperty, bool>> _predicates = [];
|
||||
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).
|
||||
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
|
||||
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>
|
||||
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))
|
||||
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>
|
||||
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);
|
||||
currentError = validationError;
|
||||
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>
|
||||
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))
|
||||
yield break;
|
||||
|
||||
|
||||
+1
-1
@@ -218,7 +218,7 @@ public static class TrackEntityMapping
|
||||
repositoryEntity.ReleaseCountry,
|
||||
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) ||
|
||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
||||
|
||||
@@ -48,7 +48,7 @@ public static class LibraryMapping
|
||||
{
|
||||
Id = scanId.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,
|
||||
User = null!,
|
||||
Library = null!,
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ public static class BookEntityMapping
|
||||
repositoryEntity.ReleaseCountry,
|
||||
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) ||
|
||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageName) ||
|
||||
!string.IsNullOrWhiteSpace(repositoryEntity.LanguageNativeName)
|
||||
|
||||
@@ -65,7 +65,7 @@ internal static class ApplicationHandlerTelemetry
|
||||
{
|
||||
activity?.SetStatus(ActivityStatusCode.Error, error);
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ public class LibraryScanJobProgressChangedDomainEventHandler : IDomainEventHandl
|
||||
public async ValueTask HandleAsync(LibraryScanJobProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
_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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -38,7 +38,7 @@ public class LibraryScanProgressChangedDomainEventHandler : IDomainEventHandler<
|
||||
public async ValueTask HandleAsync(LibraryScanProgressChangedDomainEvent domainEvent, CancellationToken cancellationToken)
|
||||
{
|
||||
_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);
|
||||
}
|
||||
}
|
||||
+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);
|
||||
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)
|
||||
{
|
||||
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;
|
||||
|
||||
// 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;
|
||||
|
||||
// Update the user and persist the temporary password.
|
||||
|
||||
+1
-1
@@ -116,7 +116,7 @@ public class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, R
|
||||
if (saveChangesResult.IsFailure)
|
||||
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.
|
||||
return new RegistrationResponse(user.Id, user.Username, totpSecret);
|
||||
}
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ public class RegisterUserCommandValidator : AbstractValidator<RegisterUserComman
|
||||
.WithError(Errors.Authentication.UsernameCannotBeEmpty)
|
||||
.Length(3, 255)
|
||||
.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);
|
||||
|
||||
RuleFor(command => command.Password)
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator<Up
|
||||
.Must(id => id != Guid.Empty)
|
||||
.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)
|
||||
.NotEmpty()
|
||||
.WithError(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty)
|
||||
|
||||
@@ -142,8 +142,8 @@ public class AlbumConfiguration : IEntityTypeConfiguration<AlbumEntity>
|
||||
.HasForeignKey(album => album.ArtistId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
builder.HasMany(album => album.Tags)
|
||||
.WithMany()
|
||||
.UsingEntity<Dictionary<string, object>>(
|
||||
|
||||
@@ -20,7 +20,7 @@ public class AlbumContributorConfiguration : IEntityTypeConfiguration<AlbumContr
|
||||
builder.ToTable("AlbumContributors");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(albumContributor => albumContributor.AlbumId)
|
||||
@@ -35,7 +35,7 @@ public class AlbumContributorConfiguration : IEntityTypeConfiguration<AlbumContr
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(albumContributor => albumContributor.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
@@ -24,7 +24,7 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
|
||||
builder.ToTable("Artists");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(artist => artist.LibraryId)
|
||||
@@ -143,8 +143,8 @@ public class ArtistConfiguration : IEntityTypeConfiguration<ArtistEntity>
|
||||
.HasMaxLength(20);
|
||||
});
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
builder.HasMany(artist => artist.Tags)
|
||||
.WithMany()
|
||||
.UsingEntity<Dictionary<string, object>>(
|
||||
|
||||
@@ -20,7 +20,7 @@ public class ArtistContributorConfiguration : IEntityTypeConfiguration<ArtistCon
|
||||
builder.ToTable("ArtistContributors");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(artistContributor => artistContributor.ArtistId)
|
||||
@@ -35,7 +35,7 @@ public class ArtistContributorConfiguration : IEntityTypeConfiguration<ArtistCon
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(artistContributor => artistContributor.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
@@ -20,7 +20,7 @@ public class BookArtworkConfiguration : IEntityTypeConfiguration<BookArtworkEnti
|
||||
builder.ToTable("BookArtwork");
|
||||
builder.HasKey(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);
|
||||
builder.Property(bookArtwork => bookArtwork.BookId)
|
||||
.IsRequired()
|
||||
@@ -49,7 +49,7 @@ public class BookArtworkConfiguration : IEntityTypeConfiguration<BookArtworkEnti
|
||||
builder.Property(bookArtwork => bookArtwork.LastUpdateUtc)
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(bookArtwork => bookArtwork.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(9);
|
||||
|
||||
@@ -23,7 +23,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
||||
builder.ToTable("Books");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(book => book.Title)
|
||||
@@ -62,8 +62,8 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
||||
.HasColumnOrder(14);
|
||||
builder.Property(book => book.OriginalLanguageNativeName)
|
||||
.HasColumnOrder(15);
|
||||
// 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
|
||||
// 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.
|
||||
builder.HasMany(book => book.Tags)
|
||||
.WithMany()
|
||||
.UsingEntity<Dictionary<string, object>>(
|
||||
@@ -213,7 +213,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(book => book.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(32);
|
||||
@@ -231,7 +231,7 @@ public class BookConfiguration : IEntityTypeConfiguration<BookEntity>
|
||||
.HasColumnOrder(35);
|
||||
|
||||
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 });
|
||||
// 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.
|
||||
|
||||
@@ -20,7 +20,7 @@ public class BookContributorConfiguration : IEntityTypeConfiguration<BookContrib
|
||||
builder.ToTable("BookContributors");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(bookContributor => bookContributor.BookId)
|
||||
@@ -35,7 +35,7 @@ public class BookContributorConfiguration : IEntityTypeConfiguration<BookContrib
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(bookContributor => bookContributor.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
@@ -18,10 +18,10 @@ public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration<Di
|
||||
public void Configure(EntityTypeBuilder<DirectoryScanFingerprintEntity> builder)
|
||||
{
|
||||
builder.ToTable("DirectoryScanFingerprints");
|
||||
// composite key, so that each directory scan fingerprint is uniquely identified within its library by its path
|
||||
// Composite key, so that each directory scan fingerprint is uniquely identified within its library by its path.
|
||||
builder.HasKey(directoryScanFingerprint => new { directoryScanFingerprint.LibraryId, directoryScanFingerprint.Path });
|
||||
|
||||
// one library with many directory scan fingerprints
|
||||
// One library with many directory scan fingerprints.
|
||||
builder.HasOne<LibraryEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(directoryScanFingerprint => directoryScanFingerprint.LibraryId)
|
||||
@@ -41,7 +41,7 @@ public class DirectoryScanFingerprintConfiguration : IEntityTypeConfiguration<Di
|
||||
.IsRequired()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public class FavoriteConfiguration : IEntityTypeConfiguration<FavoriteEntity>
|
||||
builder.ToTable("Favorites");
|
||||
builder.HasKey(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);
|
||||
|
||||
// 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.HasKey(configuration => configuration.Id);
|
||||
builder.Property(configuration => configuration.Id)
|
||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
||||
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||
.HasColumnOrder(0);
|
||||
builder.Property(configuration => configuration.LibraryId)
|
||||
.IsRequired()
|
||||
@@ -32,7 +32,7 @@ public class LibraryBookReaderConfigurationConfiguration : IEntityTypeConfigurat
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(configuration => configuration.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
@@ -21,7 +21,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
builder.ToTable("Libraries");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(library => library.Title)
|
||||
@@ -83,19 +83,19 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnOrder(18);
|
||||
|
||||
// one user with many libraries
|
||||
// One user with many libraries.
|
||||
builder.HasOne(library => library.User)
|
||||
.WithMany(user => user.Libraries)
|
||||
.HasForeignKey(library => library.UserId)
|
||||
.IsRequired();
|
||||
|
||||
// one library with many scans
|
||||
// One library with many scans.
|
||||
builder.HasMany(library => library.LibraryScans)
|
||||
.WithOne(libraryScan => libraryScan.Library)
|
||||
.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 =>
|
||||
{
|
||||
contentLocationBuilder.ToTable("LibraryContentLocations");
|
||||
@@ -112,7 +112,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
.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 =>
|
||||
{
|
||||
partBuilder.ToTable("LibraryPathTemplateParts");
|
||||
@@ -139,7 +139,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration<LibraryEntity>
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(library => library.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(12);
|
||||
|
||||
@@ -21,16 +21,16 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
||||
builder.ToTable("LibraryScans");
|
||||
builder.HasKey(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);
|
||||
|
||||
// one user with many library scans
|
||||
// One user with many library scans.
|
||||
builder.HasOne(libraryScan => libraryScan.User)
|
||||
.WithMany(user => user.LibraryScans)
|
||||
.HasForeignKey(libraryScan => libraryScan.UserId)
|
||||
.IsRequired();
|
||||
|
||||
// one library with many library scans
|
||||
// One library with many library scans.
|
||||
builder.HasOne(libraryScan => libraryScan.Library)
|
||||
.WithMany(library => library.LibraryScans)
|
||||
.HasForeignKey(libraryScan => libraryScan.LibraryId)
|
||||
@@ -41,7 +41,7 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
||||
.HasConversion<string>()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(libraryScan => libraryScan.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
@@ -58,10 +58,10 @@ public class LibraryScanConfiguration : IEntityTypeConfiguration<LibraryScanEnti
|
||||
.HasDefaultValue(null)
|
||||
.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 })
|
||||
.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)
|
||||
{
|
||||
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 });
|
||||
|
||||
// one library scan with many library scan results
|
||||
// One library scan with many library scan results.
|
||||
builder.HasOne(libraryScanResult => libraryScanResult.LibraryScan)
|
||||
.WithMany(libraryScan => libraryScan.LibraryScanResults)
|
||||
.HasForeignKey(libraryScanResult => libraryScanResult.LibraryScanId)
|
||||
@@ -38,7 +38,7 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(libraryScanResult => libraryScanResult.ContentHash)
|
||||
.HasMaxLength(24) // xxHash128 as Base64
|
||||
.HasMaxLength(24) // xxHash128 as Base64.
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
@@ -56,7 +56,7 @@ public class LibraryScanResultConfiguration : IEntityTypeConfiguration<LibrarySc
|
||||
.HasMaxLength(10)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
// Indexes
|
||||
// Indexes.
|
||||
builder.HasIndex(libraryScanResult => new { libraryScanResult.ContentHash, libraryScanResult.FileSize, libraryScanResult.Path });
|
||||
|
||||
builder.HasIndex(libraryScanResult => libraryScanResult.Path);
|
||||
|
||||
@@ -18,10 +18,10 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
||||
public void Configure(EntityTypeBuilder<LibraryScanSnapshotEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryScanSnapshots");
|
||||
// composite key, so that each media library scan snapshot item is uniquely identified within its library by its path
|
||||
// Composite key, so that each media library scan snapshot item is uniquely identified within its library by its path.
|
||||
builder.HasKey(libraryScanSnapshot => new { libraryScanSnapshot.LibraryId, libraryScanSnapshot.Path });
|
||||
|
||||
// one library with many media library scan snapshot items
|
||||
// One library with many media library scan snapshot items.
|
||||
builder.HasOne(libraryScanSnapshot => libraryScanSnapshot.Library)
|
||||
.WithMany()
|
||||
.HasForeignKey(libraryScanSnapshot => libraryScanSnapshot.LibraryId)
|
||||
@@ -49,7 +49,7 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(libraryScanSnapshot => libraryScanSnapshot.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
@@ -66,7 +66,7 @@ public class LibraryScanSnapshotConfiguration : IEntityTypeConfiguration<Library
|
||||
.HasDefaultValue(null)
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -18,10 +18,10 @@ public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration<L
|
||||
public void Configure(EntityTypeBuilder<LibraryScanStagingResultsEntity> builder)
|
||||
{
|
||||
builder.ToTable("LibraryScanStagingResults");
|
||||
// composite key, so that each media library scan staging result is uniquely identified within its scan by its path
|
||||
// Composite key, so that each media library scan staging result is uniquely identified within its scan by its path.
|
||||
builder.HasKey(libraryScanStagingResult => new { libraryScanStagingResult.LibraryScanId, libraryScanStagingResult.Path });
|
||||
|
||||
// one media library scan with many media library scan staging results
|
||||
// One media library scan with many media library scan staging results.
|
||||
builder.HasOne<LibraryScanEntity>()
|
||||
.WithMany()
|
||||
.HasForeignKey(libraryScanStagingResult => libraryScanStagingResult.LibraryScanId)
|
||||
@@ -61,7 +61,7 @@ public class LibraryScanStagingResultsConfiguration : IEntityTypeConfiguration<L
|
||||
.IsRequired()
|
||||
.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 });
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration<Medi
|
||||
builder.ToTable("MediaConsumptionRecords");
|
||||
builder.HasKey(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);
|
||||
|
||||
// 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.HasKey(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);
|
||||
builder.Property(contributor => contributor.DisplayName)
|
||||
.IsRequired()
|
||||
@@ -38,7 +38,7 @@ public class MediaContributorConfiguration : IEntityTypeConfiguration<MediaContr
|
||||
builder.Property(contributor => contributor.DateOfDeath)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(contributor => contributor.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
|
||||
@@ -21,7 +21,7 @@ public class MediaResumePointConfiguration : IEntityTypeConfiguration<MediaResum
|
||||
builder.ToTable("MediaResumePoints");
|
||||
builder.HasKey(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);
|
||||
|
||||
// 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.HasKey(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);
|
||||
builder.Property(musicArtwork => musicArtwork.OwnerType)
|
||||
.IsRequired()
|
||||
@@ -54,7 +54,7 @@ public class MusicArtworkConfiguration : IEntityTypeConfiguration<MusicArtworkEn
|
||||
builder.Property(musicArtwork => musicArtwork.LastUpdateUtc)
|
||||
.HasColumnOrder(9);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(musicArtwork => musicArtwork.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(10);
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio
|
||||
builder.ToTable("MusicLibraryScanItemMetadata");
|
||||
builder.HasKey(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);
|
||||
builder.Property(musicMetadata => musicMetadata.LibraryScanId)
|
||||
.IsRequired()
|
||||
@@ -103,6 +103,6 @@ public class MusicLibraryScanItemMetadataConfiguration : IEntityTypeConfiguratio
|
||||
.HasColumnOrder(31);
|
||||
|
||||
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)
|
||||
.HasColumnOrder(1);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(permission => permission.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
@@ -21,7 +21,7 @@ public class PlaylistConfiguration : IEntityTypeConfiguration<PlaylistEntity>
|
||||
builder.ToTable("Playlists");
|
||||
builder.HasKey(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);
|
||||
|
||||
// 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.HasKey(plugin => plugin.Id);
|
||||
builder.Property(plugin => plugin.Id)
|
||||
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
|
||||
.ValueGeneratedNever() // Because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it.
|
||||
.HasColumnOrder(0);
|
||||
builder.Property(plugin => plugin.Name)
|
||||
.IsRequired()
|
||||
@@ -51,7 +51,7 @@ public class PluginConfiguration : IEntityTypeConfiguration<PluginEntity>
|
||||
.IsRequired()
|
||||
.HasColumnOrder(8);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(plugin => plugin.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(9);
|
||||
|
||||
@@ -28,7 +28,7 @@ public class RoleConfiguration : IEntityTypeConfiguration<RoleEntity>
|
||||
.HasMaxLength(100)
|
||||
.HasColumnOrder(1);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(role => role.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
@@ -19,26 +19,26 @@ public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissi
|
||||
{
|
||||
builder.ToTable("RolePermissions");
|
||||
|
||||
// composite primary key
|
||||
// Composite primary key.
|
||||
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)
|
||||
.WithMany(user => user.RolePermissions)
|
||||
.HasForeignKey(rolePermission => rolePermission.RoleId)
|
||||
.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)
|
||||
.WithMany(role => role.RolePermissions)
|
||||
.HasForeignKey(rolePermission => rolePermission.PermissionId)
|
||||
.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)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
@@ -55,7 +55,7 @@ public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermissi
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// indexes
|
||||
// Indexes.
|
||||
builder.HasIndex(userRole => new { userRole.RoleId, userRole.PermissionId })
|
||||
.IsUnique();
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ public class ScheduledJobConfiguration : IEntityTypeConfiguration<ScheduledJobEn
|
||||
builder.ToTable("ScheduledJobs");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(scheduledJob => scheduledJob.Name)
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ public class SchedulerDisplayPreferencesConfiguration : IEntityTypeConfiguration
|
||||
builder.ToTable("SchedulerDisplayPreferences");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(preferences => preferences.UserId)
|
||||
|
||||
@@ -21,10 +21,10 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
||||
builder.ToTable("Themes");
|
||||
builder.HasKey(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);
|
||||
|
||||
// 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)
|
||||
.IsUnique();
|
||||
|
||||
@@ -63,7 +63,7 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
||||
.HasConversion<string>()
|
||||
.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)
|
||||
.IsUnique()
|
||||
.HasFilter("IsCurrent = 1");
|
||||
@@ -80,7 +80,7 @@ public class ThemeConfiguration : IEntityTypeConfiguration<ThemeEntity>
|
||||
.IsRequired()
|
||||
.HasColumnOrder(10);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(theme => theme.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(11);
|
||||
|
||||
@@ -167,8 +167,8 @@ public class TrackConfiguration : IEntityTypeConfiguration<TrackEntity>
|
||||
.HasForeignKey(track => track.AlbumId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
builder.HasMany(track => track.Tags)
|
||||
.WithMany()
|
||||
.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.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
|
||||
// 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 })
|
||||
|
||||
@@ -20,7 +20,7 @@ public class TrackContributorConfiguration : IEntityTypeConfiguration<TrackContr
|
||||
builder.ToTable("TrackContributors");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(trackContributor => trackContributor.TrackId)
|
||||
@@ -35,7 +35,7 @@ public class TrackContributorConfiguration : IEntityTypeConfiguration<TrackContr
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(trackContributor => trackContributor.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
@@ -21,7 +21,7 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
||||
builder.ToTable("Users");
|
||||
builder.HasKey(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);
|
||||
|
||||
builder.Property(user => user.Username)
|
||||
@@ -45,11 +45,11 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(5);
|
||||
|
||||
// relationships
|
||||
// Relationships.
|
||||
builder.HasMany(user => user.Libraries)
|
||||
.WithOne(library => library.User)
|
||||
.HasForeignKey(library => library.UserId)
|
||||
.IsRequired() // a library must have a user
|
||||
.IsRequired() // A library must have a user.
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.HasOne(user => user.UserRole)
|
||||
@@ -63,7 +63,7 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
||||
.HasForeignKey(userPermission => userPermission.UserId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(user => user.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(6);
|
||||
@@ -80,8 +80,8 @@ public class UserConfiguration : IEntityTypeConfiguration<UserEntity>
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(9);
|
||||
|
||||
// indexes
|
||||
// Indexes.
|
||||
builder.HasIndex(user => user.Username)
|
||||
.IsUnique(); // queried frequently
|
||||
.IsUnique(); // Queried frequently.
|
||||
}
|
||||
}
|
||||
@@ -19,26 +19,26 @@ public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissi
|
||||
{
|
||||
builder.ToTable("UserPermissions");
|
||||
|
||||
// composite primary key
|
||||
// Composite primary key.
|
||||
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)
|
||||
.WithMany(user => user.UserPermissions)
|
||||
.HasForeignKey(userPermission => userPermission.UserId)
|
||||
.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)
|
||||
.WithMany(role => role.UserPermissions)
|
||||
.HasForeignKey(userPermission => userPermission.PermissionId)
|
||||
.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)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
@@ -55,7 +55,7 @@ public class UserPermissionConfiguration : IEntityTypeConfiguration<UserPermissi
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// indexes
|
||||
// Indexes.
|
||||
builder.HasIndex(userRole => new { userRole.UserId, userRole.PermissionId })
|
||||
.IsUnique();
|
||||
}
|
||||
|
||||
@@ -19,26 +19,26 @@ public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
|
||||
{
|
||||
builder.ToTable("UserRoles");
|
||||
|
||||
// primary key
|
||||
// Primary key.
|
||||
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)
|
||||
.WithOne(user => user.UserRole)
|
||||
.HasForeignKey<UserRoleEntity>(userRole => userRole.UserId)
|
||||
.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)
|
||||
.WithMany(role => role.UserRoles)
|
||||
.HasForeignKey(userRole => userRole.RoleId)
|
||||
.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)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
@@ -55,7 +55,7 @@ public class UserRoleConfiguration : IEntityTypeConfiguration<UserRoleEntity>
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
// indexes
|
||||
// Indexes.
|
||||
builder.HasIndex(userRole => new { userRole.UserId, userRole.RoleId })
|
||||
.IsUnique();
|
||||
}
|
||||
|
||||
@@ -20,10 +20,10 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
||||
builder.ToTable("UserSettings");
|
||||
builder.HasKey(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);
|
||||
|
||||
// one user with one set of settings
|
||||
// One user with one set of settings.
|
||||
builder.HasOne<UserEntity>()
|
||||
.WithOne()
|
||||
.HasForeignKey<UserSettingsEntity>(settings => settings.UserId)
|
||||
@@ -130,7 +130,7 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
||||
.IsRequired()
|
||||
.HasColumnOrder(29);
|
||||
|
||||
// audit
|
||||
// Audit.
|
||||
builder.Property(settings => settings.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
@@ -147,7 +147,7 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration<UserSettingsEn
|
||||
.HasDefaultValue(null)
|
||||
.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)
|
||||
.IsUnique();
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ using System.Reflection;
|
||||
namespace Lumina.DataAccess.Common.DependencyInjection;
|
||||
|
||||
/// <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>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class DataAccessLayerServices
|
||||
|
||||
@@ -68,7 +68,7 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
Guid? userId = _currentUserService.UserId;
|
||||
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>())
|
||||
{
|
||||
if (entry.State == EntityState.Added)
|
||||
@@ -100,12 +100,12 @@ public sealed class UpdateAuditableEntitiesInterceptor : SaveChangesInterceptor
|
||||
/// <param name="utcNow">The current UTC timestamp.</param>
|
||||
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.CreatedBy).IsModified = false;
|
||||
|
||||
// set modification properties
|
||||
// Set modification properties.
|
||||
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);
|
||||
});
|
||||
|
||||
// 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
|
||||
// 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.
|
||||
migrationBuilder.Sql("""
|
||||
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
|
||||
|
||||
+3
-3
@@ -22,7 +22,7 @@ namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
/// </summary>
|
||||
internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerprintRepository
|
||||
{
|
||||
private const int UPSERT_BATCH_SIZE = 500; // keeps the number of bound parameters of a single UPSERT statement well under the SQLite parameter limit
|
||||
private const int UPSERT_BATCH_SIZE = 500; // Keeps the number of bound parameters of a single UPSERT statement well under the SQLite parameter limit.
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
@@ -63,14 +63,14 @@ internal sealed class DirectoryScanFingerprintRepository : IDirectoryScanFingerp
|
||||
/// <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)
|
||||
{
|
||||
// nothing to upsert for an empty collection
|
||||
// Nothing to upsert for an empty collection.
|
||||
if (entities.Count == 0)
|
||||
return Result.Updated;
|
||||
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
List<DirectoryScanFingerprintEntity> remainingEntities = [.. entities];
|
||||
// upsert the entities in batches, to keep the number of bound parameters of a single UPSERT statement under the SQLite parameter limit
|
||||
// Upsert the entities in batches, to keep the number of bound parameters of a single UPSERT statement under the SQLite parameter limit.
|
||||
while (remainingEntities.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
@@ -103,10 +103,10 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
DateTime nowUtc = DateTime.UtcNow;
|
||||
object parameters = new { libraryId, scanId, userId, nowUtc };
|
||||
|
||||
// the Id of the inserted rows is generated in SQL as a random 16 byte value formatted as 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
|
||||
// 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.
|
||||
|
||||
// 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 = """
|
||||
INSERT INTO LibraryScanResults (Id, LibraryScanId, Status, Path, ContentHash, FileSize, 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);
|
||||
|
||||
// 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 = """
|
||||
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
|
||||
@@ -137,7 +137,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
|
||||
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 = """
|
||||
DELETE FROM LibraryScanSnapshots
|
||||
WHERE LibraryId = @libraryId
|
||||
@@ -153,7 +153,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
|
||||
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 = """
|
||||
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
|
||||
@@ -172,7 +172,7 @@ internal sealed class LibraryScanSnapshotRepository : ILibraryScanSnapshotReposi
|
||||
|
||||
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;";
|
||||
|
||||
command = new(CLEAR_STAGING_SQL, parameters, transaction);
|
||||
|
||||
+5
-5
@@ -23,7 +23,7 @@ namespace Lumina.DataAccess.Core.Repositories.Libraries;
|
||||
/// </summary>
|
||||
internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingResultsRepository
|
||||
{
|
||||
private const int INSERT_BATCH_SIZE = 500; // keeps the number of bound parameters of a single INSERT statement well under the SQLite parameter limit
|
||||
private const int INSERT_BATCH_SIZE = 500; // Keeps the number of bound parameters of a single INSERT statement well under the SQLite parameter limit.
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
@@ -43,14 +43,14 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
|
||||
/// <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)
|
||||
{
|
||||
// nothing to insert for an empty collection
|
||||
// Nothing to insert for an empty collection.
|
||||
if (entities.Count == 0)
|
||||
return Result.Created;
|
||||
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync(cancellationToken);
|
||||
List<LibraryScanStagingResultsEntity> remainingEntities = [.. entities];
|
||||
// insert the entities in batches, to keep the number of bound parameters of a single INSERT statement under the SQLite parameter limit
|
||||
// Insert the entities in batches, to keep the number of bound parameters of a single INSERT statement under the SQLite parameter limit.
|
||||
while (remainingEntities.Count > 0)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
@@ -73,8 +73,8 @@ internal sealed class LibraryScanStagingResultsRepository : ILibraryScanStagingR
|
||||
public async Task<Result<Updated>> MarkChangesAgainstSnapshotAsync(Guid scanId, Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
await using SqliteConnection connection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
// compare the discovered file system items against the media library scan snapshot of the previous scan, entirely in the database, so that the snapshot never needs to be loaded into memory:
|
||||
// an item with no snapshot entry is new, an item with the same size and last write time is unchanged and keeps the stored hash, and everything else changed and needs its content hashed again
|
||||
// Compare the discovered file system items against the media library scan snapshot of the previous scan, entirely in the database, so that the snapshot never needs to be loaded into memory:
|
||||
// An item with no snapshot entry is new, an item with the same size and last write time is unchanged and keeps the stored hash, and everything else changed and needs its content hashed again.
|
||||
const string MARK_CHANGES_SQL = """
|
||||
UPDATE LibraryScanStagingResults AS staging
|
||||
SET ContentHash = COALESCE(snapshot.ContentHash, 0),
|
||||
|
||||
+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>
|
||||
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();
|
||||
|
||||
// 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>
|
||||
private static bool IsUniqueConstraintViolation(SqliteException exception)
|
||||
{
|
||||
return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
||||
return exception.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE.
|
||||
}
|
||||
|
||||
/// <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>
|
||||
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>
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderC
|
||||
_luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
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.PluginId = configuration.PluginId;
|
||||
existingConfiguration.IsEnabled = configuration.IsEnabled;
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM
|
||||
_luminaDbContext.LibraryMetadataProviderConfigurations.Add(configuration);
|
||||
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.PluginId = configuration.PluginId;
|
||||
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.
|
||||
return exception.InnerException is SqliteException sqliteException
|
||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE.
|
||||
}
|
||||
|
||||
/// <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>
|
||||
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>
|
||||
|
||||
@@ -7,13 +7,13 @@ public enum IsbnFormat
|
||||
{
|
||||
/// <summary>
|
||||
/// The 10-digit ISBN format used for books published before 2007.
|
||||
/// Example: 0-306-40615-2
|
||||
/// Example: 0-306-40615-2.
|
||||
/// </summary>
|
||||
Isbn10,
|
||||
|
||||
/// <summary>
|
||||
/// 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>
|
||||
Isbn13
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the sort order
|
||||
/// Enumeration for the sort order.
|
||||
/// </summary>
|
||||
public enum SortOrder
|
||||
{
|
||||
|
||||
@@ -42,7 +42,7 @@ public class ReleaseInfo : ValueObject
|
||||
public Optional<ReleaseCountry> ReleaseCountry { get; }
|
||||
|
||||
/// <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>
|
||||
public Optional<string> ReleaseVersion { get; }
|
||||
|
||||
|
||||
+3
-3
@@ -214,7 +214,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
contributors,
|
||||
ratings,
|
||||
tracks,
|
||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider
|
||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider.
|
||||
Optional<DateTime>.None());
|
||||
}
|
||||
|
||||
@@ -315,7 +315,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// <param name="contributors">The media contributors of the album.</param>
|
||||
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.AddRange(contributors);
|
||||
}
|
||||
@@ -326,7 +326,7 @@ public sealed class Album : Entity<AlbumId>
|
||||
/// <param name="ratings">The ratings of the album.</param>
|
||||
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.AddRange(ratings);
|
||||
}
|
||||
|
||||
+5
-5
@@ -226,7 +226,7 @@ public sealed class Track : Entity<TrackId>
|
||||
musicBrainzTrackId,
|
||||
contributors,
|
||||
ratings,
|
||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider
|
||||
DateTime.UtcNow, // TODO: should be IDateTimeProvider.
|
||||
Optional<DateTime>.None());
|
||||
}
|
||||
|
||||
@@ -304,7 +304,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// <param name="moods">The moods of the track.</param>
|
||||
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.AddRange(moods);
|
||||
}
|
||||
@@ -315,7 +315,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// <param name="isrcs">The ISRCs of the track.</param>
|
||||
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.AddRange(isrcs);
|
||||
}
|
||||
@@ -326,7 +326,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// <param name="contributors">The media contributors of the track.</param>
|
||||
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.AddRange(contributors);
|
||||
}
|
||||
@@ -337,7 +337,7 @@ public sealed class Track : Entity<TrackId>
|
||||
/// <param name="ratings">The ratings of the track.</param>
|
||||
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.AddRange(ratings);
|
||||
}
|
||||
|
||||
+2
-2
@@ -67,7 +67,7 @@ public sealed class File : FileSystemItem
|
||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
||||
bool isHidden = false)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
||||
if (createPathResult.IsFailure)
|
||||
return createPathResult.Errors;
|
||||
@@ -108,7 +108,7 @@ public sealed class File : FileSystemItem
|
||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible,
|
||||
bool isHidden = false)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
File newFile = new(
|
||||
id,
|
||||
name,
|
||||
|
||||
+2
-2
@@ -45,7 +45,7 @@ public sealed class WindowsRootItem : FileSystemItem
|
||||
string name,
|
||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
Result<FileSystemPathId> createPathResult = FileSystemPathId.Create(path);
|
||||
if (createPathResult.IsFailure)
|
||||
return createPathResult.Errors;
|
||||
@@ -72,7 +72,7 @@ public sealed class WindowsRootItem : FileSystemItem
|
||||
string name,
|
||||
FileSystemItemStatus status = FileSystemItemStatus.Accessible)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
WindowsRootItem newFile = new(
|
||||
id,
|
||||
name);
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ internal class DirectoryProviderService : IDirectoryProviderService
|
||||
/// <summary>
|
||||
/// Creates a new directory with the specified name, at the specified path.
|
||||
/// </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>
|
||||
/// <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)
|
||||
|
||||
+3
-3
@@ -15,7 +15,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.
|
||||
/// <summary>
|
||||
/// Service for file system permissions.
|
||||
/// </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;
|
||||
|
||||
@@ -41,9 +41,9 @@ internal class FileSystemPermissionsService : IFileSystemPermissionsService // T
|
||||
if (platformType == PlatformType.Unix)
|
||||
return CanAccessPathUnix(path.Path, accessMode);
|
||||
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);
|
||||
#pragma warning restore CA1416 // Validate platform compatibility
|
||||
#pragma warning restore CA1416 // Validate platform compatibility.
|
||||
else
|
||||
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 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>
|
||||
/// Initializes a new instance of the <see cref="FileTypeService"/> class.
|
||||
@@ -96,9 +96,9 @@ public class FileTypeService : IFileTypeService
|
||||
// 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);
|
||||
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);
|
||||
#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);
|
||||
// Check if the extended content contains <svg.
|
||||
return extendedContent.Contains("<svg", StringComparison.OrdinalIgnoreCase);
|
||||
@@ -127,13 +127,13 @@ public class FileTypeService : IFileTypeService
|
||||
private static ImageType IdentifyHeader(byte[] firstBytes)
|
||||
{
|
||||
if (Encoding.ASCII.GetBytes("BM").SequenceEqual(firstBytes[..2]))
|
||||
return ImageType.BMP; // BMP
|
||||
return ImageType.BMP; // BMP.
|
||||
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]))
|
||||
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]))
|
||||
return ImageType.TIFF; // TIFF
|
||||
return ImageType.TIFF; // TIFF.
|
||||
if (new byte[] { 255, 216, 255, 224 }.SequenceEqual(firstBytes[..4]))
|
||||
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
|
||||
@@ -142,23 +142,23 @@ public class FileTypeService : IFileTypeService
|
||||
if (firstBytes[0] == 255 && firstBytes[1] == 216 && firstBytes[2] == 255)
|
||||
{
|
||||
if (firstBytes[3] == 225)
|
||||
return ImageType.JPEG_CANON; // JPEG CANON
|
||||
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN
|
||||
return ImageType.JPEG_CANON; // JPEG CANON.
|
||||
return ImageType.JPEG_UNKNOWN; // JPEG UNKNOWN.
|
||||
}
|
||||
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]))
|
||||
return ImageType.ICO; // ICO
|
||||
return ImageType.ICO; // ICO.
|
||||
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]))
|
||||
return ImageType.JPEG2000; // JPEG 2000
|
||||
return ImageType.JPEG2000; // JPEG 2000.
|
||||
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]))
|
||||
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]))
|
||||
return ImageType.WEBP; // WEBP
|
||||
return ImageType.WEBP; // WEBP.
|
||||
return ImageType.None;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -53,7 +53,7 @@ public interface IPathStrategy
|
||||
/// <summary>
|
||||
/// Returns a collection of characters that are invalid for paths.
|
||||
/// </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();
|
||||
|
||||
/// <summary>
|
||||
|
||||
+1
-1
@@ -314,7 +314,7 @@ public class Library : AggregateRoot<LibraryId>
|
||||
if (!_domainEvents.Any(domainEvent => domainEvent is LibraryDeletedDomainEvent))
|
||||
_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;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -64,14 +64,14 @@ public class LibraryPathPart : ValueObject
|
||||
/// </returns>
|
||||
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)
|
||||
return new LibraryPathPart(kind, string.Empty, isOptional);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(representation))
|
||||
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)
|
||||
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>
|
||||
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.");
|
||||
job.LibraryId = libraryId;
|
||||
return job;
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ public class ParsedLibraryPath : ValueObject
|
||||
/// <returns>A list of items defining the equality.</returns>
|
||||
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))
|
||||
{
|
||||
yield return capturedValue.Key;
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class MediaContributorId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
||||
public static MediaContributorId CreateUnique()
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new MediaContributorId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class MediaContributorId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="MediaContributorId"/> instance.</returns>
|
||||
public static MediaContributorId Create(Guid value)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new MediaContributorId(value);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -58,7 +58,7 @@ public sealed class Movie : Entity<MovieId>
|
||||
/// <returns>The created <see cref="Movie"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ public sealed class Movie : Entity<MovieId>
|
||||
/// <returns>The created <see cref="Movie"/>.</returns>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -27,7 +27,7 @@ public sealed class MovieId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
||||
public static MovieId CreateUnique()
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new MovieId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public sealed class MovieId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="MovieId"/> instance.</returns>
|
||||
public static MovieId Create(Guid value)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new MovieId(value);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class EpisodeId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
||||
public static EpisodeId CreateUnique()
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new EpisodeId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class EpisodeId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="EpisodeId"/> instance.</returns>
|
||||
public static EpisodeId Create(Guid value)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new EpisodeId(value);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class SeasonId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
||||
public static SeasonId CreateUnique()
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new SeasonId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class SeasonId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="SeasonId"/> instance.</returns>
|
||||
public static SeasonId Create(Guid value)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new SeasonId(value);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -25,7 +25,7 @@ public sealed class TvShowId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
||||
public static TvShowId CreateUnique()
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new TvShowId(Guid.NewGuid());
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ public sealed class TvShowId : EntityId<Guid>
|
||||
/// <returns>The created <see cref="TvShowId"/> instance.</returns>
|
||||
public static TvShowId Create(Guid value)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new TvShowId(value);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -64,7 +64,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
|
||||
bool isComplete,
|
||||
List<Book> books)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new BookSeries(
|
||||
id,
|
||||
metadata,
|
||||
@@ -87,7 +87,7 @@ public sealed class BookSeries : Entity<BookSeriesId>
|
||||
bool isComplete,
|
||||
List<Book> books)
|
||||
{
|
||||
// TODO: enforce invariants
|
||||
// TODO: enforce invariants.
|
||||
return new BookSeries(
|
||||
BookSeriesId.CreateUnique(),
|
||||
metadata,
|
||||
|
||||
@@ -32,9 +32,9 @@ public static class SharedConfiguration
|
||||
configuration.SetBasePath(basePath);
|
||||
configuration.AddJsonFile("appsettings.shared.json", optional: false, 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>()
|
||||
.Bind(configuration.GetRequiredSection(DatabaseSettingsDto.SECTION_NAME))
|
||||
.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>
|
||||
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)
|
||||
yield break;
|
||||
// yield the current level exception itself
|
||||
// Yield the current level exception itself.
|
||||
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)
|
||||
foreach (Exception? innerException in aggregateException.InnerExceptions.SelectMany(innerException => innerException.GetInnerExceptions(maximumDepth - 1)))
|
||||
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) ?? [])
|
||||
yield return innerException;
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ public static class OptionsBuilderValidationUtilities
|
||||
/// <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
|
||||
{
|
||||
// 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>>(
|
||||
serviceProvider => new ValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
|
||||
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>
|
||||
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)
|
||||
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)
|
||||
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}'")];
|
||||
|
||||
// and return them with a failure result
|
||||
// And return them with a failure result.
|
||||
return ValidateOptionsResult.Fail(errors);
|
||||
}
|
||||
}
|
||||
@@ -36,7 +36,7 @@ public class CorsSettingsDtoValidator : AbstractValidator<CorsSettingsDto>
|
||||
private bool BeValidOrigin(string origin)
|
||||
{
|
||||
if (origin == "*")
|
||||
return true; // wildcard allowed without credentials
|
||||
return true; // Wildcard allowed without credentials.
|
||||
return Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && !origin.EndsWith('/');
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ public class JwtTokenGenerator : IJwtTokenGenerator
|
||||
/// <returns>The generated JWT token.</returns>
|
||||
public string GenerateToken(string id, string username)
|
||||
{
|
||||
// use a symmetric key approach
|
||||
// Use a symmetric key approach.
|
||||
SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256);
|
||||
Claim[] claims =
|
||||
[
|
||||
|
||||
@@ -22,16 +22,16 @@ public class QRCodeGenerator : IQRCodeGenerator
|
||||
/// <returns>Data URI for the QR code.</returns>
|
||||
public string GenerateQrCodeDataUri(string username, byte[] secret)
|
||||
{
|
||||
// convert secret to Base32
|
||||
// Convert secret to Base32.
|
||||
string base32Secret = Base32Encoding.ToString(secret);
|
||||
// build the otpauth URI
|
||||
// Build the otpauth URI.
|
||||
string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}";
|
||||
// generate QR Code
|
||||
// Generate QR Code.
|
||||
QRCoder.QRCodeGenerator qrGenerator = new();
|
||||
QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q);
|
||||
PngByteQRCode qrCode = new(qrData);
|
||||
// convert QR Code to Data URI
|
||||
byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed
|
||||
// Convert QR Code to Data URI.
|
||||
byte[] pngBytes = qrCode.GetGraphic(20); // Specify a pixel size if needed.
|
||||
string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes);
|
||||
return dataUri;
|
||||
}
|
||||
|
||||
@@ -17,11 +17,11 @@ public class TokenGenerator : ITokenGenerator
|
||||
/// <returns>A secure token.</returns>
|
||||
public string GenerateToken()
|
||||
{
|
||||
// allocate an array for the token data
|
||||
// Allocate an array for the token data.
|
||||
byte[] tokenData = new byte[32];
|
||||
// fill the array with a cryptographically strong sequence of random values
|
||||
// Fill the array with a cryptographically strong sequence of random values.
|
||||
RandomNumberGenerator.Fill(tokenData);
|
||||
// convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=')
|
||||
// Convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=').
|
||||
return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public class TotpTokenGenerator : ITotpTokenGenerator
|
||||
/// <returns>The generated TOTP secret.</returns>
|
||||
public byte[] GenerateSecret()
|
||||
{
|
||||
return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP
|
||||
return KeyGeneration.GenerateRandomKey(); // Generate a random key for TOTP.
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -28,7 +28,7 @@ public class TotpTokenGenerator : ITotpTokenGenerator
|
||||
public bool ValidateToken(byte[] secret, string token)
|
||||
{
|
||||
Totp totp = new(secret);
|
||||
// verify the TOTP token, allowing for slight time drifts between server and client
|
||||
// Verify the TOTP token, allowing for slight time drifts between server and client.
|
||||
return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -956,7 +956,7 @@ internal sealed class TrackNormalizationService : ITrackNormalizationService, ID
|
||||
|
||||
FileInfo segmentFile = new(Path.Combine(temporaryPath, fileName));
|
||||
decimal durationSeconds = endSeconds - startSeconds;
|
||||
// ffmpeg can append a final segment whose time range is empty when the last frame ends exactly on a segment boundary. That segment is
|
||||
// FFmpeg can append a final segment whose time range is empty when the last frame ends exactly on a segment boundary. That segment is
|
||||
// discarded after the list is sorted, but a zero duration anywhere else, or a missing or empty segment that is supposed to carry audio, is a malformed production.
|
||||
if (durationSeconds == 0)
|
||||
{
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancel
|
||||
if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan))
|
||||
{
|
||||
scan.Cancel();
|
||||
// remove and dispose after cancellation
|
||||
// Remove and dispose after cancellation.
|
||||
if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan))
|
||||
removedScan?.Dispose();
|
||||
}
|
||||
@@ -61,7 +61,7 @@ internal class MediaLibrariesScanCancellationTracker : IMediaLibrariesScanCancel
|
||||
if (_runningScans.TryGetValue(mediaLibraryScanCompositeId, out CancellationTokenSource? scan))
|
||||
{
|
||||
scan.Cancel();
|
||||
// remove and dispose after cancellation
|
||||
// Remove and dispose after cancellation.
|
||||
if (_runningScans.TryRemove(mediaLibraryScanCompositeId, out CancellationTokenSource? removedScan))
|
||||
removedScan?.Dispose();
|
||||
}
|
||||
|
||||
+1
-1
@@ -205,7 +205,7 @@ internal sealed class BooksMediaLibraryScanMetadataEnricher : IMediaLibraryScanM
|
||||
BookMetadataLookupDto bookMetadataLookup = new(
|
||||
LibraryId: bookEntity.LibraryId,
|
||||
Path: bookEntity.Path,
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: This should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results.
|
||||
Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results.
|
||||
OpenLibraryId: bookEntity.OpenLibraryId,
|
||||
Title: bookEntity.Title,
|
||||
Author: null,
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace Lumina.Infrastructure.Core.Plugins;
|
||||
/// </summary>
|
||||
internal sealed class PluginInstaller : IPluginInstaller
|
||||
{
|
||||
// the install mutates the shared plugins directory, so the operations are serialized per resolved directory.
|
||||
// The install mutates the shared plugins directory, so the operations are serialized per resolved directory.
|
||||
// A per-instance gate is NOT enough: several hosts can run against the same plugins directory at once (for
|
||||
// example the parallel in-memory hosts started by the test factories), so the gate is keyed on the directory.
|
||||
private static readonly ConcurrentDictionary<string, SemaphoreSlim> s_pluginDirectoryGates = new(StringComparer.Ordinal);
|
||||
|
||||
@@ -33,7 +33,7 @@ internal sealed class PluginLoadContext : AssemblyLoadContext
|
||||
if (assemblyName.Name is null)
|
||||
return null;
|
||||
|
||||
// try to resolve the assembly from the default context first, so that the plugin shares the host and framework assemblies
|
||||
// Try to resolve the assembly from the default context first, so that the plugin shares the host and framework assemblies.
|
||||
try
|
||||
{
|
||||
return AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
|
||||
@@ -42,7 +42,7 @@ internal sealed class PluginLoadContext : AssemblyLoadContext
|
||||
{
|
||||
}
|
||||
|
||||
// fall back to resolving the assembly from the plugin directory
|
||||
// Fall back to resolving the assembly from the plugin directory.
|
||||
string dependencyPath = Path.Combine(_pluginDirectory, assemblyName.Name + ".dll");
|
||||
if (File.Exists(dependencyPath))
|
||||
return LoadFromAssemblyPath(dependencyPath);
|
||||
|
||||
@@ -37,7 +37,7 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
|
||||
if (string.IsNullOrEmpty(plaintext))
|
||||
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
|
||||
|
||||
// Generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
|
||||
// Generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts.
|
||||
byte[] iv = new byte[16];
|
||||
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
|
||||
rng.GetBytes(iv);
|
||||
@@ -48,21 +48,21 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
|
||||
// Encrypt the plaintext
|
||||
// Encrypt the plaintext.
|
||||
using ICryptoTransform encryptor = aes.CreateEncryptor();
|
||||
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
|
||||
|
||||
// Compute SHA-256 checksum of the plaintext
|
||||
// Compute SHA-256 checksum of the plaintext.
|
||||
byte[] checksum = SHA256.HashData(plaintextBytes);
|
||||
|
||||
// Combine IV, ciphertext, and checksum
|
||||
// Combine IV, ciphertext, and checksum.
|
||||
byte[] combined = new byte[iv.Length + ciphertext.Length + checksum.Length];
|
||||
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
|
||||
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
|
||||
Buffer.BlockCopy(checksum, 0, combined, iv.Length + ciphertext.Length, checksum.Length);
|
||||
|
||||
// Return the combined data as a Base64-encoded string
|
||||
// Return the combined data as a Base64-encoded string.
|
||||
return Convert.ToBase64String(combined);
|
||||
}
|
||||
|
||||
@@ -78,14 +78,14 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
|
||||
if (string.IsNullOrEmpty(ciphertext))
|
||||
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
|
||||
|
||||
// Decode the combined data (IV + ciphertext + checksum) from Base64
|
||||
// Decode the combined data (IV + ciphertext + checksum) from Base64.
|
||||
byte[] combined = Convert.FromBase64String(ciphertext);
|
||||
|
||||
// Validate the minimum length (16 bytes for IV + 32 bytes for checksum)
|
||||
// Validate the minimum length (16 bytes for IV + 32 bytes for checksum).
|
||||
if (combined.Length < 16 + 32)
|
||||
throw new ArgumentException("Invalid ciphertext");
|
||||
|
||||
// Extract IV, ciphertext, and checksum from the combined data
|
||||
// Extract IV, ciphertext, and checksum from the combined data.
|
||||
byte[] iv = new byte[16];
|
||||
byte[] checksum = new byte[32];
|
||||
byte[] encryptedData = new byte[combined.Length - 16 - 32];
|
||||
@@ -100,18 +100,18 @@ public sealed class CryptographyService : ICryptographyService, IDisposable
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
|
||||
// Decrypt the encrypted data
|
||||
// Decrypt the encrypted data.
|
||||
using ICryptoTransform decryptor = aes.CreateDecryptor();
|
||||
byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
|
||||
|
||||
// Compute the checksum of the decrypted data and validate against the provided checksum
|
||||
// Compute the checksum of the decrypted data and validate against the provided checksum.
|
||||
byte[] computedChecksum = SHA256.HashData(decryptedBytes);
|
||||
|
||||
// If checksums do not match, throw a CryptographicException indicating potential corruption
|
||||
// If checksums do not match, throw a CryptographicException indicating potential corruption.
|
||||
if (!computedChecksum.SequenceEqual(checksum))
|
||||
throw new CryptographicException("Checksum validation failed. The data may be corrupted.");
|
||||
|
||||
// Return the decrypted plaintext as a UTF-8 string
|
||||
// Return the decrypted plaintext as a UTF-8 string.
|
||||
return Encoding.UTF8.GetString(decryptedBytes);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user