Files
Nexus.Reader/src/NexusReader.UI.Shared/Components/Organisms/BookIngestionModal.razor
T
Antigravity 5a2223a4c8 feat: Ingestion Pipeline Stabilization and WASM Service Proxies (#42)
This PR stabilizes the Nexus Ingestion Engine by implementing functional service proxies for the Blazor WASM client and refining the backend infrastructure for real-time progress tracking and database compatibility.

### Key Changes
- **Infrastructure Stabilization**:
  - Implemented production-grade `EbookRepository` with PostgreSQL `EF.Functions.ILike` support.
  - Enforced `IsReadyForReading = false` state for newly added ebooks (resolves #35).
  - Updated `SignalRSyncBroadcaster` to support targeted user messaging and ingestion-specific progress updates (resolves #37).
- **WASM Client Functional Proxies**:
  - Replaced "Throwing" dummy services with `WasmEbookRepository`, `WasmSyncBroadcaster`, `WasmBookStorageService`, and `WasmEmbeddingGenerator`.
  - These services proxy requests to the backend via a new set of Minimal API endpoints in `NexusReader.Web`.
- **Domain Refinement**:
  - Added `IsReadyForReading` flag to the `Ebook` entity to manage background AI processing states.

### Related Issues
- Fixes #35
- Fixes #36
- Fixes #37

---------

Co-authored-by: Marek Jasiński <jasins.marek@gmail.com>
Reviewed-on: #42
Co-authored-by: Antigravity <antigravity@google.com>
Co-committed-by: Antigravity <antigravity@google.com>
2026-05-13 18:24:24 +00:00

248 lines
9.3 KiB
Plaintext

@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)
{
<div class="modal-backdrop" @onclick="CloseModal">
<div class="modal-content glass-panel" @onclick:stopPropagation>
<div class="modal-header">
<h2>Add New Book</h2>
<button class="close-btn" @onclick="CloseModal">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
<div class="modal-body">
<div class="parsing-state shimmer" style="@(IsParsing ? "display:flex;" : "display:none;")">
<div class="shimmer-content">
<div class="spinner"></div>
<p>Scanning metadata...</p>
</div>
</div>
<div class="verification-state" style="@(IsVerifying && !IsParsing ? "display:flex;" : "display:none;")">
@if (Metadata != null)
{
<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">
<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 && !IsVerifying ? "display:flex;" : "display:none;")"
@ondragenter="OnDragEnter"
@ondragleave="OnDragLeave">
<div class="drop-zone">
<InputFile id="epub-upload" OnChange="HandleFileSelected" accept=".epub" class="file-input-cover" />
<div class="drop-zone-content">
<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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
<p>Drag and drop your .epub file here</p>
<span>or click to browse</span>
</div>
</div>
</div>
@if (!string.IsNullOrEmpty(ErrorMessage))
{
<div class="error-message">
@ErrorMessage
</div>
}
</div>
</div>
</div>
}
@code {
/// <summary>
/// Gets or sets a value indicating whether the modal is open.
/// </summary>
[Parameter]
public bool IsOpen { get; set; }
/// <summary>
/// Event triggered when the IsOpen state changes.
/// </summary>
[Parameter]
public EventCallback<bool> IsOpenChanged { get; set; }
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;
private async Task CloseModal()
{
IsOpen = false;
Reset();
await IsOpenChanged.InvokeAsync(false);
}
private void Reset()
{
IsParsing = false;
IsVerifying = false;
IsIngesting = false;
Metadata = null;
ErrorMessage = null;
_isDragging = false;
_epubBytes = null;
}
private void OnDragEnter() => _isDragging = true;
private void OnDragLeave() => _isDragging = false;
private async Task HandleFileSelected(InputFileChangeEventArgs e)
{
_isDragging = false;
var file = e.File;
if (file == null) return;
if (!file.Name.EndsWith(".epub", StringComparison.OrdinalIgnoreCase))
{
ErrorMessage = "Only .epub files are supported.";
return;
}
ErrorMessage = null;
IsParsing = true;
StateHasChanged();
try
{
using var stream = file.OpenReadStream(MaxFileSize);
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
{
ErrorMessage = result.Errors.FirstOrDefault()?.Message ?? "Failed to parse EPUB.";
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error uploading EPUB");
ErrorMessage = $"An unexpected error occurred: {ex.Message}";
}
finally
{
IsParsing = false;
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()
{
// Clear the large byte array so it is eligible for GC even if the component is cached.
_epubBytes = null;
return ValueTask.CompletedTask;
}
}