Merge pull request #141 from BinaryAlley/feature/implement-plugin-system-for-metadata-scrapping

Feature/implement plugin system for metadata scrapping
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-12 15:14:59 -07:00
commit 76db0c1597
564 files changed
+14719 -978

No files matched your search

+5 -2
View File
@@ -65,5 +65,8 @@ $RECYCLE.BIN/
*.sql
*.sqlite
# Agent configuration
AGENTS.md
# AI
AGENTS.[Mm][Dd]
agents.[Mm][Dd]
SKILL.[Mm][Dd]
skill.[Mm][Dd]
+9 -4
View File
@@ -21,6 +21,8 @@ POST api/v1/books
```json
{
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -122,6 +124,9 @@ POST api/v1/books
```json
{
"id": "32b336e8-dafc-4a08-9dec-9454e66dd55d",
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"publisher": "Houghton Mifflin",
"pageCount": 398,
@@ -205,9 +210,9 @@ POST api/v1/books
"voteCount": 87654
}
],
"id": {
"value": "32b336e8-dafc-4a08-9dec-9454e66dd55d"
}
"metadataStatus": "Pending",
"lastMetadataUpdateUtc": null,
"metadataProvider": null
}
```
@@ -216,7 +221,7 @@ POST api/v1/books
#### Get Books Request
```js
GET /books
GET /books?libraryId=3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a
```
#### Get Books Response
@@ -0,0 +1,47 @@
# Architecture Decision Record (ADR): 0010 - Failure Semantics of the Best-Effort Metadata Enrichment Job
## Status
**Accepted** (2026-08-09)
## Context
ADR-0009 established that every media library scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`. That decision applies to the mandatory scan jobs: file system discovery, scan diff, content hashing and scan results save. These jobs are transactional in nature, and a failure in any of them means the file state of the library was not committed.
The metadata enrichment phase runs after the scan results save job, once the file state of the library is committed and the books are materialized. The enrichment phase is best-effort: a book whose metadata could not be retrieved is still browsable with its shell metadata (path and filename-derived title), and a crash mid-enrichment must not roll back the already committed scan results, nor hide the successfully enriched books. This was an explicit product decision: partial enrichment survives a crash, and the scan is not considered failed because a remote metadata provider was unreachable or a provider crashed.
## Decision
The metadata enrichment job (`MediaLibraryScanMetadataEnrichmentJob`) is a best-effort job with failure semantics that differ from the mandatory jobs of ADR-0009:
- Per-book failures are isolated: a metadata provider that throws, returns unusable metadata, or fails to be applied marks the book as `Failed` (`MetadataStatus.Failed`) and moves to the next book. The other providers are still tried for the same book, and the other books are still processed.
- Per-provider failures are isolated: a crashing metadata provider does not prevent the other providers from being tried, in their configured order.
- The scan is considered completed (`LibraryScanFinishedDomainEvent`) after the enrichment phase, even when some books failed to be enriched. The failure is recorded on the books, not on the scan.
- Only a host-side catastrophic failure of the enrichment job itself (e.g., a storage error) fails the scan, through the existing catch-all of ADR-0009. In that case the file state is already committed, and a re-scan retries the enrichment.
The `MediaLibraryScanResultsSaveJob` no longer publishes `LibraryScanFinishedDomainEvent`. The event is published by the last job of the directed acyclic job graph: the save job when the library does not permit downloading data from the web (no enrichment phase), or the metadata enrichment job otherwise.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Partial enrichment | Books successfully enriched before a crash stay browsable and enriched |
| Provider isolation | A crashing provider does not prevent other providers from being tried |
| Scan completion | The scan reaches a completed state regardless of enrichment outcome |
| Retryability | Books with `MetadataStatus.Failed` or `Pending` are re-enriched on the next scan |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Host failures still fail | Only host-side storage errors fail the scan; re-scan retries enrichment |
| No per-provider audit trail | Books record the failed status; per-provider error detail is a future refinement |
## Alternatives Considered
### 1. Fail the scan on any enrichment failure
Keep ADR-0009 semantics for the enrichment job.
**Rejected**: The file state is already committed, and partial enrichment is better than failing a scan that saved the library. Failing the scan would also roll back nothing, while misleading the user about the scan outcome.
### 2. Run enrichment outside the scan lifetime
Enrich the books asynchronously after the scan, decoupled from the scan progress and cancellation.
**Rejected**: This contradicts the decision that the metadata enrichment phase is part of the scan lifetime, covered by the scan progress reporting and cancellation machinery, so that the scan progress reaches completion only when the metadata is downloaded.
+2
View File
@@ -2,6 +2,8 @@ POST {{host}}/api/v1/books
Content-Type: application/json
{
"libraryId": "00000000-0000-0000-0000-000000000000",
"path": "/books/the-fellowship-of-the-ring.epub",
"metadata": {
"title": "The Fellowship of the Ring",
"originalTitle": "The Fellowship of the Ring",
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core;
using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Threading;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
/// <summary>
/// Provides extension methods for registering the Open Library metadata provider services.
/// </summary>
internal static class OpenLibraryServices
{
/// <summary>
/// Registers the Open Library book metadata provider and its dependencies, associated with the plugin that provides it.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <param name="settingsCallback">Action used to configure the <see cref="OpenLibrarySettingsDto"/>.</param>
/// <returns>The service collection, for chaining.</returns>
internal static IServiceCollection AddOpenLibraryBookMetadataProvider(this IServiceCollection services, Guid pluginId, Action<OpenLibrarySettingsDto>? settingsCallback = null)
{
ArgumentNullException.ThrowIfNull(services);
// Build the runtime settings per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
services.TryAddScoped(serviceProvider =>
{
OpenLibrarySettingsDto openLibrarySettings = new();
settingsCallback?.Invoke(openLibrarySettings);
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
if (settingsStore is not null)
{
IReadOnlyDictionary<string, string>? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult();
if (storedSettings is not null)
OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings);
}
return openLibrarySettings;
});
services.AddHttpClient<OpenLibraryHttpClient>();
// Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations.
services.AddKeyedTransient<IRemoteMetadataProvider, OpenLibraryBookMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an author from the Open Library API.
/// </summary>
internal sealed record OpenLibraryAuthorResponse
{
/// <summary>
/// Gets the key of the author.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; }
/// <summary>
/// Gets the name of the author.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the personal name of the author.
/// </summary>
[JsonPropertyName("personal_name")]
public string? PersonalName { get; init; }
}
@@ -0,0 +1,145 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an edition from the Open Library API.
/// </summary>
internal sealed record OpenLibraryEditionResponse
{
/// <summary>
/// Gets the key of the edition.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; }
/// <summary>
/// Gets the title of the edition.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the subtitle of the edition.
/// </summary>
[JsonPropertyName("subtitle")]
public string? Subtitle { get; init; }
/// <summary>
/// Gets the notes of the edition.
/// </summary>
[JsonPropertyName("notes")]
public JsonElement Notes { get; init; }
/// <summary>
/// Gets the publication date of the edition.
/// </summary>
[JsonPropertyName("publish_date")]
public string? PublishDate { get; init; }
/// <summary>
/// Gets the publishers of the edition.
/// </summary>
[JsonPropertyName("publishers")]
public List<string> Publishers { get; init; } = [];
/// <summary>
/// Gets the publication places of the edition.
/// </summary>
[JsonPropertyName("publish_places")]
public List<string> PublishPlaces { get; init; } = [];
/// <summary>
/// Gets the number of pages of the edition.
/// </summary>
[JsonPropertyName("number_of_pages")]
public int? NumberOfPages { get; init; }
/// <summary>
/// Gets the physical format of the edition.
/// </summary>
[JsonPropertyName("physical_format")]
public string? PhysicalFormat { get; init; }
/// <summary>
/// Gets the name of the edition.
/// </summary>
[JsonPropertyName("edition_name")]
public string? EditionName { get; init; }
/// <summary>
/// Gets the series the edition belongs to.
/// </summary>
[JsonPropertyName("series")]
public List<string> Series { get; init; } = [];
/// <summary>
/// Gets the volume of the edition within its series.
/// </summary>
[JsonPropertyName("volume")]
public string? Volume { get; init; }
/// <summary>
/// Gets the ISBN-10 identifiers of the edition.
/// </summary>
[JsonPropertyName("isbn_10")]
public List<string> Isbn10 { get; init; } = [];
/// <summary>
/// Gets the ISBN-13 identifiers of the edition.
/// </summary>
[JsonPropertyName("isbn_13")]
public List<string> Isbn13 { get; init; } = [];
/// <summary>
/// Gets the LCCN identifiers of the edition.
/// </summary>
[JsonPropertyName("lccn")]
public List<string> Lccn { get; init; } = [];
/// <summary>
/// Gets the OCLC numbers of the edition.
/// </summary>
[JsonPropertyName("oclc_numbers")]
public List<string> OclcNumbers { get; init; } = [];
/// <summary>
/// Gets the external identifiers of the edition, keyed by identifier name.
/// </summary>
[JsonPropertyName("identifiers")]
public JsonElement Identifiers { get; init; }
/// <summary>
/// Gets the source records of the edition.
/// </summary>
[JsonPropertyName("source_records")]
public List<string> SourceRecords { get; init; } = [];
/// <summary>
/// Gets the languages of the edition.
/// </summary>
[JsonPropertyName("languages")]
public List<OpenLibraryKeyReferenceResponse> Languages { get; init; } = [];
/// <summary>
/// Gets the authors of the edition.
/// </summary>
[JsonPropertyName("authors")]
public List<OpenLibraryKeyReferenceResponse> Authors { get; init; } = [];
/// <summary>
/// Gets the works the edition belongs to.
/// </summary>
[JsonPropertyName("works")]
public List<OpenLibraryKeyReferenceResponse> Works { get; init; } = [];
/// <summary>
/// Gets the contributions of the edition.
/// </summary>
[JsonPropertyName("contributions")]
public List<string> Contributions { get; init; } = [];
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the editions of a work from the Open Library API.
/// </summary>
internal sealed record OpenLibraryEditionsResponse
{
/// <summary>
/// Gets the editions of the work.
/// </summary>
[JsonPropertyName("entries")]
public List<OpenLibraryEditionResponse> Entries { get; init; } = [];
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a reference to a resource of the Open Library API by its key.
/// </summary>
internal sealed record OpenLibraryKeyReferenceResponse
{
/// <summary>
/// Gets the key of the referenced resource.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the summary of the ratings of a work from the Open Library API.
/// </summary>
internal sealed record OpenLibraryRatingSummaryResponse
{
/// <summary>
/// Gets the average rating of the work.
/// </summary>
[JsonPropertyName("average")]
public decimal? Average { get; init; }
/// <summary>
/// Gets the number of ratings of the work.
/// </summary>
[JsonPropertyName("count")]
public int? Count { get; init; }
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the ratings of a work from the Open Library API.
/// </summary>
internal sealed record OpenLibraryRatingsResponse
{
/// <summary>
/// Gets the summary of the ratings of the work.
/// </summary>
[JsonPropertyName("summary")]
public OpenLibraryRatingSummaryResponse? Summary { get; init; }
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a search document from the Open Library API.
/// </summary>
internal sealed record OpenLibrarySearchDocumentResponse
{
/// <summary>
/// Gets the key of the search document.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; }
/// <summary>
/// Gets the title of the search document.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the author names of the search document.
/// </summary>
[JsonPropertyName("author_name")]
public List<string> AuthorNames { get; init; } = [];
/// <summary>
/// Gets the author keys of the search document.
/// </summary>
[JsonPropertyName("author_key")]
public List<string> AuthorKeys { get; init; } = [];
/// <summary>
/// Gets the first publication year of the search document.
/// </summary>
[JsonPropertyName("first_publish_year")]
public int? FirstPublishYear { get; init; }
/// <summary>
/// Gets the edition keys of the search document.
/// </summary>
[JsonPropertyName("edition_key")]
public List<string> EditionKeys { get; init; } = [];
/// <summary>
/// Gets the ISBNs of the search document.
/// </summary>
[JsonPropertyName("isbn")]
public List<string> Isbns { get; init; } = [];
/// <summary>
/// Gets the languages of the search document.
/// </summary>
[JsonPropertyName("language")]
public List<string> Languages { get; init; } = [];
/// <summary>
/// Gets the publishers of the search document.
/// </summary>
[JsonPropertyName("publisher")]
public List<string> Publishers { get; init; } = [];
/// <summary>
/// Gets the subjects of the search document.
/// </summary>
[JsonPropertyName("subject")]
public List<string> Subjects { get; init; } = [];
/// <summary>
/// Gets the publication places of the search document.
/// </summary>
[JsonPropertyName("publish_place")]
public List<string> PublishPlaces { get; init; } = [];
/// <summary>
/// Gets the median number of pages of the search document.
/// </summary>
[JsonPropertyName("number_of_pages_median")]
public int? NumberOfPagesMedian { get; init; }
/// <summary>
/// Gets the average rating of the search document.
/// </summary>
[JsonPropertyName("ratings_average")]
public decimal? RatingsAverage { get; init; }
/// <summary>
/// Gets the number of ratings of the search document.
/// </summary>
[JsonPropertyName("ratings_count")]
public int? RatingsCount { get; init; }
/// <summary>
/// Gets the Amazon identifiers of the search document.
/// </summary>
[JsonPropertyName("id_amazon")]
public List<string> AmazonIds { get; init; } = [];
/// <summary>
/// Gets the Goodreads identifiers of the search document.
/// </summary>
[JsonPropertyName("id_goodreads")]
public List<string> GoodreadsIds { get; init; } = [];
/// <summary>
/// Gets the Google identifiers of the search document.
/// </summary>
[JsonPropertyName("id_google")]
public List<string> GoogleIds { get; init; } = [];
/// <summary>
/// Gets the LibraryThing identifiers of the search document.
/// </summary>
[JsonPropertyName("id_librarything")]
public List<string> LibraryThingIds { get; init; } = [];
/// <summary>
/// Gets the LCCN identifiers of the search document.
/// </summary>
[JsonPropertyName("lccn")]
public List<string> Lccn { get; init; } = [];
/// <summary>
/// Gets the OCLC identifiers of the search document.
/// </summary>
[JsonPropertyName("oclc")]
public List<string> Oclc { get; init; } = [];
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a search from the Open Library API.
/// </summary>
internal sealed record OpenLibrarySearchResponse
{
/// <summary>
/// Gets the documents that match the search.
/// </summary>
[JsonPropertyName("docs")]
public List<OpenLibrarySearchDocumentResponse> Documents { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an author reference within a work from the Open Library API.
/// </summary>
internal sealed record OpenLibraryWorkAuthorResponse
{
/// <summary>
/// Gets the author of the work.
/// </summary>
[JsonPropertyName("author")]
public OpenLibraryKeyReferenceResponse? Author { get; init; }
/// <summary>
/// Gets the key of the author reference.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; } // Older records can contain a direct key rather than an author wrapper.
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a work from the Open Library API.
/// </summary>
internal sealed record OpenLibraryWorkResponse
{
/// <summary>
/// Gets the key of the work.
/// </summary>
[JsonPropertyName("key")]
public string? Key { get; init; }
/// <summary>
/// Gets the title of the work.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the original title of the work.
/// </summary>
[JsonPropertyName("original_title")]
public string? OriginalTitle { get; init; }
/// <summary>
/// Gets the description of the work.
/// </summary>
[JsonPropertyName("description")]
public JsonElement Description { get; init; }
/// <summary>
/// Gets the first publication date of the work.
/// </summary>
[JsonPropertyName("first_publish_date")]
public string? FirstPublishDate { get; init; }
/// <summary>
/// Gets the subjects of the work.
/// </summary>
[JsonPropertyName("subjects")]
public List<string> Subjects { get; init; } = [];
/// <summary>
/// Gets the genres of the work.
/// </summary>
[JsonPropertyName("genres")]
public List<string> Genres { get; init; } = [];
/// <summary>
/// Gets the authors of the work.
/// </summary>
[JsonPropertyName("authors")]
public List<OpenLibraryWorkAuthorResponse> Authors { get; init; } = [];
/// <summary>
/// Gets the original languages of the work.
/// </summary>
[JsonPropertyName("original_languages")]
public List<OpenLibraryKeyReferenceResponse> OriginalLanguages { get; init; } = [];
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the Open Library metadata plugin.
/// </summary>
internal sealed class OpenLibrarySettingsDto
{
/// <summary>
/// Gets or sets the user agent sent with every request to the Open Library API.
/// </summary>
public string UserAgent { get; set; } = "Lumina-OpenLibrary/1.0";
/// <summary>
/// Gets or sets the contact email sent with every request to the Open Library API.
/// </summary>
public string? ContactEmail { get; set; }
/// <summary>
/// Gets or sets the maximum number of results returned by a single search.
/// </summary>
public int SearchResultLimit { get; set; } = 10;
/// <summary>
/// Gets or sets the maximum number of editions fetched for a single work.
/// </summary>
public int WorkEditionLimit { get; set; } = 50;
/// <summary>
/// Gets or sets the minimum interval between consecutive requests to the Open Library API.
/// </summary>
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.1);
}
@@ -0,0 +1,252 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core.Mapping;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.OpenLibrary.Core.Api;
/// <summary>
/// HTTP client that calls the Open Library API and deserializes its JSON responses into typed response models.
/// </summary>
internal sealed class OpenLibraryHttpClient
{
private readonly HttpClient _httpClient;
private readonly OpenLibrarySettingsDto _openLibrarySettings;
private readonly SemaphoreSlim _requestGate = new(1, 1);
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
private const string SEARCH_FIELDS =
"key,title,author_name,author_key,first_publish_year,edition_key,isbn," +
"language,publisher,subject,publish_place,number_of_pages_median," +
"ratings_average,ratings_count,id_amazon,id_goodreads,id_google," +
"id_librarything,lccn,oclc";
/// <summary>
/// Initializes a new instance of the <see cref="OpenLibraryHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the Open Library API.</param>
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings)
{
_httpClient = httpClient;
_openLibrarySettings = openLibrarySettings;
_httpClient.BaseAddress ??= new("https://openlibrary.org/");
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(openLibrarySettings.UserAgent);
if (!string.IsNullOrWhiteSpace(openLibrarySettings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null)
_httpClient.DefaultRequestHeaders.From = openLibrarySettings.ContactEmail!;
}
/// <summary>
/// Gets an edition by its ISBN.
/// </summary>
/// <param name="isbn">The ISBN of the edition to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The edition, or <see langword="null"/> when no edition was found for the ISBN.</returns>
public Task<OpenLibraryEditionResponse?> GetEditionByIsbnAsync(string isbn, CancellationToken cancellationToken)
{
string normalized = OpenLibraryMapper.NormalizeIsbn(isbn);
return GetJsonOrNullAsync<OpenLibraryEditionResponse>($"isbn/{Uri.EscapeDataString(normalized)}.json", cancellationToken);
}
/// <summary>
/// Gets an edition by its Open Library edition identifier.
/// </summary>
/// <param name="editionId">The Open Library edition identifier of the edition to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The edition, or <see langword="null"/> when no edition was found for the identifier.</returns>
public Task<OpenLibraryEditionResponse?> GetEditionAsync(string editionId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<OpenLibraryEditionResponse>($"books/{Uri.EscapeDataString(NormalizeOlid(editionId, 'M'))}.json", cancellationToken);
}
/// <summary>
/// Gets a work by its Open Library work identifier.
/// </summary>
/// <param name="workId">The Open Library work identifier of the work to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work, or <see langword="null"/> when no work was found for the identifier.</returns>
public Task<OpenLibraryWorkResponse?> GetWorkAsync(string workId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<OpenLibraryWorkResponse>($"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}.json", cancellationToken);
}
/// <summary>
/// Gets an author by its Open Library author identifier.
/// </summary>
/// <param name="authorId">The Open Library author identifier of the author to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The author, or <see langword="null"/> when no author was found for the identifier.</returns>
public Task<OpenLibraryAuthorResponse?> GetAuthorAsync(string authorId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<OpenLibraryAuthorResponse>($"authors/{Uri.EscapeDataString(NormalizeOlid(authorId, 'A'))}.json", cancellationToken);
}
/// <summary>
/// Gets the ratings of a work by its Open Library work identifier.
/// </summary>
/// <param name="workId">The Open Library work identifier of the work to get the ratings for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The ratings, or <see langword="null"/> when no ratings were found for the work.</returns>
public Task<OpenLibraryRatingsResponse?> GetRatingsAsync(string workId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<OpenLibraryRatingsResponse>($"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}/ratings.json", cancellationToken);
}
/// <summary>
/// Gets a list of editions for a work by its Open Library work identifier.
/// </summary>
/// <param name="workId">The Open Library work identifier of the work to get the editions for.</param>
/// <param name="limit">The maximum number of editions to get.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of editions for the work.</returns>
public async Task<IReadOnlyList<OpenLibraryEditionResponse>> GetEditionsAsync(string workId, int limit, CancellationToken cancellationToken)
{
OpenLibraryEditionsResponse? response = await GetJsonOrNullAsync<OpenLibraryEditionsResponse>(
$"works/{Uri.EscapeDataString(NormalizeOlid(workId, 'W'))}/editions.json" +
$"?limit={Math.Clamp(limit, 1, 1000).ToString(CultureInfo.InvariantCulture)}",
cancellationToken)
.ConfigureAwait(false);
return response?.Entries ?? [];
}
/// <summary>
/// Searches Open Library for books matching the lookup.
/// </summary>
/// <param name="lookup">The lookup describing the book to search for.</param>
/// <param name="limit">The maximum number of search results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of search results for the lookup.</returns>
public async Task<IReadOnlyList<OpenLibrarySearchDocumentResponse>> SearchAsync(BookMetadataLookupDto lookup, int limit, CancellationToken cancellationToken)
{
List<KeyValuePair<string, string>> parameters = [];
string? isbn = lookup.Isbn;
string? title = lookup.Title;
string? author = lookup.Author;
string? languageCode = lookup.LanguageCode;
if (!string.IsNullOrWhiteSpace(isbn))
parameters.Add(new("isbn", OpenLibraryMapper.NormalizeIsbn(isbn)));
if (!string.IsNullOrWhiteSpace(title))
parameters.Add(new("title", title.Trim()));
if (!string.IsNullOrWhiteSpace(author))
parameters.Add(new("author", author.Trim()));
if (!string.IsNullOrWhiteSpace(languageCode))
parameters.Add(new("language", languageCode.Trim()));
parameters.Add(new("fields", SEARCH_FIELDS));
parameters.Add(new("limit", Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)));
string query = string.Join("&", parameters.Select(pair => $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}"));
OpenLibrarySearchResponse? response = await GetJsonOrNullAsync<OpenLibrarySearchResponse>($"search.json?{query}", cancellationToken).ConfigureAwait(false);
return response?.Documents ?? [];
}
/// <summary>
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to deserialize the JSON response into.</typeparam>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
private async Task<T?> GetJsonOrNullAsync<T>(string relativeUrl, CancellationToken cancellationToken)
{
for (int attempt = 0; attempt < 3; attempt++)
{
using HttpResponseMessage response = await SendAsync(relativeUrl, cancellationToken).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NotFound)
return default;
if (response.IsSuccessStatusCode)
{
await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return await JsonSerializer.DeserializeAsync<T>(stream, s_serializerOptions, cancellationToken).ConfigureAwait(false);
}
if (attempt < 2 && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
{
TimeSpan retryDelay = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
continue;
}
response.EnsureSuccessStatusCode();
}
return default;
}
/// <summary>
/// Sends a GET request to the Open Library API, throttled to respect the configured minimum request interval.
/// </summary>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendAsync(string relativeUrl, CancellationToken cancellationToken)
{
await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval;
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
HttpRequestMessage request = new(HttpMethod.Get, relativeUrl);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
_lastRequestAt = DateTimeOffset.UtcNow;
return response;
}
finally
{
_requestGate.Release();
}
}
/// <summary>
/// Normalizes a raw Open Library identifier into its canonical OLID form.
/// </summary>
/// <param name="value">The raw Open Library identifier to normalize.</param>
/// <param name="expectedSuffix">The suffix the OLID must end with, for example <c>M</c> for editions.</param>
/// <returns>The canonical OLID.</returns>
/// <exception cref="ArgumentException">The value is not a valid Open Library identifier.</exception>
private static string NormalizeOlid(string value, char expectedSuffix)
{
string id = value.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant();
if (id.Length < 4 || !id.StartsWith("OL", StringComparison.Ordinal) || id[^1] != expectedSuffix || !id.AsSpan(2, id.Length - 3).ToString().All(char.IsDigit))
throw new ArgumentException($"'{value}' is not a valid Open Library {expectedSuffix} identifier.", nameof(value));
return id;
}
}
@@ -0,0 +1,532 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Plugins.OpenLibrary.Core.Mapping;
/// <summary>
/// Maps Open Library API responses into the application's book request DTOs.
/// </summary>
internal static partial class OpenLibraryMapper
{
/// <summary>
/// Matches a contribution in the form <c>Name (Role)</c>.
/// </summary>
[GeneratedRegex(@"^(?<name>.+?)\s*\((?<role>[^)]+)\)\s*$")]
private static partial Regex ContributorPattern();
/// <summary>
/// Matches a volume number in a series or volume string.
/// </summary>
[GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?<number>\d+)\b", RegexOptions.IgnoreCase)]
private static partial Regex VolumePattern();
/// <summary>
/// Matches a four digit year.
/// </summary>
[GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
private static partial Regex YearPattern();
private static readonly HashSet<string> s_genreWords = new(StringComparer.OrdinalIgnoreCase)
{
"adventure", "biography", "children's literature", "comics", "crime",
"drama", "dystopian", "erotica", "essay", "fantasy", "fiction",
"historical fiction", "history", "horror", "humor", "memoir", "mystery",
"nonfiction", "poetry", "romance", "science fiction", "thriller",
"travel", "young adult"
};
/// <summary>
/// Maps the edition, work, author, rating, and search data into a full book request.
/// </summary>
/// <param name="lookup">The lookup describing the book to map.</param>
/// <param name="edition">The edition data, or <see langword="null"/> when no edition was found.</param>
/// <param name="work">The work data, or <see langword="null"/> when no work was found.</param>
/// <param name="authors">The authors of the book.</param>
/// <param name="ratings">The ratings of the book, or <see langword="null"/> when no ratings were found.</param>
/// <param name="fallback">The search document used as a fallback source of data, or <see langword="null"/>.</param>
/// <returns>The mapped book request.</returns>
public static AddBookRequest MapDetailed(
BookMetadataLookupDto lookup,
OpenLibraryEditionResponse? edition,
OpenLibraryWorkResponse? work,
IReadOnlyList<OpenLibraryAuthorResponse> authors,
OpenLibraryRatingsResponse? ratings,
OpenLibrarySearchDocumentResponse? fallback = null)
{
List<string> subjects = DistinctValues(work?.Subjects ?? fallback?.Subjects ?? []);
List<string> explicitGenres = DistinctValues(work?.Genres ?? []);
List<string> genreNames = explicitGenres.Count > 0 ? explicitGenres : [.. subjects.Where(LooksLikeGenre)];
(DateOnly? Date, int? Year) originalRelease = ParseOpenLibraryDate(work?.FirstPublishDate);
int? originalYear = originalRelease.Date?.Year ?? originalRelease.Year ?? fallback?.FirstPublishYear;
(DateOnly? Date, int? Year) editionRelease = ParseOpenLibraryDate(edition?.PublishDate);
string? workId = ExtractOlid(work?.Key, 'W') ?? ExtractOlid(fallback?.Key, 'W');
string? editionId = ExtractOlid(edition?.Key, 'M') ?? fallback?.EditionKeys.FirstOrDefault();
string? currentLanguageCode = ExtractLanguageCode(edition?.Languages.FirstOrDefault()?.Key) ?? fallback?.Languages.FirstOrDefault();
string? originalLanguageCode = ExtractLanguageCode(work?.OriginalLanguages.FirstOrDefault()?.Key);
Dictionary<string, List<string>> identifiers = ReadIdentifiers(edition?.Identifiers ?? default);
string? asin = FirstIdentifier(identifiers, "amazon", "asin") ?? FirstSourceIdentifier(edition?.SourceRecords, "amazon") ?? fallback?.AmazonIds.FirstOrDefault();
string? goodreadsId = FirstIdentifier(identifiers, "goodreads") ?? fallback?.GoodreadsIds.FirstOrDefault();
string? libraryThingId = FirstIdentifier(identifiers, "librarything") ?? fallback?.LibraryThingIds.FirstOrDefault();
string? googleBooksId = FirstIdentifier(identifiers, "google", "google_books") ?? FirstSourceIdentifier(edition?.SourceRecords, "google") ?? fallback?.GoogleIds.FirstOrDefault();
string? barnesAndNobleId = FirstIdentifier(identifiers, "barnesandnoble", "barnes_and_noble", "bn");
string? appleBooksId = FirstIdentifier(identifiers, "apple", "apple_books", "ibooks");
List<IsbnDto> isbns = MapIsbns(lookup.Isbn, edition, fallback);
List<MediaContributorDto> contributors = MapContributors(authors, edition?.Contributions, fallback?.AuthorNames);
List<BookRatingDto> mappedRatings = MapRatings(ratings, fallback);
string? title = FirstNotEmpty(edition?.Title, work?.Title, fallback?.Title);
string? description = ReadText(work?.Description ?? default) ?? ReadText(edition?.Notes ?? default);
string? releaseCountry = edition?.PublishPlaces.FirstOrDefault() ?? fallback?.PublishPlaces.FirstOrDefault();
string? releaseVersion = edition?.EditionName;
return new AddBookRequest(
lookup.LibraryId,
lookup.Path,
new WrittenContentMetadataDto(
title,
work?.OriginalTitle,
description,
new ReleaseInfoDto(
originalRelease.Date,
originalYear,
editionRelease.Date,
editionRelease.Date?.Year ?? editionRelease.Year,
NullIfWhiteSpace(releaseCountry),
NullIfWhiteSpace(releaseVersion)),
genreNames.Select(name => new GenreDto(name)).ToList(),
subjects.Select(name => new TagDto(name)).ToList(),
MapLanguage(currentLanguageCode),
MapLanguage(originalLanguageCode),
edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(),
edition?.NumberOfPages ?? fallback?.NumberOfPagesMedian),
MapFormat(edition?.PhysicalFormat),
NullIfWhiteSpace(edition?.EditionName),
ParseVolumeNumber(edition?.Volume, edition?.Series.FirstOrDefault()),
MapSeries(edition?.Series.FirstOrDefault()),
NullIfWhiteSpace(asin),
NullIfWhiteSpace(goodreadsId),
NullIfWhiteSpace(edition?.Lccn.FirstOrDefault() ?? fallback?.Lccn.FirstOrDefault()),
NullIfWhiteSpace(edition?.OclcNumbers.FirstOrDefault() ?? fallback?.Oclc.FirstOrDefault()),
editionId ?? workId,
NullIfWhiteSpace(libraryThingId),
NullIfWhiteSpace(googleBooksId),
NullIfWhiteSpace(barnesAndNobleId),
NullIfWhiteSpace(appleBooksId),
isbns,
contributors,
mappedRatings);
}
/// <summary>
/// Maps a search document into a book request candidate.
/// </summary>
/// <param name="lookup">The lookup describing the book to map.</param>
/// <param name="document">The search document to map.</param>
/// <returns>The mapped book request candidate.</returns>
public static AddBookRequest MapSearchCandidate(BookMetadataLookupDto lookup, OpenLibrarySearchDocumentResponse document)
{
return MapDetailed(lookup, null, null, [], null, document);
}
/// <summary>
/// Normalizes an ISBN into its canonical form without separators or whitespace.
/// </summary>
/// <param name="isbn">The ISBN to normalize.</param>
/// <returns>The normalized ISBN.</returns>
/// <exception cref="ArgumentException">The ISBN is empty, white space, or contains invalid characters.</exception>
public static string NormalizeIsbn(string isbn)
{
ArgumentException.ThrowIfNullOrWhiteSpace(isbn);
string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant();
if ((normalized.Length != 10 && normalized.Length != 13) ||
normalized[..^1].Any(character => !char.IsDigit(character)) ||
(!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X')))
throw new ArgumentException("The ISBN must contain 10 or 13 valid characters.", nameof(isbn));
return normalized;
}
/// <summary>
/// Extracts the canonical OLID from an Open Library key, when it matches the expected suffix.
/// </summary>
/// <param name="key">The Open Library key to extract the OLID from.</param>
/// <param name="expectedSuffix">The suffix the OLID must end with, for example <c>W</c> for works.</param>
/// <returns>The canonical OLID, or <see langword="null"/> when the key does not contain a matching OLID.</returns>
public static string? ExtractOlid(string? key, char expectedSuffix)
{
if (string.IsNullOrWhiteSpace(key))
return null;
string candidate = key.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant();
return candidate.StartsWith("OL", StringComparison.Ordinal) && candidate.EndsWith(expectedSuffix) && candidate.Length > 3 ? candidate : null;
}
/// <summary>
/// Maps a physical format string into a book format enum value.
/// </summary>
/// <param name="physicalFormat">The physical format string to map.</param>
/// <returns>The mapped book format, or <see langword="null"/> when the format is not recognized.</returns>
public static BookFormat? MapFormat(string? physicalFormat)
{
if (string.IsNullOrWhiteSpace(physicalFormat))
return null;
string value = physicalFormat.Trim().ToLowerInvariant();
if (value.Contains("mass market", StringComparison.Ordinal))
return BookFormat.MassMarketPaperback;
if (value.Contains("trade paperback", StringComparison.Ordinal))
return BookFormat.TradePaperback;
if (value.Contains("paperback", StringComparison.Ordinal) || value.Contains("softcover", StringComparison.Ordinal))
return BookFormat.Paperback;
if (value.Contains("hardcover", StringComparison.Ordinal) || value.Contains("hard cover", StringComparison.Ordinal) || value.Contains("hardback", StringComparison.Ordinal) || value.Contains("clothbound", StringComparison.Ordinal))
return BookFormat.Hardcover;
if (value.Contains("ebook", StringComparison.Ordinal) || value.Contains("e-book", StringComparison.Ordinal) || value.Contains("electronic", StringComparison.Ordinal))
return BookFormat.eBook;
if (value.Contains("audiobook", StringComparison.Ordinal) || value.Contains("audio book", StringComparison.Ordinal) || value.Contains("audio cd", StringComparison.Ordinal) || value.Contains("audio cassette", StringComparison.Ordinal))
return BookFormat.Audiobook;
if (value.Contains("large print", StringComparison.Ordinal))
return BookFormat.LargePrint;
if (value.Contains("board book", StringComparison.Ordinal))
return BookFormat.BoardBook;
if (value.Contains("spiral", StringComparison.Ordinal))
return BookFormat.SpiralBound;
if (value.Contains("library binding", StringComparison.Ordinal))
return BookFormat.LibraryBinding;
if (value.Contains("leather", StringComparison.Ordinal))
return BookFormat.LeatherBound;
if (value.Contains("pop-up", StringComparison.Ordinal) || value.Contains("popup", StringComparison.Ordinal))
return BookFormat.PopupBook;
return null;
}
/// <summary>
/// Maps the ISBNs from the lookup, edition, and search document into ISBN DTOs, de-duplicating normalized values.
/// </summary>
/// <param name="lookupIsbn">The ISBN of the lookup.</param>
/// <param name="edition">The edition data to read the ISBNs from.</param>
/// <param name="fallback">The search document to read the ISBNs from.</param>
/// <returns>The mapped and de-duplicated ISBN DTOs.</returns>
private static List<IsbnDto> MapIsbns(string? lookupIsbn, OpenLibraryEditionResponse? edition, OpenLibrarySearchDocumentResponse? fallback)
{
List<IsbnDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
void Add(string? raw, IsbnFormat? declaredFormat = null)
{
if (string.IsNullOrWhiteSpace(raw))
return;
string normalized;
try
{
normalized = NormalizeIsbn(raw);
}
catch (ArgumentException)
{
return;
}
if (!seen.Add(normalized))
return;
IsbnFormat format = declaredFormat ?? (normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13);
result.Add(new IsbnDto(normalized, format));
}
Add(lookupIsbn);
foreach (string isbn in edition?.Isbn10 ?? [])
Add(isbn, IsbnFormat.Isbn10);
foreach (string isbn in edition?.Isbn13 ?? [])
Add(isbn, IsbnFormat.Isbn13);
foreach (string isbn in fallback?.Isbns ?? [])
Add(isbn);
return result;
}
/// <summary>
/// Maps the authors and contributions into contributor DTOs, de-duplicating identical name and role pairs.
/// </summary>
/// <param name="authors">The authors of the book.</param>
/// <param name="contributions">The contribution strings of the edition.</param>
/// <param name="fallbackAuthors">The author names from the search document.</param>
/// <returns>The mapped contributor DTOs.</returns>
private static List<MediaContributorDto> MapContributors(IReadOnlyList<OpenLibraryAuthorResponse> authors, IReadOnlyList<string>? contributions, IReadOnlyList<string>? fallbackAuthors)
{
List<MediaContributorDto> result = [];
HashSet<string> seen = new(StringComparer.OrdinalIgnoreCase);
void Add(string? displayName, string? legalName, string role, string category)
{
if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}"))
return;
result.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), NullIfWhiteSpace(legalName)), new MediaContributorRoleDto(role, category)));
}
foreach (OpenLibraryAuthorResponse author in authors)
Add(author.Name, author.PersonalName, "Author", "Writing");
foreach (string authorName in fallbackAuthors ?? [])
Add(authorName, null, "Author", "Writing");
foreach (string contribution in contributions ?? [])
{
Match match = ContributorPattern().Match(contribution);
string name = match.Success ? match.Groups["name"].Value.Trim() : contribution.Trim();
string role = match.Success ? match.Groups["role"].Value.Trim() : "Contributor";
Add(name, null, role, ContributorCategory(role));
}
return result;
}
/// <summary>
/// Maps the ratings into a single Open Library rating DTO when an average or a count is present.
/// </summary>
/// <param name="ratings">The ratings of the work.</param>
/// <param name="fallback">The search document to read the ratings from.</param>
/// <returns>The mapped rating DTOs, or an empty list when no rating data was found.</returns>
private static List<BookRatingDto> MapRatings(OpenLibraryRatingsResponse? ratings, OpenLibrarySearchDocumentResponse? fallback)
{
decimal? average = ratings?.Summary?.Average ?? fallback?.RatingsAverage;
int? count = ratings?.Summary?.Count ?? fallback?.RatingsCount;
if (average is null && count is null)
return [];
return [new BookRatingDto(average, 5m, BookRatingSource.OpenLibrary, count)];
}
/// <summary>
/// Maps a language code into a language info DTO by matching it against known cultures.
/// </summary>
/// <param name="rawCode">The raw language code to map.</param>
/// <returns>The mapped language info, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
IEnumerable<CultureInfo> cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures));
CultureInfo? culture = cultures.FirstOrDefault(candidate =>
string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) ||
string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase));
return culture is null ? new LanguageInfoDto(code, code, null) : new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName);
}
/// <summary>
/// Maps a series string into a book series DTO.
/// </summary>
/// <param name="series">The series string to map.</param>
/// <returns>The mapped book series, or <see langword="null"/> when the string is empty.</returns>
private static BookSeriesDto? MapSeries(string? series)
{
string? value = NullIfWhiteSpace(series);
return value is null ? null : new BookSeriesDto(value);
}
/// <summary>
/// Parses a volume number from the first candidate that contains one.
/// </summary>
/// <param name="candidates">The strings that may contain a volume number.</param>
/// <returns>The parsed volume number, or <see langword="null"/> when no candidate contains one.</returns>
private static int? ParseVolumeNumber(params string?[] candidates)
{
foreach (string? candidate in candidates)
{
if (string.IsNullOrWhiteSpace(candidate))
continue;
Match match = VolumePattern().Match(candidate);
if (match.Success && int.TryParse(match.Groups["number"].Value, out int number))
return number;
}
return null;
}
/// <summary>
/// Parses an Open Library date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseOpenLibraryDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
DateTimeStyles styles = DateTimeStyles.AllowWhiteSpaces;
string[] formats =
[
"yyyy-MM-dd", "yyyy-M-d", "MMMM d, yyyy", "MMM d, yyyy",
"d MMMM yyyy", "d MMM yyyy"
];
if (DateOnly.TryParseExact(value.Trim(), formats, CultureInfo.InvariantCulture, styles, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = YearPattern().Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Reads the text out of a JSON element that is either a plain string or an object with a <c>value</c> property.
/// </summary>
/// <param name="element">The JSON element to read.</param>
/// <returns>The text, or <see langword="null"/> when the element does not contain readable text.</returns>
private static string? ReadText(JsonElement element)
{
return element.ValueKind switch
{
JsonValueKind.String => NullIfWhiteSpace(element.GetString()),
JsonValueKind.Object when element.TryGetProperty("value", out JsonElement value) => ReadText(value),
_ => null
};
}
/// <summary>
/// Reads an identifiers object into a dictionary keyed by identifier name.
/// </summary>
/// <param name="element">The JSON element to read.</param>
/// <returns>The identifier values keyed by identifier name.</returns>
private static Dictionary<string, List<string>> ReadIdentifiers(JsonElement element)
{
Dictionary<string, List<string>> result = new(StringComparer.OrdinalIgnoreCase);
if (element.ValueKind != JsonValueKind.Object)
return result;
foreach (JsonProperty property in element.EnumerateObject())
{
IEnumerable<string?> values = property.Value.ValueKind switch
{
JsonValueKind.String => [property.Value.GetString()],
JsonValueKind.Array => property.Value.EnumerateArray()
.Where(item => item.ValueKind == JsonValueKind.String)
.Select(item => item.GetString()),
_ => []
};
result[property.Name] = [.. values
.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value!)];
}
return result;
}
/// <summary>
/// Gets the first value of the first identifier key that has values.
/// </summary>
/// <param name="identifiers">The identifiers to read from.</param>
/// <param name="keys">The identifier keys to try, in order.</param>
/// <returns>The first value, or <see langword="null"/> when none of the keys have values.</returns>
private static string? FirstIdentifier(IReadOnlyDictionary<string, List<string>> identifiers, params string[] keys)
{
foreach (string key in keys)
if (identifiers.TryGetValue(key, out List<string>? values) && values.Count > 0)
return values[0];
return null;
}
/// <summary>
/// Gets the identifier value from a source record prefixed with the given source name.
/// </summary>
/// <param name="sourceRecords">The source records to read from.</param>
/// <param name="source">The source name prefix to match.</param>
/// <returns>The identifier value, or <see langword="null"/> when no source record matches.</returns>
private static string? FirstSourceIdentifier(IReadOnlyList<string>? sourceRecords, string source)
{
string prefix = source + ":";
string? match = sourceRecords?.FirstOrDefault(value => value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
return match?[prefix.Length..];
}
/// <summary>
/// Extracts the language code from an Open Library language key.
/// </summary>
/// <param name="key">The language key to extract the code from.</param>
/// <returns>The language code, or <see langword="null"/> when the key is empty.</returns>
private static string? ExtractLanguageCode(string? key)
{
return string.IsNullOrWhiteSpace(key) ? null : key.Trim().TrimEnd('/').Split('/').Last();
}
/// <summary>
/// Trims, filters, and de-duplicates the given values, ignoring case.
/// </summary>
/// <param name="values">The values to process.</param>
/// <returns>The processed values.</returns>
private static List<string> DistinctValues(IEnumerable<string> values)
{
return [.. values.Select(value => value.Trim()).Where(value => value.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Determines whether a subject is likely to describe a genre.
/// </summary>
/// <param name="subject">The subject to check.</param>
/// <returns><see langword="true"/> when the subject is a known genre word or ends in fiction or literature.</returns>
private static bool LooksLikeGenre(string subject)
{
return s_genreWords.Contains(subject) ||
subject.EndsWith(" fiction", StringComparison.OrdinalIgnoreCase) ||
subject.EndsWith(" literature", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Maps a contributor role into a contributor category.
/// </summary>
/// <param name="role">The role to categorize.</param>
/// <returns>The mapped contributor category.</returns>
private static string ContributorCategory(string role)
{
if (role.Contains("illustr", StringComparison.OrdinalIgnoreCase) ||
role.Contains("artist", StringComparison.OrdinalIgnoreCase))
return "Art";
if (role.Contains("translat", StringComparison.OrdinalIgnoreCase))
return "Translation";
if (role.Contains("edit", StringComparison.OrdinalIgnoreCase) ||
role.Contains("author", StringComparison.OrdinalIgnoreCase) ||
role.Contains("writer", StringComparison.OrdinalIgnoreCase))
return "Writing";
if (role.Contains("narrat", StringComparison.OrdinalIgnoreCase))
return "Performance";
return "Other";
}
/// <summary>
/// Gets the first value that is not empty or white space.
/// </summary>
/// <param name="values">The values to check, in order.</param>
/// <returns>The first non-empty value, or <see langword="null"/> when all values are empty.</returns>
private static string? FirstNotEmpty(params string?[] values)
{
return values.Select(NullIfWhiteSpace).FirstOrDefault(value => value is not null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,364 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses;
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using Lumina.Plugins.OpenLibrary.Core.Api;
using Lumina.Plugins.OpenLibrary.Core.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.OpenLibrary.Core;
/// <summary>
/// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs.
/// </summary>
internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider<BookMetadataLookupDto, BookMetadataDto>
{
private readonly OpenLibraryHttpClient _openLibraryHttpClient;
private readonly OpenLibrarySettingsDto _openLibrarySettings;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "Open Library";
/// <summary>
/// Gets the media library type this metadata provider supports.
/// </summary>
public LibraryType SupportedLibraryType => LibraryType.Book;
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="OpenLibraryBookMetadataProvider"/> class.
/// </summary>
/// <param name="openLibraryHttpClient">The HTTP client used to call the Open Library API.</param>
/// <param name="openLibrarySettings">The settings that configure the Open Library API requests.</param>
public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings)
{
_openLibraryHttpClient = openLibraryHttpClient;
_openLibrarySettings = openLibrarySettings;
}
/// <summary>
/// Searches for the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the media item to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of metadata candidates found for the media item.</returns>
public async Task<IReadOnlyList<BookMetadataDto>> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
ValidateLookup(bookMetadataLookup);
if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId))
{
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookRequestMatch is null ? [] : [new BookMetadataDto(
exactBookRequestMatch.Metadata?.Title,
exactBookRequestMatch.Metadata?.OriginalTitle,
exactBookRequestMatch.Metadata?.Description,
exactBookRequestMatch.Metadata?.ReleaseInfo,
exactBookRequestMatch.Metadata?.Genres,
exactBookRequestMatch.Metadata?.Tags,
exactBookRequestMatch.Metadata?.Language,
exactBookRequestMatch.Metadata?.OriginalLanguage,
exactBookRequestMatch.Metadata?.Publisher,
exactBookRequestMatch.Metadata?.PageCount,
exactBookRequestMatch.Format,
exactBookRequestMatch.Edition,
exactBookRequestMatch.VolumeNumber,
exactBookRequestMatch.Series,
exactBookRequestMatch.ASIN,
exactBookRequestMatch.GoodreadsId,
exactBookRequestMatch.LCCN,
exactBookRequestMatch.OCLCNumber,
exactBookRequestMatch.OpenLibraryId,
exactBookRequestMatch.LibraryThingId,
exactBookRequestMatch.GoogleBooksId,
exactBookRequestMatch.BarnesAndNobleId,
exactBookRequestMatch.AppleBooksId,
exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings,
CoverImageUrl: null
)];
}
IReadOnlyList<OpenLibrarySearchDocumentResponse> openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
return [.. openLibrarySearchDocuments
.Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title))
.Select(openLibrarySearchDocument =>
{
AddBookRequest addBookRequest = OpenLibraryMapper.MapSearchCandidate(bookMetadataLookup, openLibrarySearchDocument);
return new BookMetadataDto(
addBookRequest.Metadata?.Title,
addBookRequest.Metadata?.OriginalTitle,
addBookRequest.Metadata?.Description,
addBookRequest.Metadata?.ReleaseInfo,
addBookRequest.Metadata?.Genres,
addBookRequest.Metadata?.Tags,
addBookRequest.Metadata?.Language,
addBookRequest.Metadata?.OriginalLanguage,
addBookRequest.Metadata?.Publisher,
addBookRequest.Metadata?.PageCount,
addBookRequest.Format,
addBookRequest.Edition,
addBookRequest.VolumeNumber,
addBookRequest.Series,
addBookRequest.ASIN,
addBookRequest.GoodreadsId,
addBookRequest.LCCN,
addBookRequest.OCLCNumber,
addBookRequest.OpenLibraryId,
addBookRequest.LibraryThingId,
addBookRequest.GoogleBooksId,
addBookRequest.BarnesAndNobleId,
addBookRequest.AppleBooksId,
addBookRequest.ISBNs,
addBookRequest.Contributors,
addBookRequest.Ratings,
CoverImageUrl: null
);
})];
}
/// <summary>
/// Gets the metadata of the media item described by <paramref name="bookMetadataLookup"/>.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the media item to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the media item, or <see langword="null"/> when no metadata was found.</returns>
public async Task<BookMetadataDto?> GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false);
return exactBookRequestMatch is null ? null : new BookMetadataDto(
exactBookRequestMatch.Metadata?.Title,
exactBookRequestMatch.Metadata?.OriginalTitle,
exactBookRequestMatch.Metadata?.Description,
exactBookRequestMatch.Metadata?.ReleaseInfo,
exactBookRequestMatch.Metadata?.Genres,
exactBookRequestMatch.Metadata?.Tags,
exactBookRequestMatch.Metadata?.Language,
exactBookRequestMatch.Metadata?.OriginalLanguage,
exactBookRequestMatch.Metadata?.Publisher,
exactBookRequestMatch.Metadata?.PageCount,
exactBookRequestMatch.Format,
exactBookRequestMatch.Edition,
exactBookRequestMatch.VolumeNumber,
exactBookRequestMatch.Series,
exactBookRequestMatch.ASIN,
exactBookRequestMatch.GoodreadsId,
exactBookRequestMatch.LCCN,
exactBookRequestMatch.OCLCNumber,
exactBookRequestMatch.OpenLibraryId,
exactBookRequestMatch.LibraryThingId,
exactBookRequestMatch.GoogleBooksId,
exactBookRequestMatch.BarnesAndNobleId,
exactBookRequestMatch.AppleBooksId,
exactBookRequestMatch.ISBNs,
exactBookRequestMatch.Contributors,
exactBookRequestMatch.Ratings,
CoverImageUrl: null
);
}
/// <summary>
/// Resolves the lookup into a full book request by combining edition, work, author, and rating data from Open Library.
/// </summary>
/// <param name="bookMetadataLookup">The lookup describing the book to resolve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The resolved book request, or <see langword="null"/> when no matching book was found.</returns>
public async Task<AddBookRequest?> GetBookAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken = default)
{
ValidateLookup(bookMetadataLookup);
OpenLibraryEditionResponse? openLibraryEditionResponse = null;
OpenLibraryWorkResponse? openLibraryWorkResponse = null;
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 (!string.IsNullOrWhiteSpace(openLibraryId))
{
string olid = NormalizeOlid(openLibraryId);
if (olid.EndsWith('M'))
openLibraryEditionResponse = await _openLibraryHttpClient.GetEditionAsync(olid, cancellationToken).ConfigureAwait(false);
else if (olid.EndsWith('W'))
{
// A work has no publisher-specific details on its own (no ISBN, page count, etc.), so we still need to pull it for its work-level fields (e.g. description, subjects).
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(olid, cancellationToken).ConfigureAwait(false);
// A work can have many editions; SelectEdition picks the one that best matches the lookup criteria (language, format, etc.) instead of assuming the first result is right.
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
}
else
throw new ArgumentException("A book Open Library ID must be a work ID ending in W or an edition ID ending in M.", nameof(bookMetadataLookup));
if (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
return null;
}
// 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 (openLibraryEditionResponse is null && openLibraryWorkResponse is null)
{
IReadOnlyList<OpenLibrarySearchDocumentResponse> searchResults = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, 1, cancellationToken).ConfigureAwait(false);
if (searchResults.Count == 0 || searchResults[0] is null)
return null;
string? workId = OpenLibraryMapper.ExtractOlid(searchResults[0].Key, 'W');
if (workId is not null)
{
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(workId, cancellationToken).ConfigureAwait(false);
openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup);
}
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 (openLibraryEditionResponse is null && openLibraryWorkResponse is null && openLibrarySearchDocumentResponse is null)
return null;
string? editionWorkId = OpenLibraryMapper.ExtractOlid(openLibraryEditionResponse?.Works.FirstOrDefault()?.Key, 'W');
if (openLibraryWorkResponse is null && editionWorkId is not null)
openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(editionWorkId, cancellationToken).ConfigureAwait(false);
List<string> authorIds = [.. (openLibraryWorkResponse?.Authors
.Select(item => OpenLibraryMapper.ExtractOlid(item.Author?.Key ?? item.Key, 'A')) ?? [])
.Concat(openLibraryEditionResponse?.Authors
.Select(item => OpenLibraryMapper.ExtractOlid(item.Key, 'A')) ?? [])
.Where(id => id is not null)
.Select(id => id!)
.Distinct(StringComparer.OrdinalIgnoreCase)];
List<OpenLibraryAuthorResponse> authors = [];
foreach (string authorId in authorIds)
{
OpenLibraryAuthorResponse? author = await _openLibraryHttpClient.GetAuthorAsync(authorId, cancellationToken).ConfigureAwait(false);
if (author is not null)
authors.Add(author);
}
string? finalWorkId = OpenLibraryMapper.ExtractOlid(openLibraryWorkResponse?.Key, 'W') ?? editionWorkId;
OpenLibraryRatingsResponse? ratings = finalWorkId is null ? null : await _openLibraryHttpClient.GetRatingsAsync(finalWorkId, cancellationToken).ConfigureAwait(false);
return OpenLibraryMapper.MapDetailed(bookMetadataLookup, openLibraryEditionResponse, openLibraryWorkResponse, authors, ratings, openLibrarySearchDocumentResponse);
}
/// <summary>
/// Selects the best matching edition from the given editions, favoring matches for the lookup's ISBN and language.
/// </summary>
/// <param name="openLibraryEditions">The editions to select from.</param>
/// <param name="bookMetadataLookup">The lookup the selected edition must match.</param>
/// <returns>The best matching edition, or <see langword="null"/> when no edition was found.</returns>
private static OpenLibraryEditionResponse? SelectEdition(IReadOnlyList<OpenLibraryEditionResponse> openLibraryEditions, BookMetadataLookupDto bookMetadataLookup)
{
string? lookupIsbn = bookMetadataLookup.Isbn;
string? wantedIsbn = string.IsNullOrWhiteSpace(lookupIsbn) ? null : OpenLibraryMapper.NormalizeIsbn(lookupIsbn);
string? wantedLanguage = bookMetadataLookup.LanguageCode?.Trim();
return openLibraryEditions
.Select((edition, index) => new
{
Edition = edition,
Index = index,
Score = ScoreEdition(edition, wantedIsbn, wantedLanguage)
})
.OrderByDescending(item => item.Score)
.ThenBy(item => item.Index)
.Select(item => item.Edition)
.FirstOrDefault();
}
/// <summary>
/// Scores an edition against the wanted ISBN and language to rank how well it matches the lookup.
/// </summary>
/// <param name="openLibraryEdition">The edition to score.</param>
/// <param name="wantedIsbn">The normalized ISBN to match, or <see langword="null"/> when the lookup has no ISBN.</param>
/// <param name="wantedLanguage">The language code to match, or <see langword="null"/> when the lookup has no language.</param>
/// <returns>The match score of the edition, where a higher score is a better match.</returns>
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 (wantedIsbn is not null && openLibraryEdition.Isbn10.Concat(openLibraryEdition.Isbn13).Any(value => string.Equals(SafeNormalizeIsbn(value), wantedIsbn, StringComparison.OrdinalIgnoreCase)))
score += 10_000;
if (!string.IsNullOrWhiteSpace(wantedLanguage) && openLibraryEdition.Languages.Any(language =>
string.Equals(language.Key?.Trim().TrimEnd('/').Split('/').Last(), wantedLanguage, StringComparison.OrdinalIgnoreCase)))
score += 1_000;
if (openLibraryEdition.NumberOfPages is > 0)
score += 100;
if (openLibraryEdition.Isbn10.Count + openLibraryEdition.Isbn13.Count > 0)
score += 50;
if (openLibraryEdition.Publishers.Count > 0)
score += 20;
if (!string.IsNullOrWhiteSpace(openLibraryEdition.PublishDate))
score += 10;
if (!string.IsNullOrWhiteSpace(openLibraryEdition.EditionName))
score += 5;
return score;
}
/// <summary>
/// Normalizes an ISBN, returning <see langword="null"/> when the value is not a valid ISBN.
/// </summary>
/// <param name="value">The ISBN to normalize.</param>
/// <returns>The normalized ISBN, or <see langword="null"/> when the value is not a valid ISBN.</returns>
private static string? SafeNormalizeIsbn(string value)
{
try
{
return OpenLibraryMapper.NormalizeIsbn(value);
}
catch (ArgumentException)
{
return null;
}
}
/// <summary>
/// Normalizes a raw Open Library identifier into its canonical OLID form.
/// </summary>
/// <param name="raw">The raw Open Library identifier to normalize.</param>
/// <returns>The canonical OLID.</returns>
/// <exception cref="ArgumentException">The value is not a valid Open Library identifier.</exception>
private static string NormalizeOlid(string raw)
{
string id = raw.Trim().TrimEnd('/').Split('/').Last().ToUpperInvariant();
if (id.Length < 4 || !id.StartsWith("OL", StringComparison.Ordinal) || (id[^1] is not ('M' or 'W')) || !id.AsSpan(2, id.Length - 3).ToString().All(char.IsDigit))
throw new ArgumentException("The Open Library ID is invalid.", nameof(raw));
return id;
}
/// <summary>
/// Validates that the lookup contains the information required to resolve book metadata.
/// </summary>
/// <param name="bookMetadataLookup">The lookup to validate.</param>
/// <exception cref="ArgumentException">The lookup is missing required information.</exception>
private static void ValidateLookup(BookMetadataLookupDto bookMetadataLookup)
{
ArgumentNullException.ThrowIfNull(bookMetadataLookup);
if (bookMetadataLookup.LibraryId == Guid.Empty)
throw new ArgumentException("LibraryId is required.", nameof(bookMetadataLookup));
ArgumentException.ThrowIfNullOrWhiteSpace(bookMetadataLookup.Path);
if (string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) && string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId) && string.IsNullOrWhiteSpace(bookMetadataLookup.Title))
throw new ArgumentException("At least one of Isbn, OpenLibraryId, or Title is required.", nameof(bookMetadataLookup));
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.OpenLibrary.Common.DependencyInjection;
using Lumina.Plugins.OpenLibrary.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.OpenLibrary.Core;
/// <summary>
/// Plugin that provides book metadata retrieval from Open Library.
/// </summary>
public sealed class OpenLibraryPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("08b17802-7f9c-4c4b-9d7f-b507bbed3e58");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "Open Library Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Retrieves book and edition metadata from Open Library.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return
[
new PluginSettingDescriptorDto(
Key: OpenLibrarySettingsKeys.CONTACT_EMAIL,
Label: "Contact Email",
Type: PluginSettingType.Text),
new PluginSettingDescriptorDto(
Key: OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT,
Label: "Search Result Limit",
Type: PluginSettingType.Number,
DefaultValue: "10"),
new PluginSettingDescriptorDto(
Key: OpenLibrarySettingsKeys.WORK_EDITION_LIMIT,
Label: "Work Edition Limit",
Type: PluginSettingType.Number,
DefaultValue: "50"),
new PluginSettingDescriptorDto(
Key: OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
Label: "Minimum Request Interval (seconds)",
Type: PluginSettingType.Number,
DefaultValue: "1.1")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddOpenLibraryBookMetadataProvider(pluginId: Id);
}
}
@@ -0,0 +1,27 @@
namespace Lumina.Plugins.OpenLibrary.Core.Settings;
/// <summary>
/// Keys of the settings of the Open Library metadata plugin, shared by the settings schema and the settings loader.
/// </summary>
internal static class OpenLibrarySettingsKeys
{
/// <summary>
/// The key of the setting defining the contact email sent to the Open Library API.
/// </summary>
internal const string CONTACT_EMAIL = "ContactEmail";
/// <summary>
/// The key of the setting defining the maximum number of results returned by a single search.
/// </summary>
internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit";
/// <summary>
/// The key of the setting defining the maximum number of editions fetched for a single work.
/// </summary>
internal const string WORK_EDITION_LIMIT = "WorkEditionLimit";
/// <summary>
/// The key of the setting defining the minimum interval between consecutive requests to the Open Library API, in seconds.
/// </summary>
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
#endregion
namespace Lumina.Plugins.OpenLibrary.Core.Settings;
/// <summary>
/// Applies the settings persisted by the host onto the runtime settings of the Open Library metadata plugin.
/// </summary>
internal static class OpenLibrarySettingsLoader
{
/// <summary>
/// Overlays the persisted <paramref name="storedSettings"/> onto the provided <paramref name="settings"/>, keeping the default values of the settings that were not persisted.
/// </summary>
/// <param name="settings">The runtime settings onto which the persisted settings are applied.</param>
/// <param name="storedSettings">The settings persisted by the host, keyed by setting key.</param>
public static void Apply(OpenLibrarySettingsDto settings, IReadOnlyDictionary<string, string> storedSettings)
{
if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.CONTACT_EMAIL, out string? contactEmail))
settings.ContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) &&
int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue))
settings.SearchResultLimit = Math.Max(1, searchResultLimitValue);
if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.WORK_EDITION_LIMIT, out string? workEditionLimit) &&
int.TryParse(workEditionLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int workEditionLimitValue))
settings.WorkEditionLimit = Math.Max(1, workEditionLimitValue);
if (storedSettings.TryGetValue(OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue))
settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue));
}
}
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -19,6 +19,16 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the media library this book belongs to.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the file system path of the book.
/// </summary>
public required string Path { get; set; }
/// <summary>
/// Gets or sets the title of the media item.
/// </summary>
@@ -195,6 +205,21 @@ public class BookEntity : IStorageEntity, IAuditableEntity
/// </summary>
public List<BookRatingEntity> Ratings { get; set; } = [];
/// <summary>
/// Gets or sets the status of the metadata enrichment of the book.
/// </summary>
public MetadataStatus MetadataStatus { get; set; }
/// <summary>
/// Gets or sets the date and time when the metadata of the book was last enriched.
/// </summary>
public DateTime? LastMetadataUpdateUtc { get; set; }
/// <summary>
/// Gets or sets the name of the plugin that enriched the metadata of the book.
/// </summary>
public string? MetadataProvider { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System.Diagnostics;
#endregion
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System.Diagnostics;
#endregion
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Repository entity for the configuration of a metadata provider of a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
public class LibraryMetadataProviderConfigurationEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets or sets the Id of the configuration.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the Id of the media library the configuration belongs to.
/// </summary>
public required Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the Id of the plugin providing the metadata.
/// </summary>
public required Guid PluginId { get; set; }
/// <summary>
/// Gets or sets whether the metadata provider is enabled for the media library.
/// </summary>
public required bool IsEnabled { get; set; }
/// <summary>
/// Gets or sets the rank of the metadata provider, determining the order in which providers are tried.
/// </summary>
public required int Rank { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -0,0 +1,75 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DataAccess.Entities.Plugins;
/// <summary>
/// Repository entity for a plugin.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class PluginEntity : IStorageEntity, IAuditableEntity
{
/// <summary>
/// Gets the Id of the plugin.
/// </summary>
public required Guid Id { get; init; }
/// <summary>
/// Gets or sets the display name of the plugin.
/// </summary>
public required string Name { get; set; }
/// <summary>
/// Gets or sets the author of the plugin.
/// </summary>
public required string Author { get; set; }
/// <summary>
/// Gets or sets the version of the plugin.
/// </summary>
public required string Version { get; set; }
/// <summary>
/// Gets or sets the description of the plugin.
/// </summary>
public required string Description { get; set; }
/// <summary>
/// Gets or sets the load status of the plugin.
/// </summary>
public PluginLoadStatus LoadStatus { get; set; }
/// <summary>
/// Gets or sets the error message when the plugin failed to load.
/// </summary>
public string? LoadError { get; set; }
/// <summary>
/// Gets or sets the serialized settings of the plugin.
/// </summary>
public string? SettingsJson { get; set; }
/// <summary>
/// Gets or sets the time and date when the entity was added.
/// </summary>
public required DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the Id of the user that created the entity.
/// </summary>
public required Guid CreatedBy { get; set; }
/// <summary>
/// Gets or sets the optional time and date when the entity was updated.
/// </summary>
public DateTime? UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the optional Id of the user that updated the entity.
/// </summary>
public required Guid? UpdatedBy { get; set; }
}
@@ -1,7 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Books;
@@ -11,6 +16,43 @@ namespace Lumina.Application.Common.DataAccess.Repositories.Books;
/// </summary>
public interface IBookRepository : IRepository<BookEntity>,
IInsertRepositoryAction<BookEntity>,
IUpdateRepositoryAction<BookEntity>,
IGetByIdRepositoryAction<BookEntity, Guid>,
IGetAllRepositoryAction<BookEntity>
{
/// <summary>
/// Gets all the books of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="BookEntity"/>, or an error.</returns>
Task<ErrorOr<IEnumerable<BookEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the book of the media library identified by <paramref name="libraryId"/> that is stored at the provided <paramref name="path"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose book is retrieved.</param>
/// <param name="path">The file system path of the book to be retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="BookEntity"/> stored at the provided path, or an error.</returns>
Task<ErrorOr<BookEntity?>> GetByPathAsync(Guid libraryId, string path, CancellationToken cancellationToken);
/// <summary>
/// Gets a page of the books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet,
/// ordered by path, using keyset pagination.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are retrieved.</param>
/// <param name="lastPath">The path of the last retrieved book, used for keyset pagination. Pass <see langword="null"/> to get the first page.</param>
/// <param name="pageSize">The maximum number of books to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of books needing their metadata enriched, or an error.</returns>
Task<ErrorOr<IReadOnlyList<BookEntity>>> GetBooksNeedingMetadataAsync(Guid libraryId, string? lastPath, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Gets the number of books of the media library identified by <paramref name="libraryId"/> whose metadata has not been enriched yet.
/// </summary>
/// <param name="libraryId">The Id of the media library whose books are counted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the number of books needing their metadata enriched, or an error.</returns>
Task<ErrorOr<int>> GetBooksNeedingMetadataCountAsync(Guid libraryId, CancellationToken cancellationToken);
}
@@ -3,7 +3,7 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -24,6 +24,14 @@ public interface ILibraryScanSnapshotRepository : IRepository<LibraryScanSnapsho
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of deleted media library scan snapshot item paths, or an error.</returns>
Task<ErrorOr<IReadOnlyList<string>>> GetDeletedPathsAsync(Guid libraryId, Guid scanId, CancellationToken cancellationToken);
/// <summary>
/// Gets the paths of all the media library scan snapshot items of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The unique identifier of the library whose media library scan snapshot item paths are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of media library scan snapshot item paths, or an error.</returns>
Task<ErrorOr<IReadOnlyList<string>>> GetPathsAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Atomically applies the results of the current scan to the storage medium, by replacing the media library scan snapshot of the previous scan with the snapshot of the current scan.
/// The operation updates the changed media library scan snapshot items, deletes the ones that are no longer present on disk, adds audit entries for all changed, new and deleted items,
@@ -3,7 +3,7 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -44,7 +44,7 @@ public interface ILibraryScanStagingResultsRepository : IRepository<LibraryScanS
/// <param name="pageSize">The maximum number of staging results to retrieve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a page of staging results that need hashing, or an error.</returns>
Task<ErrorOr<IReadOnlyList<HashedFileSystemFile>>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken);
Task<ErrorOr<IReadOnlyList<HashedFileSystemFileDto>>> GetFilesToHashPageAsync(Guid scanId, string? lastPath, int pageSize, CancellationToken cancellationToken);
/// <summary>
/// Updates the content hashes of the provided media library scan staging results.
@@ -53,7 +53,7 @@ public interface ILibraryScanStagingResultsRepository : IRepository<LibraryScanS
/// <param name="hashedFiles">The file system items whose content hashes are updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection<HashedFileSystemFile> hashedFiles, CancellationToken cancellationToken);
Task<ErrorOr<Updated>> UpdateFileHashesAsync(Guid scanId, IReadOnlyCollection<HashedFileSystemFileDto> hashedFiles, CancellationToken cancellationToken);
/// <summary>
/// Clears all the media library scan staging results of the provided media library scan from the storage medium.
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// <summary>
/// Interface for the repository for the metadata provider configurations of media libraries.
/// </summary>
public interface ILibraryMetadataProviderConfigurationRepository : IRepository<LibraryMetadataProviderConfigurationEntity>
{
/// <summary>
/// Gets all the metadata provider configurations of the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configurations are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
Task<ErrorOr<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken);
/// <summary>
/// Gets the metadata provider configuration of the media library identified by <paramref name="libraryId"/> for the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library whose metadata provider configuration is retrieved.</param>
/// <param name="pluginId">The Id of the plugin whose metadata provider configuration is retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the <see cref="LibraryMetadataProviderConfigurationEntity"/>, or an error.</returns>
Task<ErrorOr<LibraryMetadataProviderConfigurationEntity?>> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken);
/// <summary>
/// Inserts the provided <paramref name="configuration"/> into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="configuration">The metadata provider configuration to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken);
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.DataAccess.Repositories.Plugins;
/// <summary>
/// Interface for the repository for plugins.
/// </summary>
public interface IPluginRepository : IRepository<PluginEntity>,
IGetByIdRepositoryAction<PluginEntity, Guid>,
IGetAllRepositoryAction<PluginEntity>
{
/// <summary>
/// Inserts the provided <paramref name="plugin"/> into the storage medium, or updates it when it already exists.
/// </summary>
/// <param name="plugin">The plugin to insert or update.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpsertAsync(PluginEntity plugin, CancellationToken cancellationToken);
/// <summary>
/// Updates the settings of the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The Id of the plugin whose settings are updated.</param>
/// <param name="settingsJson">The serialized settings of the plugin.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpdateSettingsAsync(Guid pluginId, string? settingsJson, CancellationToken cancellationToken);
}
@@ -2,7 +2,7 @@
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -2,13 +2,13 @@
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.Configuration;
namespace Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// Data transfer object for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class MediaSettingsModel
public class MediaSettingsDto
{
public const string SECTION_NAME = "MediaSettings";
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
/// <summary>
/// Data transfer object for deserializing plugins settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class PluginsSettingsDto
{
public const string SECTION_NAME = "PluginsSettings";
/// <summary>
/// Gets or sets the directory where the plugin assemblies are located.
/// </summary>
public required string Directory { get; init; }
}
@@ -1,16 +1,16 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.FileSystem;
namespace Lumina.Application.Common.Infrastructure.Models.DTO.FileSystem;
/// <summary>
/// Generic file system node.
/// </summary>
[DebuggerDisplay("Path: {Path}")]
public class FileSystemTreeNode
public class FileSystemTreeNodeDto
{
/// <summary>
/// Gets or sets the full path of the file or directory.
@@ -30,5 +30,5 @@ public class FileSystemTreeNode
/// <summary>
/// Gets or sets the list of child nodes.
/// </summary>
public List<FileSystemTreeNode> Children { get; set; } = [];
public List<FileSystemTreeNodeDto> Children { get; set; } = [];
}
@@ -4,14 +4,14 @@ using System.Diagnostics;
using System.Runtime.InteropServices;
#endregion
namespace Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
namespace Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
/// <summary>
/// Represents an item for the payload of the file hashing media library scan job.
/// </summary>
[DebuggerDisplay("Path = {Path}, CurrentHash = {CurrentHash}, OldHash = {OldHash}, Ticks = {Ticks}, Size = {Size}")]
[StructLayout(LayoutKind.Sequential)]
public struct HashedFileSystemFile : IEquatable<HashedFileSystemFile>
public struct HashedFileSystemFileDto : IEquatable<HashedFileSystemFileDto>
{
/// <summary>
/// The path of the file system file.
@@ -39,7 +39,7 @@ public struct HashedFileSystemFile : IEquatable<HashedFileSystemFile>
public long Ticks { get; set; }
/// <inheritdoc/>
public readonly bool Equals(HashedFileSystemFile other)
public readonly bool Equals(HashedFileSystemFileDto other)
{
return Size == other.Size && CurrentHash == other.CurrentHash && OldHash == other.OldHash && Ticks == other.Ticks && Path == other.Path;
}
@@ -47,17 +47,17 @@ public struct HashedFileSystemFile : IEquatable<HashedFileSystemFile>
/// <inheritdoc/>
public override readonly bool Equals(object? obj)
{
return obj is HashedFileSystemFile item && Equals(item);
return obj is HashedFileSystemFileDto item && Equals(item);
}
/// <inheritdoc/>
public static bool operator ==(HashedFileSystemFile left, HashedFileSystemFile right)
public static bool operator ==(HashedFileSystemFileDto left, HashedFileSystemFileDto right)
{
return left.Equals(right);
}
/// <inheritdoc/>
public static bool operator !=(HashedFileSystemFile left, HashedFileSystemFile right)
public static bool operator !=(HashedFileSystemFileDto left, HashedFileSystemFileDto right)
{
return !(left == right);
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Common.Infrastructure.Plugins;
/// <summary>
/// Manager of the plugins loaded by the host application.
/// </summary>
public interface IPluginManager
{
/// <summary>
/// Gets the plugins that were loaded successfully.
/// </summary>
/// <returns>The collection of loaded plugins.</returns>
IReadOnlyList<IPlugin> GetPlugins();
/// <summary>
/// Gets the plugin identified by <paramref name="pluginId"/>.
/// </summary>
/// <param name="pluginId">The unique identifier of the plugin.</param>
/// <returns>The plugin, or <see langword="null"/> when no plugin with the provided Id was loaded.</returns>
IPlugin? GetPlugin(Guid pluginId);
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -20,5 +20,5 @@ public interface IFileHashService
/// <param name="callback">Callback to invoke during processing of elements.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A collection of the hashed files, along with their hashes.</returns>
Task<List<HashedFileSystemFile>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFile> files, Func<Task> callback, CancellationToken cancellationToken);
Task<List<HashedFileSystemFileDto>> HashFilesAsync(IReadOnlyCollection<HashedFileSystemFileDto> files, Func<Task> callback, CancellationToken cancellationToken);
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
#endregion
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
using System.Linq;
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Enums.FileSystem;
using Lumina.Domain.SharedKernel.Common.Enums.FileSystem;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
#endregion
@@ -2,7 +2,7 @@
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
@@ -19,6 +19,8 @@ public static class AddBookRequestMapping
public static AddBookCommand ToCommand(this AddBookRequest request)
{
return new AddBookCommand(
request.LibraryId,
request.Path,
request.Metadata,
request.Format,
request.Edition,
@@ -7,12 +7,13 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -110,6 +111,8 @@ public static class BookEntityMapping
return Book.Create(
BookId.Create(repositoryEntity.Id),
LibraryId.Create(repositoryEntity.LibraryId),
repositoryEntity.Path,
writtenContentMetadataResult.Value,
bookFormat,
Optional<string>.FromNullable(repositoryEntity.Edition),
@@ -190,6 +193,8 @@ public static class BookEntityMapping
);
return new BookResponse(
repositoryEntity.Id,
repositoryEntity.LibraryId,
repositoryEntity.Path,
metadata,
repositoryEntity.Format,
repositoryEntity.Edition,
@@ -207,6 +212,9 @@ public static class BookEntityMapping
[.. repositoryEntity.ISBNs.ToResponses()],
null,
[.. repositoryEntity.Ratings.ToResponses()],
repositoryEntity.MetadataStatus,
repositoryEntity.LastMetadataUpdateUtc,
repositoryEntity.MetadataProvider,
repositoryEntity.CreatedOnUtc,
repositoryEntity.UpdatedOnUtc
);
@@ -24,6 +24,8 @@ public static class BookMapping
return new BookEntity
{
Id = domainEntity.Id.Value,
LibraryId = domainEntity.LibraryId.Value,
Path = domainEntity.Path,
Title = domainEntity.Metadata.Title,
OriginalTitle = domainEntity.Metadata.OriginalTitle.HasValue ? domainEntity.Metadata.OriginalTitle.Value : null,
Description = domainEntity.Metadata.Description.HasValue ? domainEntity.Metadata.Description.Value : null,
@@ -57,6 +59,9 @@ public static class BookMapping
AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null,
ISBNs = domainEntity.ISBNs.ToRepositoryEntities().ToList(),
Ratings = domainEntity.Ratings.ToRepositoryEntities().ToList(),
MetadataStatus = domainEntity.MetadataStatus,
LastMetadataUpdateUtc = domainEntity.LastMetadataUpdateUtc.HasValue ? domainEntity.LastMetadataUpdateUtc.Value : null,
MetadataProvider = domainEntity.MetadataProvider.HasValue ? domainEntity.MetadataProvider.Value : null,
CreatedOnUtc = domainEntity.CreatedOnUtc,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null,
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for applying <see cref="BookMetadataDto"/> to <see cref="Book"/>.
/// </summary>
public static class BookMetadataDtoMapping
{
/// <summary>
/// Applies the metadata of <paramref name="metadata"/> to <paramref name="book"/>, marking its metadata as enriched by the provided <paramref name="providerName"/>.
/// </summary>
/// <param name="book">The domain book to which the metadata is applied.</param>
/// <param name="metadata">The metadata to be applied.</param>
/// <param name="providerName">The name of the metadata provider that enriched the book.</param>
/// <param name="lastUpdateUtc">The date and time when the metadata was enriched.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public static ErrorOr<Success> ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc)
{
if (string.IsNullOrWhiteSpace(metadata.Title))
return Domain.SharedKernel.Common.Errors.Errors.Metadata.TitleCannotBeEmpty;
if (metadata.ReleaseInfo is null)
return Domain.SharedKernel.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull;
ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate),
Optional<int>.FromNullable(metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
List<ErrorOr<Genre>> domainGenresResult = metadata.Genres is not null
? [.. metadata.Genres.Select(genre => Genre.Create(genre.Name))]
: [];
List<Error> genresErrors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)];
if (genresErrors.Count != 0)
return genresErrors;
List<ErrorOr<Tag>> domainTagsResult = metadata.Tags is not null
? [.. metadata.Tags.Select(tag => Tag.Create(tag.Name))]
: [];
List<Error> tagsErrors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)];
if (tagsErrors.Count != 0)
return tagsErrors;
Optional<LanguageInfo> languageInfo = Optional<LanguageInfo>.None();
if (metadata.Language is not null)
{
ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(metadata.Language.LanguageCode, metadata.Language.LanguageName, Optional<string>.FromNullable(metadata.Language.NativeName));
if (languageInfoResult.IsError)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
Optional<LanguageInfo> originalLanguageInfo = Optional<LanguageInfo>.None();
if (metadata.OriginalLanguage is not null)
{
ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(metadata.OriginalLanguage.LanguageCode, metadata.OriginalLanguage.LanguageName, Optional<string>.FromNullable(metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsError)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
ErrorOr<WrittenContentMetadata> writtenContentMetadataResult = WrittenContentMetadata.Create(
metadata.Title,
Optional<string>.FromNullable(metadata.OriginalTitle),
Optional<string>.FromNullable(metadata.Description),
releaseInfoResult.Value,
[.. domainGenresResult.Select(genreResult => genreResult.Value)],
[.. domainTagsResult.Select(tagResult => tagResult.Value)],
languageInfo,
originalLanguageInfo,
Optional<string>.FromNullable(metadata.Publisher),
Optional<int>.FromNullable(metadata.PageCount)
);
if (writtenContentMetadataResult.IsError)
return writtenContentMetadataResult.Errors;
List<ErrorOr<Isbn>> domainIsbnsResult = metadata.Isbns is not null
? [.. metadata.Isbns.Where(isbn => isbn.Value is not null && isbn.Format is not null).Select(isbn => Isbn.Create(isbn.Value, (IsbnFormat)(int)isbn.Format!.Value))]
: [];
List<Error> isbnsErrors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)];
if (isbnsErrors.Count != 0)
return isbnsErrors;
List<ErrorOr<BookRating>> domainRatingsResult = metadata.Ratings is not null
? [.. metadata.Ratings.Where(rating => rating.Value is not null && rating.MaxValue is not null).Select(rating => BookRating.Create(
rating.Value!.Value,
rating.MaxValue!.Value,
Optional<BookRatingSource>.FromNullable((BookRatingSource?)(rating.Source is null ? null : (BookRatingSource)(int)rating.Source.Value)),
Optional<int>.FromNullable(rating.VoteCount)
))]
: [];
List<Error> ratingsErrors = [.. domainRatingsResult.Where(ratingResult => ratingResult.IsError).SelectMany(ratingResult => ratingResult.Errors)];
if (ratingsErrors.Count != 0)
return ratingsErrors;
book.ApplyEnrichedMetadata(
writtenContentMetadataResult.Value,
Optional<BookFormat>.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null),
Optional<string>.FromNullable(metadata.Edition),
Optional<int>.FromNullable(metadata.VolumeNumber),
Optional<BookSeries>.None(),
Optional<string>.FromNullable(metadata.ASIN),
Optional<string>.FromNullable(metadata.GoodreadsId),
Optional<string>.FromNullable(metadata.LCCN),
Optional<string>.FromNullable(metadata.OCLCNumber),
Optional<string>.FromNullable(metadata.OpenLibraryId),
Optional<string>.FromNullable(metadata.LibraryThingId),
Optional<string>.FromNullable(metadata.GoogleBooksId),
Optional<string>.FromNullable(metadata.BarnesAndNobleId),
Optional<string>.FromNullable(metadata.AppleBooksId),
[.. domainIsbnsResult.Select(isbnResult => isbnResult.Value)],
[.. domainRatingsResult.Select(ratingResult => ratingResult.Value)],
providerName,
lastUpdateUtc
);
return Result.Success;
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Extension methods for converting <see cref="GetBooksRequest"/>.
/// </summary>
public static class GetBooksRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetBooksQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetBooksQuery ToQuery(this GetBooksRequest request)
{
return new GetBooksQuery(request.LibraryId);
}
}
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
@@ -2,7 +2,7 @@
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Linq;
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="GetLibraryMetadataProvidersRequest"/>.
/// </summary>
public static class GetLibraryMetadataProvidersRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetLibraryMetadataProvidersQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetLibraryMetadataProvidersQuery ToQuery(this GetLibraryMetadataProvidersRequest request)
{
return new GetLibraryMetadataProvidersQuery(request.LibraryId);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="GetPluginSettingsRequest"/>.
/// </summary>
public static class GetPluginSettingsRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetPluginSettingsQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
public static GetPluginSettingsQuery ToQuery(this GetPluginSettingsRequest request)
{
return new GetPluginSettingsQuery(request.PluginId);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Responses.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="LibraryMetadataProviderConfigurationEntity"/>.
/// </summary>
public static class LibraryMetadataProviderConfigurationEntityMapping
{
/// <summary>
/// Converts <paramref name="configuration"/> to <see cref="LibraryMetadataProviderResponse"/>.
/// </summary>
/// <param name="configuration">The repository entity to be converted.</param>
/// <param name="providerName">The display name of the metadata provider.</param>
/// <returns>The converted response.</returns>
public static LibraryMetadataProviderResponse ToResponse(this LibraryMetadataProviderConfigurationEntity configuration, string providerName)
{
return new LibraryMetadataProviderResponse(
configuration.PluginId,
providerName,
configuration.IsEnabled,
configuration.Rank
);
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Responses.Plugins;
using System.Collections.Generic;
using System.Text.Json;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="PluginEntity"/>.
/// </summary>
public static class PluginEntityMapping
{
/// <summary>
/// Converts <paramref name="pluginEntity"/> to <see cref="PluginResponse"/>.
/// </summary>
/// <param name="pluginEntity">The repository entity to be converted.</param>
/// <returns>The converted response.</returns>
public static PluginResponse ToResponse(this PluginEntity pluginEntity)
{
return new PluginResponse(
pluginEntity.Id,
pluginEntity.Name,
pluginEntity.Author,
pluginEntity.Version,
pluginEntity.Description,
pluginEntity.LoadStatus,
pluginEntity.LoadError,
pluginEntity.ToSettings()
);
}
/// <summary>
/// Deserializes the settings of <paramref name="pluginEntity"/>.
/// </summary>
/// <param name="pluginEntity">The repository entity whose settings are deserialized.</param>
/// <returns>The deserialized settings, or <see langword="null"/> when no settings are stored.</returns>
public static IReadOnlyDictionary<string, string>? ToSettings(this PluginEntity pluginEntity)
{
if (pluginEntity.SettingsJson is null)
return null;
return JsonSerializer.Deserialize<Dictionary<string, string>>(pluginEntity.SettingsJson);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="PluginSettingDescriptorDto"/>.
/// </summary>
public static class PluginSettingDescriptorMapping
{
/// <summary>
/// Converts <paramref name="descriptor"/> to <see cref="PluginSettingDescriptorResponse"/>.
/// </summary>
/// <param name="descriptor">The plugin contract setting descriptor to be converted.</param>
/// <returns>The converted response.</returns>
public static PluginSettingDescriptorResponse ToResponse(this PluginSettingDescriptorDto descriptor)
{
return new PluginSettingDescriptorResponse(
descriptor.Key,
descriptor.Label,
(PluginSettingType)(int)descriptor.Type,
descriptor.DefaultValue,
descriptor.AllowedValues
);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="ReorderLibraryMetadataProvidersRequest"/>.
/// </summary>
public static class ReorderLibraryMetadataProvidersRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="ReorderLibraryMetadataProvidersCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static ReorderLibraryMetadataProvidersCommand ToCommand(this ReorderLibraryMetadataProvidersRequest request)
{
return new ReorderLibraryMetadataProvidersCommand(request.LibraryId, request.PluginIds);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="SetLibraryMetadataProviderEnabledRequest"/>.
/// </summary>
public static class SetLibraryMetadataProviderEnabledRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="SetLibraryMetadataProviderEnabledCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static SetLibraryMetadataProviderEnabledCommand ToCommand(this SetLibraryMetadataProviderEnabledRequest request)
{
return new SetLibraryMetadataProviderEnabledCommand(request.LibraryId, request.PluginId, request.IsEnabled);
}
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings;
using Lumina.Contracts.Requests.Plugins;
#endregion
namespace Lumina.Application.Common.Mapping.Plugins;
/// <summary>
/// Extension methods for converting <see cref="UpdatePluginSettingsRequest"/>.
/// </summary>
public static class UpdatePluginSettingsRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="UpdatePluginSettingsCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static UpdatePluginSettingsCommand ToCommand(this UpdatePluginSettingsRequest request)
{
return new UpdatePluginSettingsCommand(request.PluginId, request.Settings);
}
}
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDirectories;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetFiles;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Files.Queries.GetTreeFiles;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.CombinePath;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Commands.SplitPath;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathRoot;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Thumbnails.Queries.GetThumbnail;
@@ -8,9 +8,9 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
@@ -21,7 +21,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -13,7 +13,7 @@ using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -13,7 +13,7 @@ using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -20,7 +20,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -8,9 +8,9 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
@@ -24,7 +24,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
@@ -22,15 +22,15 @@ public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDele
{
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsModel _mediaSettingsModel;
private readonly MediaSettingsDto _mediaSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryDeletedDomainEventHandler"/> class.
/// </summary>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsModel"/>.</param>
public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsModel> mediaSettingsModelOptions)
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsDto> mediaSettingsModelOptions)
{
_environmentContext = environmentContext;
_pathService = pathService;
@@ -2,10 +2,9 @@
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
@@ -18,6 +17,7 @@ using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
@@ -30,7 +30,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsModel _mediaSettingsModel;
private readonly MediaSettingsDto _mediaSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="LibrarySavedDomainEventHandler"/> class.
@@ -38,12 +38,12 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsModel"/>.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsDto"/>.</param>
public LibrarySavedDomainEventHandler(
IUnitOfWork unitOfWork,
IEnvironmentContext environmentContext,
IPathService pathService,
IOptions<MediaSettingsModel> mediaSettingsModelOptions)
IOptions<MediaSettingsDto> mediaSettingsModelOptions)
{
_unitOfWork = unitOfWork;
_environmentContext = environmentContext;
@@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
@@ -7,12 +7,12 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
@@ -15,7 +15,7 @@ using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.SharedKernel.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress;
@@ -1,6 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -1,8 +1,9 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Lumina.Contracts.DTO.MediaContributors;
@@ -15,6 +16,8 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Command for adding a book.
/// </summary>
/// <param name="LibraryId">The Id of the media library this book belongs to.</param>
/// <param name="Path">The file system path of the book.</param>
/// <param name="Metadata">Written content metadata of the book.</param>
/// <param name="Format">The format of the book (e.g., Hardcover, Paperback), if applicable.</param>
/// <param name="Edition">The edition of the book, if applicable.</param>
@@ -32,8 +35,10 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book.</param>
/// <param name="Contributors">The list of media contributors (actors, directors, etc) starring in this book.</param>
/// <param name="Ratings">The list of ratings for this book.</param>
[DebuggerDisplay("Title: {Title}")]
[DebuggerDisplay("Title: {Metadata.Title}")]
public record AddBookCommand(
Guid LibraryId,
string Path,
WrittenContentMetadataDto? Metadata,
BookFormat? Format,
string? Edition,
@@ -4,7 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
@@ -12,6 +12,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaCon
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Collections.Generic;
@@ -139,6 +140,8 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
if (metadataResult.IsError)
return metadataResult.Errors;
ErrorOr<Book> createBookResult = Book.Create(
LibraryId.Create(request.LibraryId),
request.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition),
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.BookLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
@@ -16,6 +16,10 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
/// </summary>
public AddBookCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.WrittenContent.BookLibraryCannotBeNull.Description);
RuleFor(x => x.Path)
.NotEmpty().WithMessage(Errors.WrittenContent.BookPathCannotBeEmpty.Description);
RuleFor(x => x.Metadata)
.NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description)
.ChildRules(metadata =>
@@ -2,12 +2,16 @@
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
/// <summary>
/// Query for getting all books.
/// Query for getting all the books of a media library.
/// </summary>
public record class GetBooksQuery() : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
/// <param name="LibraryId">The Id of the media library whose books are retrieved.</param>
public record GetBooksQuery(
Guid LibraryId
) : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
Loaded 100 of 564 files, more files were not shown because too many files have changed in this diff. Show more