Files
Nexus.Reader/src/NexusReader.UI.Shared/Components/Organisms/BookIngestionModal.razor
T

319 lines
12 KiB
Plaintext

@using Microsoft.AspNetCore.Components.Forms
@using NexusReader.Application.Abstractions.Services
@using NexusReader.Application.Queries.Reader
@using NexusReader.Application.Commands.Library
@using NexusReader.UI.Shared.Services
@using System.Net.Http.Json
@inject IEpubMetadataExtractor MetadataExtractor
@inject ILogger<BookIngestionModal> Logger
@inject HttpClient Http
@inject IReaderNavigationService ReaderNavigation
@inject IJSRuntime JSRuntime
@inject ISyncService SyncService
@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>
@if (!IsIngesting && !IsIndexing)
{
<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 && !IsIndexing ? "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 && !IsIndexing ? "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 class="form-group">
<label>Description</label>
<textarea class="form-input" @bind="Metadata.Description" placeholder="Book description" rows="3"></textarea>
</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 && !IsIndexing ? "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>
<div class="indexing-state" style="@(IsIndexing ? "display:flex;" : "display:none;")">
<div class="indexing-content">
<div class="spinner"></div>
<h3>Nexus AI Indexing</h3>
<p class="status-msg">@IngestionStatusMessage</p>
<div class="progress-bar-container">
<div class="progress-bar-fill" style="width: @((IngestionProgressPercent * 100).ToString("F0"))%"></div>
</div>
<span class="percent">@((IngestionProgressPercent * 100).ToString("F0"))%</span>
</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 bool IsIndexing { get; set; }
private string IngestionStatusMessage { get; set; } = "Initializing...";
private double IngestionProgressPercent { get; set; }
private Guid IngestedBookId { get; set; } = Guid.Empty;
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;
protected override async Task OnInitializedAsync()
{
await SyncService.InitializeAsync();
SyncService.OnIngestionProgressReceived += HandleIngestionProgress;
}
private async Task HandleIngestionProgress(string message, double progress)
{
if (!IsIndexing) return;
IngestionStatusMessage = message;
IngestionProgressPercent = progress;
await InvokeAsync(StateHasChanged);
if (progress >= 1.0)
{
// Give the user a moment to see the completion message
await Task.Delay(2500);
// Now close the modal and navigate to the book
if (IngestedBookId != Guid.Empty)
{
var bookId = IngestedBookId;
await InvokeAsync(async () => {
await CloseModal();
ReaderNavigation.NavigateToBook(bookId);
});
}
}
}
private async Task CloseModal()
{
if (IsIngesting || IsIndexing) return;
IsOpen = false;
Reset();
await IsOpenChanged.InvokeAsync(false);
}
private void Reset()
{
IsParsing = false;
IsVerifying = false;
IsIngesting = false;
IsIndexing = false;
IngestionStatusMessage = "Initializing...";
IngestionProgressPercent = 0.0;
IngestedBookId = Guid.Empty;
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),
Metadata.Description
);
var response = await Http.PostAsJsonAsync("api/library/ingest", request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IngestResult>();
if (result != null)
{
IngestedBookId = result.Id;
IsVerifying = false;
IsIngesting = false;
IsIndexing = true;
IngestionStatusMessage = "Book saved! Starting background indexing...";
IngestionProgressPercent = 0.0;
StateHasChanged();
}
}
else
{
ErrorMessage = await response.Content.ReadAsStringAsync();
IsIngesting = false;
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error during ingestion");
ErrorMessage = "Failed to save book to library. Please try again.";
IsIngesting = false;
}
finally
{
StateHasChanged();
}
}
private record IngestResult(Guid Id);
public async ValueTask DisposeAsync()
{
SyncService.OnIngestionProgressReceived -= HandleIngestionProgress;
// Clear the large byte array so it is eligible for GC even if the component is cached.
_epubBytes = null;
await ValueTask.CompletedTask;
}
}