#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Enums.BookLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Common.ValueObjects.Metadata;
using Lumina.Domain.Core.Aggregates.MediaContributor.MediaContributorAggregate.ValueObjects;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Converters;
///
/// Custom JSON converter for the class.
///
public class BookJsonConverter : JsonConverter
{
#region ===================================================================== METHODS ===================================================================================
///
/// Reads and converts JSON to a object.
///
/// The JSON reader.
/// The type of the object to convert.
/// The serializer options.
/// The converted object.
public override Book Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
JsonElement root = doc.RootElement;
Guid id = root.GetProperty("id").GetProperty("value").GetGuid();
DateTime created = root.GetProperty("created").GetDateTime();
WrittenContentMetadata metadata = DeserializeMetadata(root.GetProperty("metadata"));
BookFormat? format = null;
if (root.TryGetProperty("format", out JsonElement formatElement))
{
if (formatElement.ValueKind == JsonValueKind.String)
{
string formatString = formatElement.GetString()!;
if (Enum.TryParse(formatString, out BookFormat parsedFormat))
format = parsedFormat;
}
}
string? edition = root.GetProperty("edition").GetString();
int volumeNumber = root.GetProperty("volumeNumber").GetInt32();
BookSeries series = DeserializeBookSeries(root.GetProperty("series"));
string? asin = root.GetProperty("asin").GetString();
string? goodreadsId = root.GetProperty("goodreadsId").GetString();
string? lccn = root.GetProperty("lccn").GetString();
string? oclcNumber = root.GetProperty("oclcNumber").GetString();
string? openLibraryId = root.GetProperty("openLibraryId").GetString();
string? libraryThingId = root.GetProperty("libraryThingId").GetString();
string? googleBooksId = root.GetProperty("googleBooksId").GetString();
string? barnesAndNobleId = root.GetProperty("barnesAndNobleId").GetString();
string? appleBooksId = root.GetProperty("appleBooksId").GetString();
List isbns = DeserializeIsbns(root.GetProperty("isbNs"));
List contributorIds = DeserializeContributorIds(root.GetProperty("contributors"));
List ratings = DeserializeRatings(root.GetProperty("ratings"));
ErrorOr.ErrorOr createBookResult = Book.Create(
BookId.Create(id),
metadata,
Optional.FromNullable(format),
Optional.FromNullable(edition),
volumeNumber,
Optional.FromNullable(series),
Optional.FromNullable(asin),
Optional.FromNullable(goodreadsId),
Optional.FromNullable(lccn),
Optional.FromNullable(oclcNumber),
Optional.FromNullable(openLibraryId),
Optional.FromNullable(libraryThingId),
Optional.FromNullable(googleBooksId),
Optional.FromNullable(barnesAndNobleId),
Optional.FromNullable(appleBooksId),
created,
default,
isbns,
contributorIds,
ratings: ratings
);
if (createBookResult.IsError)
throw new JsonException($"Failed to create Book: {string.Join(", ", createBookResult.Errors)}");
return createBookResult.Value;
}
}
///
/// Writes a object to JSON. This method is not implemented.
///
/// The JSON writer.
/// The object to write.
/// The serializer options.
public override void Write(Utf8JsonWriter writer, Book value, JsonSerializerOptions options)
{
throw new NotImplementedException("Serialization is not implemented for Book class.");
}
///
/// Deserializes the metadata from JSON.
///
/// The JSON element containing the metadata.
/// The deserialized .
private WrittenContentMetadata DeserializeMetadata(JsonElement element)
{
string? title = element.GetProperty("title").GetString();
string? originalTitle = element.GetProperty("originalTitle").GetString();
string? description = element.GetProperty("description").GetString();
ReleaseInfo releaseInfo = DeserializeReleaseInfo(element.GetProperty("releaseInfo"));
List genres = DeserializeGenres(element.GetProperty("genres"));
List tags = DeserializeTags(element.GetProperty("tags"));
LanguageInfo? language = DeserializeLanguageInfo(element.GetProperty("language"));
LanguageInfo? originalLanguage = DeserializeLanguageInfo(element.GetProperty("originalLanguage"));
string? publisher = element.GetProperty("publisher").GetString();
int? pageCount = null;
if (element.TryGetProperty("pageCount", out JsonElement pageCountElement))
if (pageCountElement.ValueKind != JsonValueKind.Null)
pageCount = pageCountElement.GetInt32();
ErrorOr.ErrorOr metadataResult = WrittenContentMetadata.Create(
title!,
Optional.FromNullable(originalTitle),
Optional.FromNullable(description),
releaseInfo,
genres,
tags,
Optional.FromNullable(language),
Optional.FromNullable(originalLanguage),
Optional.FromNullable(publisher),
Optional.FromNullable(pageCount)
);
if (metadataResult.IsError)
throw new JsonException($"Failed to create WrittenContentMetadata: {string.Join(", ", metadataResult.Errors)}");
return metadataResult.Value;
}
///
/// Deserializes the release info from JSON.
///
/// The JSON element containing the release info.
/// The deserialized .
private ReleaseInfo DeserializeReleaseInfo(JsonElement element)
{
DateOnly? originalReleaseDate = element.TryGetProperty("originalReleaseDate", out JsonElement ordElement) ?
DateOnly.Parse(ordElement.GetString()!) : (DateOnly?)null;
int? originalReleaseYear = element.TryGetProperty("originalReleaseYear", out JsonElement oryElement) && oryElement.ValueKind == JsonValueKind.Number
? oryElement.GetInt32() : (int?)null;
DateOnly? reReleaseDate = element.TryGetProperty("reReleaseDate", out JsonElement rrdElement) && rrdElement.ValueKind == JsonValueKind.String ?
DateOnly.Parse(rrdElement.GetString()!) : (DateOnly?)null;
int? reReleaseYear = element.TryGetProperty("reReleaseYear", out JsonElement rryElement) && rryElement.ValueKind == JsonValueKind.Number
? rryElement.GetInt32() : (int?)null;
string? releaseCountry = element.TryGetProperty("releaseCountry", out JsonElement rcElement) ?
rcElement.GetString() : null;
string? releaseVersion = element.TryGetProperty("releaseVersion", out JsonElement rvElement) ?
rvElement.GetString() : null;
ErrorOr.ErrorOr releaseInfoResult = ReleaseInfo.Create(
Optional.FromNullable(originalReleaseDate),
Optional.FromNullable(originalReleaseYear),
Optional.FromNullable(reReleaseDate),
Optional.FromNullable(reReleaseYear),
Optional.FromNullable(releaseCountry),
Optional.FromNullable(releaseVersion)
);
if (releaseInfoResult.IsError)
throw new JsonException($"Failed to create ReleaseInfo: {string.Join(", ", releaseInfoResult.Errors)}");
return releaseInfoResult.Value;
}
///
/// Deserializes the genres from JSON.
///
/// The JSON element containing the genres.
/// The deserialized list of .
private List DeserializeGenres(JsonElement element)
{
return element.EnumerateArray()
.Select(g => Genre.Create(g.GetProperty("name").GetString()!).Value)
.ToList();
}
///
/// Deserializes the tags from JSON.
///
/// The JSON element containing the tags.
/// The deserialized list of .
private List DeserializeTags(JsonElement element)
{
return element.EnumerateArray()
.Select(t => Tag.Create(t.GetProperty("name").GetString()!).Value)
.ToList();
}
///
/// Deserializes the language info from JSON.
///
/// The JSON element containing the language info.
/// The deserialized .
private LanguageInfo? DeserializeLanguageInfo(JsonElement element)
{
if (element.ValueKind != JsonValueKind.Null)
{
string? languageCode = element.GetProperty("languageCode").GetString();
string? languageName = element.GetProperty("languageName").GetString();
string? nativeName = element.TryGetProperty("nativeName", out JsonElement nnElement) ? nnElement.GetString() : null;
ErrorOr.ErrorOr languageInfoResult = LanguageInfo.Create(
languageCode!,
languageName!,
Optional.FromNullable(nativeName)
);
if (languageInfoResult.IsError)
throw new JsonException($"Failed to create LanguageInfo: {string.Join(", ", languageInfoResult.Errors)}");
return languageInfoResult.Value;
}
else
return null;
}
///
/// Deserializes the book series from JSON.
///
/// The JSON element containing the book series.
/// The deserialized .
private BookSeries DeserializeBookSeries(JsonElement element)
{
// TODO: implement when book series are implemented
return null!;
}
///
/// Deserializes the ISBNs from JSON.
///
/// The JSON element containing the ISBNs.
/// The deserialized list of .
private List DeserializeIsbns(JsonElement element)
{
return element.EnumerateArray()
.Select(i => Isbn.Create(i.GetProperty("value").GetString()!,
Enum.Parse(i.GetProperty("format").GetString()!)).Value)
.ToList();
}
///
/// Deserializes the contributor IDs from JSON.
///
/// The JSON element containing the contributor IDs.
/// The deserialized list of .
private List DeserializeContributorIds(JsonElement element)
{
// TODO: implement when contributors are implemented
return [];
}
///
/// Deserializes the ratings from JSON.
///
/// The JSON element containing the ratings.
/// The deserialized list of .
private List DeserializeRatings(JsonElement element)
{
return element.EnumerateArray()
.Select(r => BookRating.Create(
r.GetProperty("value").GetInt32(),
r.GetProperty("maxValue").GetInt32(),
Optional.FromNullable(Enum.Parse(r.GetProperty("source").GetString()!)),
Optional.FromNullable(
r.TryGetProperty("voteCount", out JsonElement voteCountElement) && voteCountElement.ValueKind != JsonValueKind.Null
? voteCountElement.GetInt32()
: (int?)null)
).Value)
.ToList();
}
#endregion
}