#region ========================================================================= USING =====================================================================================
using Nemera.Contracts.DTO.Common;
using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Nemera.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Nemera.Plugins.Calibre.Core.Mapping;
using Nemera.Plugins.Calibre.Core.Opf;
using Nemera.Plugins.Contracts.Core.Metadata;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Nemera.Plugins.Calibre.Core;
///
/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs.
///
internal sealed class CalibreBookMetadataProvider : IMetadataProvider
{
///
/// Gets the display name of the metadata provider.
///
public string Name => "Calibre";
///
/// Gets the media library types this metadata provider supports.
///
public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook];
///
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
///
public bool RequiresWebAccess => false;
///
/// Searches for the metadata of the media item described by .
///
/// The lookup describing the media item to search for.
/// Cancellation token that can be used to stop the execution.
/// The collection of metadata candidates found for the media item.
public Task> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
BookMetadataDto? metadata = GetMetadata(bookMetadataLookup);
return Task.FromResult>(metadata is null ? [] : [metadata]);
}
///
/// Gets the metadata of the media item described by .
///
/// The lookup describing the media item to get the metadata for.
/// Cancellation token that can be used to stop the execution.
/// The metadata of the media item, or when no metadata was found.
public Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken)
{
return Task.FromResult(GetMetadata(bookMetadataLookup));
}
///
/// Reads the metadata of the book from the OPF file located next to the book file described by .
///
/// The lookup describing the book to get the metadata for.
/// The metadata of the book, or when no OPF file was found.
private static BookMetadataDto? GetMetadata(BookMetadataLookupDto bookMetadataLookup)
{
if (string.IsNullOrWhiteSpace(bookMetadataLookup.Path))
return null;
string opfFilePath = Path.Combine(Path.GetDirectoryName(bookMetadataLookup.Path) ?? string.Empty, "metadata.opf");
if (!File.Exists(opfFilePath))
return null;
return CalibreMapper.Map(OpfReader.Read(opfFilePath));
}
}