feat(ingestion): implement hybrid metadata verification form #34 #41

Merged
mjasin merged 2 commits from feature/issue-34 into develop 2026-05-12 18:19:07 +00:00
15 changed files with 533 additions and 24 deletions
@@ -0,0 +1,29 @@
namespace NexusReader.Application.Abstractions.Services;
/// <summary>
/// Service for managing ebook and cover file storage.
/// </summary>
public interface IBookStorageService
{
/// <summary>
/// Saves an ebook file and returns its relative path/URL.
/// </summary>
Task<string> SaveEbookAsync(byte[] data, string fileName);
/// <summary>
/// Saves an ebook file using a stream and returns its relative path/URL.
/// </summary>
Task<string> SaveEbookAsync(Stream data, string fileName);
/// <summary>
/// Saves a cover image and returns its relative path/URL.
/// Returns null if no cover data is provided.
/// </summary>
Task<string?> SaveCoverAsync(byte[] data, string fileName);
/// <summary>
/// Saves a cover image using a stream and returns its relative path/URL.
/// Returns null if no cover data is provided.
/// </summary>
Task<string?> SaveCoverAsync(Stream data, string fileName);
}
@@ -0,0 +1,21 @@
using NexusReader.Application.Abstractions.Messaging;
namespace NexusReader.Application.Commands.Library;
/// <summary>
/// Command to ingest a new ebook into the library.
/// </summary>
/// <param name="Title">The title of the book.</param>
/// <param name="AuthorName">The name of the author.</param>
/// <param name="CoverImage">The raw bytes of the cover image (optional).</param>
/// <param name="EpubData">The raw bytes of the EPUB file.</param>
/// <param name="UserId">The ID of the user owning the book.</param>
/// <param name="TenantId">The tenant ID for multi-tenant isolation. Defaults to "global" for single-tenant or default usage.</param>
public record IngestEbookCommand(
string Title,
string AuthorName,
byte[]? CoverImage,
byte[] EpubData,
string UserId,
string TenantId = "global"
) : ICommand<Guid>;
@@ -0,0 +1,85 @@
using FluentResults;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Data.Persistence;
using NexusReader.Domain.Entities;
namespace NexusReader.Application.Commands.Library;
public class IngestEbookCommandHandler : IRequestHandler<IngestEbookCommand, Result<Guid>>
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
private readonly IBookStorageService _storageService;
public IngestEbookCommandHandler(
IDbContextFactory<AppDbContext> dbContextFactory,
IBookStorageService storageService)
{
_dbContextFactory = dbContextFactory;
_storageService = storageService;
}
public async Task<Result<Guid>> Handle(IngestEbookCommand request, CancellationToken cancellationToken)
{
using var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
string epubPath;
string? coverUrl;
try
{
// 1. Save Files
epubPath = await _storageService.SaveEbookAsync(request.EpubData, $"{request.Title}.epub");
coverUrl = request.CoverImage != null && request.CoverImage.Length > 0
? await _storageService.SaveCoverAsync(request.CoverImage, $"{request.Title}_cover.jpg")
: null;
}
catch (Exception ex)
{
return Result.Fail(new Error($"Storage failure: {ex.Message}").CausedBy(ex));
}
try
{
// 2. Resolve Author
var authorName = string.IsNullOrWhiteSpace(request.AuthorName) ? "Unknown Author" : request.AuthorName.Trim();
// Use case-insensitive comparison
var author = await context.Authors
.FirstOrDefaultAsync(a => a.Name.ToLower() == authorName.ToLower(), cancellationToken);
if (author == null)
{
author = new Author { Name = authorName };
context.Authors.Add(author);
}
// 3. Create Ebook
var ebook = new Ebook
{
Title = request.Title,
Author = author,
FilePath = epubPath, // Relative URL from wwwroot
CoverUrl = coverUrl,
UserId = request.UserId,
TenantId = request.TenantId,
AddedDate = DateTime.UtcNow
};
context.Ebooks.Add(ebook);
await context.SaveChangesAsync(cancellationToken);
return Result.Ok(ebook.Id);
}
catch (DbUpdateException ex)
{
return Result.Fail(new Error($"Database error during ingestion: {ex.Message}").CausedBy(ex));
}
catch (Exception ex)
{
return Result.Fail(new Error($"Unexpected error during ingestion: {ex.Message}").CausedBy(ex));
}
}
}
@@ -0,0 +1,8 @@
namespace NexusReader.Application.Commands.Library;
public record IngestEbookRequest(
string Title,
string AuthorName,
string? CoverImageBase64,
string EpubDataBase64
);
@@ -1,7 +1,22 @@
namespace NexusReader.Application.Queries.Reader;
public record LocalEpubMetadata(
string Title,
string Author,
byte[]? CoverImage = null
);
/// <summary>
/// Represents metadata extracted from a local EPUB file.
/// </summary>
public record LocalEpubMetadata
{
/// <summary>
/// The title of the book.
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// The author(s) of the book.
/// </summary>
public string Author { get; set; } = string.Empty;
/// <summary>
/// The raw bytes of the cover image, if available.
/// </summary>
public byte[]? CoverImage { get; set; }
}
@@ -75,6 +75,7 @@ public static class DependencyInjection
services.AddScoped<IKnowledgeService, KnowledgeService>();
services.AddTransient<IEpubReader, EpubReaderService>();
services.AddTransient<IEpubMetadataExtractor, EpubMetadataExtractor>();
services.AddSingleton<IBookStorageService, BookStorageService>();
services.AddAuthorizationCore(options =>
{
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Hosting;
using NexusReader.Application.Abstractions.Services;
namespace NexusReader.Infrastructure.Services;
/// <summary>
/// Infrastructure implementation of book storage using local filesystem.
/// All paths returned are relative to the web root.
/// </summary>
public class BookStorageService : IBookStorageService
{
private readonly IWebHostEnvironment _environment;
public BookStorageService(IWebHostEnvironment environment)
{
_environment = environment;
}
public async Task<string> SaveEbookAsync(byte[] data, string fileName)
{
using var stream = new MemoryStream(data);
return await SaveEbookAsync(stream, fileName);
}
public async Task<string> SaveEbookAsync(Stream data, string fileName)
{
var uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads");
EnsureDirectoryExists(uploadsFolder);
var uniqueFileName = $"{Guid.NewGuid()}_{fileName}";
var filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await data.CopyToAsync(fileStream);
}
return Path.Combine("uploads", uniqueFileName);
}
public async Task<string?> SaveCoverAsync(byte[] data, string fileName)
{
if (data == null || data.Length == 0) return null;
using var stream = new MemoryStream(data);
return await SaveCoverAsync(stream, fileName);
}
public async Task<string?> SaveCoverAsync(Stream data, string fileName)
{
var coversFolder = Path.Combine(_environment.WebRootPath, "covers");
EnsureDirectoryExists(coversFolder);
var uniqueFileName = $"{Guid.NewGuid()}_{fileName}";
var filePath = Path.Combine(coversFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await data.CopyToAsync(fileStream);
}
return Path.Combine("covers", uniqueFileName);
}
private void EnsureDirectoryExists(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
@@ -228,7 +228,7 @@ public class EpubMetadataExtractor : IEpubMetadataExtractor
var title = bookRef.Title ?? "Unknown Title";
var author = bookRef.Author ?? "Unknown Author";
byte[]? cover = await bookRef.ReadCoverAsync();
return Result.Ok(new LocalEpubMetadata(title, author, cover));
return Result.Ok(new LocalEpubMetadata { Title = title, Author = author, CoverImage = cover });
}
catch (Exception ex)
{
@@ -1,8 +1,13 @@
@using Microsoft.AspNetCore.Components.Forms
@using NexusReader.Application.Abstractions.Services
@using NexusReader.Application.Queries.Reader
@using NexusReader.Application.Commands.Library
@using System.Net.Http.Json
@inject IEpubMetadataExtractor MetadataExtractor
@inject ILogger<BookIngestionModal> Logger
@inject HttpClient Http
@inject IReaderNavigationService ReaderNavigation
@inject IJSRuntime JSRuntime
@implements IAsyncDisposable
@if (IsOpen)
@@ -24,22 +29,48 @@
</div>
</div>
<div class="metadata-state" style="@(Metadata != null && !IsParsing ? "display:flex;" : "display:none;")">
<div class="verification-state" style="@(IsVerifying && !IsParsing ? "display:flex;" : "display:none;")">
@if (Metadata != null)
{
<div class="metadata-info">
<h3>@Metadata.Title</h3>
<p class="author">@Metadata.Author</p>
<div class="verification-layout">
<div class="cover-preview">
@if (Metadata.CoverImage != null)
{
<img src="data:image/jpeg;base64,@Convert.ToBase64String(Metadata.CoverImage)" alt="Cover Preview" />
}
else
{
<div class="glowing-placeholder">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>
</div>
}
</div>
<div class="verification-form">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-input" @bind="Metadata.Title" placeholder="Enter book title" />
</div>
<div class="form-group">
<label>Author</label>
<input type="text" class="form-input" @bind="Metadata.Author" placeholder="Enter author name" />
</div>
</div>
</div>
<div class="actions">
<button class="btn btn-primary">Confirm & Upload</button>
<button class="btn btn-secondary" @onclick="Reset">Cancel</button>
<NexusButton Class="btn-secondary" OnClick="Reset" Disabled="IsIngesting">Back</NexusButton>
<NexusButton Class="@($"btn-primary {(IsIngesting ? "btn-loading" : "")}")"
OnClick="SaveToLibrary"
Disabled="IsIngesting">
@(IsIngesting ? "" : "Save to Library")
</NexusButton>
</div>
}
</div>
<div class="upload-state @(_isDragging ? "drag-over" : "")"
style="@(!IsParsing && Metadata == null ? "display:flex;" : "display:none;")"
style="@(!IsParsing && !IsVerifying ? "display:flex;" : "display:none;")"
@ondragenter="OnDragEnter"
@ondragleave="OnDragLeave">
<div class="drop-zone">
@@ -64,6 +95,8 @@
</div>
}
@code {
/// <summary>
/// Gets or sets a value indicating whether the modal is open.
@@ -79,8 +112,11 @@
private bool _isDragging;
private bool IsParsing { get; set; }
private bool IsVerifying { get; set; }
private bool IsIngesting { get; set; }
private LocalEpubMetadata? Metadata { get; set; }
private string? ErrorMessage { get; set; }
private byte[]? _epubBytes;
// Allow up to 50 MB
private const long MaxFileSize = 50 * 1024 * 1024;
@@ -95,9 +131,12 @@
private void Reset()
{
IsParsing = false;
IsVerifying = false;
IsIngesting = false;
Metadata = null;
ErrorMessage = null;
_isDragging = false;
_epubBytes = null;
}
private void OnDragEnter() => _isDragging = true;
@@ -123,17 +162,17 @@
try
{
using var stream = file.OpenReadStream(MaxFileSize);
// In Blazor WASM, we might need to copy to memory stream first for synchronous parsing if the parser doesn't stream well over interop
using var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
_epubBytes = memoryStream.ToArray();
memoryStream.Position = 0;
var result = await MetadataExtractor.ExtractMetadataAsync(memoryStream);
if (result.IsSuccess)
{
Metadata = result.Value;
IsVerifying = true;
}
else
{
@@ -143,7 +182,7 @@
catch (Exception ex)
{
Logger.LogError(ex, "Error uploading EPUB");
ErrorMessage = $"An unexpected error occurred: {ex.Message} \n {ex.StackTrace}";
ErrorMessage = $"An unexpected error occurred: {ex.Message}";
}
finally
{
@@ -151,9 +190,56 @@
StateHasChanged();
}
}
private async Task SaveToLibrary()
{
if (Metadata == null || _epubBytes == null) return;
IsIngesting = true;
ErrorMessage = null;
StateHasChanged();
try
{
var request = new IngestEbookRequest(
Metadata.Title,
Metadata.Author,
Metadata.CoverImage != null ? Convert.ToBase64String(Metadata.CoverImage) : null,
Convert.ToBase64String(_epubBytes)
);
var response = await Http.PostAsJsonAsync("api/library/ingest", request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IngestResult>();
if (result != null)
{
await CloseModal();
ReaderNavigation.NavigateToBook(result.Id);
}
}
else
{
ErrorMessage = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error during ingestion");
ErrorMessage = "Failed to save book to library. Please try again.";
}
finally
{
IsIngesting = false;
StateHasChanged();
}
}
private record IngestResult(Guid Id);
public ValueTask DisposeAsync()
{
// Cleanup if necessary
return ValueTask.CompletedTask;
}
}
@@ -242,11 +242,139 @@
transform: translateY(0);
}
/* Verification State */
.verification-state {
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeIn 0.4s ease-out;
}
.verification-layout {
display: grid;
grid-template-columns: 140px 1fr;
gap: 2rem;
align-items: start;
}
.cover-preview {
width: 140px;
height: 200px;
border-radius: 12px;
overflow: hidden;
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
position: relative;
}
.cover-preview img {
width: 100%;
height: 100%;
object-fit: cover;
}
.glowing-placeholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, #1a1a1a 0%, #0a0a0a 100%);
position: relative;
overflow: hidden;
}
.glowing-placeholder::after {
content: '';
position: absolute;
width: 150%;
height: 150%;
background: radial-gradient(circle, var(--nexus-neon-alpha, rgba(0, 255, 153, 0.15)) 0%, transparent 70%);
animation: pulseGlow 4s infinite alternate;
}
.glowing-placeholder svg {
color: var(--nexus-neon, #00ffaa);
opacity: 0.5;
z-index: 1;
filter: drop-shadow(0 0 10px var(--nexus-neon-alpha-deep, rgba(0, 255, 153, 0.3)));
}
.verification-form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.form-group label {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--nexus-text-muted, #888);
font-weight: 600;
}
.form-input {
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 0.75rem 1rem;
color: var(--nexus-text);
font-family: var(--nexus-font-sans);
transition: all 0.3s;
}
.form-input:focus {
outline: none;
border-color: var(--nexus-neon, #00ffaa);
background: rgba(255, 255, 255, 0.06);
box-shadow: 0 0 15px rgba(0, 255, 153, 0.1);
}
.error-message {
margin-top: 1rem;
color: #ff5555;
color: var(--nexus-error, #ff5555);
text-align: center;
font-size: 0.9rem;
padding: 0.75rem;
background: var(--nexus-error-alpha, rgba(255, 85, 85, 0.1));
border-radius: 8px;
border: 1px solid var(--nexus-error-alpha-deep, rgba(255, 85, 85, 0.2));
}
@keyframes pulseGlow {
from { transform: scale(1); opacity: 0.5; }
to { transform: scale(1.2); opacity: 0.8; }
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
filter: grayscale(1);
}
.btn-loading {
position: relative;
color: transparent !important;
}
.btn-loading::after {
content: "";
position: absolute;
width: 20px;
height: 20px;
border: 2px solid rgba(0, 0, 0, 0.1);
border-top-color: #000;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes fadeIn {
@@ -12,4 +12,9 @@ public interface IReaderNavigationService
Task GoToNextChapter();
Task GoToPreviousChapter();
Task UpdateMetadataAsync(int currentIndex, int totalChapters, string title);
/// <summary>
/// Navigates to the reader for a specific book.
/// </summary>
void NavigateToBook(Guid bookId);
}
@@ -1,9 +1,17 @@
using System.Linq;
using Microsoft.AspNetCore.Components;
namespace NexusReader.UI.Shared.Services;
public class ReaderNavigationService : IReaderNavigationService
{
private readonly NavigationManager _navigationManager;
public ReaderNavigationService(NavigationManager navigationManager)
{
_navigationManager = navigationManager;
}
public int CurrentChapterIndex { get; private set; } = 0;
public int TotalChapters { get; private set; } = 1;
public string ChapterTitle { get; private set; } = "Loading...";
@@ -47,6 +55,11 @@ public class ReaderNavigationService : IReaderNavigationService
}
}
public void NavigateToBook(Guid bookId)
{
_navigationManager.NavigateTo($"/reader/{bookId}");
}
private async Task NotifyNavigationChangedAsync()
{
var handlers = OnNavigationChanged?.GetInvocationList();
+11
View File
@@ -45,6 +45,7 @@ builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().Cre
// Dummy registrations for server-only handlers to satisfy DI validation
builder.Services.AddSingleton<IDbContextFactory<AppDbContext>>(new ThrowingDbContextFactory());
builder.Services.AddSingleton<IEmbeddingGenerator<string, Embedding<float>>>(new ThrowingEmbeddingGenerator());
builder.Services.AddSingleton<IBookStorageService>(new ThrowingBookStorageService());
builder.Services.AddApplication();
builder.Services.AddScoped<IEpubReader, WasmEpubReader>();
@@ -64,3 +65,13 @@ public class ThrowingEmbeddingGenerator : IEmbeddingGenerator<string, Embedding<
=> throw new NotSupportedException("Embedding generation cannot be used in WASM client.");
public object? GetService(Type serviceType, object? serviceKey = null) => null;
}
public class ThrowingBookStorageService : IBookStorageService
{
private const string ErrorMessage = "File storage operations are not supported in the WASM client. Use the API endpoint for ingestion.";
public Task<string> SaveEbookAsync(byte[] data, string fileName) => throw new NotSupportedException(ErrorMessage);
public Task<string> SaveEbookAsync(Stream data, string fileName) => throw new NotSupportedException(ErrorMessage);
public Task<string?> SaveCoverAsync(byte[] data, string fileName) => throw new NotSupportedException(ErrorMessage);
public Task<string?> SaveCoverAsync(Stream data, string fileName) => throw new NotSupportedException(ErrorMessage);
}
@@ -48,7 +48,7 @@ public class WasmEpubMetadataExtractor : IEpubMetadataExtractor
var title = bookRef.Title ?? "Unknown Title";
var author = bookRef.Author ?? "Unknown Author";
byte[]? cover = await bookRef.ReadCoverAsync();
return Result.Ok(new LocalEpubMetadata(title, author, cover));
return Result.Ok(new LocalEpubMetadata { Title = title, Author = author, CoverImage = cover });
}
catch (Exception ex)
{
+40 -4
View File
@@ -1,9 +1,11 @@
using NexusReader.Web.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Components;
using NexusReader.Application;
using NexusReader.Infrastructure;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.User;
using NexusReader.Application.Commands.Library;
using MediatR;
using NexusReader.Web.Client.Services;
using NexusReader.UI.Shared.Services;
@@ -48,13 +50,23 @@ builder.Services.AddScoped<IReaderInteractionService, ReaderInteractionService>(
builder.Services.AddScoped<KnowledgeCoordinator>();
builder.Services.AddScoped<ISyncService, SyncService>();
builder.Services.AddHttpClient("NexusAPI", client =>
builder.Services.AddHttpClient("NexusAPI", (sp, client) =>
{
client.BaseAddress = new Uri(builder.Configuration["ApiBaseUrl"] ?? "http://localhost:5000");
var configuration = sp.GetRequiredService<IConfiguration>();
var apiBaseUrl = configuration["ApiBaseUrl"];
if (!string.IsNullOrEmpty(apiBaseUrl))
{
client.BaseAddress = new Uri(apiBaseUrl);
}
else
{
// For local development/Interactive Server, we use the current base address
var nav = sp.GetRequiredService<NavigationManager>();
client.BaseAddress = new Uri(nav.BaseUri);
}
});
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("NexusAPI"));
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IIdentityService, NexusReader.Web.Services.ServerIdentityService>();
builder.Services.AddCascadingAuthenticationState();
@@ -220,9 +232,9 @@ if (!app.Environment.IsDevelopment())
app.UseHttpsRedirection();
}
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapHub<NexusReader.Infrastructure.RealTime.SyncHub>("/synchub");
@@ -281,6 +293,30 @@ knowledgeApi.MapDelete("/", async (IKnowledgeService knowledgeService) =>
return Results.BadRequest(errorMsg);
});
app.MapPost("/api/library/ingest", async ([FromBody] IngestEbookRequest request, ClaimsPrincipal user, IMediator mediator) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
var epubData = Convert.FromBase64String(request.EpubDataBase64);
byte[]? coverData = !string.IsNullOrEmpty(request.CoverImageBase64)
? Convert.FromBase64String(request.CoverImageBase64)
: null;
var command = new IngestEbookCommand(
request.Title,
request.AuthorName,
coverData,
epubData,
userId
);
var result = await mediator.Send(command);
if (result.IsSuccess) return Results.Ok(new { Id = result.Value });
return Results.BadRequest(result.Errors.FirstOrDefault()?.Message ?? "Ingestion failed");
}).RequireAuthorization().DisableAntiforgery();
app.MapPost("/api/StripeWebhook", async (
HttpContext context,
UserManager<NexusUser> userManager,