feature/FA-misc_VariousUpdates #41

Merged
conco merged 2 commits from feature/FA-misc_VariousUpdates into master 2025-12-09 14:22:15 +00:00
12 changed files with 476 additions and 26 deletions
Showing only changes of commit e70c39ea75 - Show all commits

View File

@@ -162,4 +162,138 @@ public class NovelUpdateServiceTests
}
private record NovelCreateResult(Novel Novel, Chapter Chapter);
#region UpdateImage Tests
[Fact]
public async Task UpdateImage_sets_NewPath_on_image_without_chapter()
{
// Arrange
using var dbContext = CreateDbContext();
var image = new Image
{
OriginalPath = "http://original/cover.jpg",
NewPath = null
};
dbContext.Images.Add(image);
await dbContext.SaveChangesAsync();
var adapter = Substitute.For<ISourceAdapter>();
var eventBus = Substitute.For<IEventBus>();
var service = CreateService(dbContext, adapter, eventBus);
var newUrl = "https://cdn.example.com/uploaded/cover.jpg";
// Act
await service.UpdateImage(image.Id, newUrl);
// Assert
var updatedImage = await dbContext.Images.FindAsync(image.Id);
updatedImage!.NewPath.Should().Be(newUrl);
updatedImage.OriginalPath.Should().Be("http://original/cover.jpg");
}
[Fact]
public async Task UpdateImage_updates_chapter_body_html_with_new_url()
{
// Arrange
using var dbContext = CreateDbContext();
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
var image = new Image
{
OriginalPath = "http://original/image.jpg",
NewPath = null,
Chapter = chapter
};
chapter.Images.Add(image);
await dbContext.SaveChangesAsync();
// Set up the chapter body with an img tag referencing the image by ID (as PullChapterContents does)
var pendingUrl = "https://pending/placeholder.jpg";
var bodyHtml = $"<p>Content</p><img src=\"{pendingUrl}\" alt=\"{image.Id}\" />";
chapter.Body.Texts.Add(new LocalizationText
{
Language = Language.En,
Text = bodyHtml
});
await dbContext.SaveChangesAsync();
var adapter = Substitute.For<ISourceAdapter>();
var eventBus = Substitute.For<IEventBus>();
var service = CreateService(dbContext, adapter, eventBus, pendingUrl);
var newUrl = "https://cdn.example.com/uploaded/image.jpg";
// Act
await service.UpdateImage(image.Id, newUrl);
// Assert
var updatedImage = await dbContext.Images
.Include(i => i.Chapter)
.ThenInclude(c => c.Body)
.ThenInclude(b => b.Texts)
.FirstAsync(i => i.Id == image.Id);
updatedImage.NewPath.Should().Be(newUrl);
var updatedBodyText = updatedImage.Chapter!.Body.Texts.Single().Text;
var doc = new HtmlDocument();
doc.LoadHtml(updatedBodyText);
var imgNode = doc.DocumentNode.SelectSingleNode("//img");
imgNode.Should().NotBeNull();
imgNode!.GetAttributeValue("src", string.Empty).Should().Be(newUrl);
}
[Fact]
public async Task UpdateImage_does_not_modify_other_images_in_chapter_body()
{
// Arrange
using var dbContext = CreateDbContext();
var source = new Source { Name = "Demo", Key = "demo", Url = "http://demo" };
var (novel, chapter) = CreateNovelWithSingleChapter(dbContext, source);
var image1 = new Image { OriginalPath = "http://original/img1.jpg", Chapter = chapter };
var image2 = new Image { OriginalPath = "http://original/img2.jpg", Chapter = chapter };
chapter.Images.Add(image1);
chapter.Images.Add(image2);
await dbContext.SaveChangesAsync();
var pendingUrl = "https://pending/placeholder.jpg";
var bodyHtml = $"<p>Content</p><img src=\"{pendingUrl}\" alt=\"{image1.Id}\" /><img src=\"{pendingUrl}\" alt=\"{image2.Id}\" />";
chapter.Body.Texts.Add(new LocalizationText
{
Language = Language.En,
Text = bodyHtml
});
await dbContext.SaveChangesAsync();
var adapter = Substitute.For<ISourceAdapter>();
var eventBus = Substitute.For<IEventBus>();
var service = CreateService(dbContext, adapter, eventBus, pendingUrl);
var newUrl = "https://cdn.example.com/uploaded/img1.jpg";
// Act - only update image1
await service.UpdateImage(image1.Id, newUrl);
// Assert
var updatedChapter = await dbContext.Chapters
.Include(c => c.Body)
.ThenInclude(b => b.Texts)
.FirstAsync(c => c.Id == chapter.Id);
var updatedBodyText = updatedChapter.Body.Texts.Single().Text;
var doc = new HtmlDocument();
doc.LoadHtml(updatedBodyText);
var img1Node = doc.DocumentNode.SelectSingleNode($"//img[@alt='{image1.Id}']");
var img2Node = doc.DocumentNode.SelectSingleNode($"//img[@alt='{image2.Id}']");
img1Node!.GetAttributeValue("src", string.Empty).Should().Be(newUrl);
img2Node!.GetAttributeValue("src", string.Empty).Should().Be(pendingUrl);
}
#endregion
}

View File

@@ -350,6 +350,20 @@ public class NovelUpdateService
});
}
// Publish chapter pull events for chapters without body content
var chaptersNeedingPull = novel.Chapters
.Where(c => c.Body?.Texts == null || !c.Body.Texts.Any())
.ToList();
foreach (var chapter in chaptersNeedingPull)
{
await _eventBus.Publish(new ChapterPullRequestedEvent
{
NovelId = novel.Id,
ChapterNumber = chapter.Order
});
}
return novel;
}
@@ -434,6 +448,7 @@ public class NovelUpdateService
if (match != null)
{
match.Attributes["src"].Value = newUrl;
bodyText.Text = chapterDoc.DocumentNode.OuterHtml;
}
}
}

View File

@@ -69,6 +69,7 @@ public class RabbitMQEventBus : IEventBus, IHostedService
await channel.ExchangeDeclareAsync(ExchangeName, ExchangeType.Direct,
cancellationToken: cancellationToken);
await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false, cancellationToken: cancellationToken);
await channel.QueueDeclareAsync(_options.ClientIdentifier, true, false, false,
cancellationToken: cancellationToken);
var consumer = new AsyncEventingBasicConsumer(channel);

View File

@@ -13,7 +13,6 @@
import ChapterNavigation from './ChapterNavigation.svelte';
import ChapterProgressBar from './ChapterProgressBar.svelte';
import { sanitizeChapterHtml } from '$lib/utils/sanitizeChapter';
import ArrowLeft from '@lucide/svelte/icons/arrow-left';
interface Props {
novelId?: string;
@@ -102,12 +101,6 @@
<ChapterProgressBar progress={scrollProgress} />
<div class="space-y-6 pt-2">
<!-- Back Navigation -->
<Button variant="ghost" href="/novels/{novelId}" class="-ml-2 gap-2">
<ArrowLeft class="h-4 w-4" />
Back to Novel
</Button>
<!-- Loading State -->
{#if fetching}
<Card>

View File

@@ -0,0 +1,141 @@
<script lang="ts">
import { client } from '$lib/graphql/client';
import { ImportNovelDocument } from '$lib/graphql/__generated__/graphql';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '$lib/components/ui/card';
interface Props {
open: boolean;
onClose: () => void;
onSuccess?: () => void;
}
let { open = $bindable(), onClose, onSuccess }: Props = $props();
let novelUrl = $state('');
let submitting = $state(false);
let error: string | null = $state(null);
let success = $state(false);
async function handleSubmit(e: Event) {
e.preventDefault();
if (!novelUrl.trim()) {
error = 'Please enter a URL';
return;
}
submitting = true;
error = null;
try {
const result = await client
.mutation(ImportNovelDocument, { input: { novelUrl: novelUrl.trim() } })
.toPromise();
if (result.error) {
error = result.error.message;
return;
}
if (result.data?.importNovel?.novelUpdateRequestedEvent) {
success = true;
setTimeout(() => {
handleClose();
onSuccess?.();
}, 1500);
}
} catch (e) {
error = e instanceof Error ? e.message : 'Unknown error occurred';
} finally {
submitting = false;
}
}
function handleClose() {
novelUrl = '';
error = null;
success = false;
onClose();
}
function handleBackdropClick(e: MouseEvent) {
if (e.target === e.currentTarget) {
handleClose();
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
handleClose();
}
}
</script>
<svelte:window onkeydown={handleKeydown} />
{#if open}
<div
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm"
onclick={handleBackdropClick}
onkeydown={handleKeydown}
role="dialog"
aria-modal="true"
aria-labelledby="import-modal-title"
tabindex="-1"
>
<Card class="w-full max-w-md mx-4 shadow-xl">
<CardHeader>
<CardTitle id="import-modal-title">Import Novel</CardTitle>
<p class="text-muted-foreground text-sm">
Enter the URL of the novel you want to import
</p>
</CardHeader>
<CardContent>
<form onsubmit={handleSubmit} class="space-y-4">
<div class="space-y-2">
<label for="novel-url" class="text-sm font-medium">Novel URL</label>
<Input
id="novel-url"
type="url"
placeholder="https://example.com/novel/..."
bind:value={novelUrl}
disabled={submitting || success}
/>
</div>
{#if error}
<p class="text-destructive text-sm">{error}</p>
{/if}
{#if success}
<p class="text-green-600 dark:text-green-400 text-sm">
Import request submitted successfully!
</p>
{/if}
<div class="flex justify-end gap-2 pt-2">
<Button
type="button"
variant="outline"
onclick={handleClose}
disabled={submitting}
>
Cancel
</Button>
<Button type="submit" disabled={submitting || success || !novelUrl.trim()}>
{#if submitting}
Importing...
{:else if success}
Done
{:else}
Import
{/if}
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
{/if}

View File

@@ -30,7 +30,8 @@
<script lang="ts">
import { onMount } from 'svelte';
import { client } from '$lib/graphql/client';
import { NovelDocument } from '$lib/graphql/__generated__/graphql';
import { NovelDocument, ImportNovelDocument } from '$lib/graphql/__generated__/graphql';
import { isAuthenticated } from '$lib/auth/authStore';
import { Card, CardContent, CardHeader } from '$lib/components/ui/card';
import { Badge } from '$lib/components/ui/badge';
import { Button } from '$lib/components/ui/button';
@@ -49,6 +50,7 @@
import BookOpen from '@lucide/svelte/icons/book-open';
import ChevronDown from '@lucide/svelte/icons/chevron-down';
import ChevronUp from '@lucide/svelte/icons/chevron-up';
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
interface Props {
novelId?: string;
@@ -60,6 +62,9 @@
let fetching = $state(true);
let error: string | null = $state(null);
let descriptionExpanded = $state(false);
let refreshing = $state(false);
let refreshError: string | null = $state(null);
let refreshSuccess = $state(false);
const DESCRIPTION_PREVIEW_LENGTH = 300;
@@ -90,6 +95,13 @@
const chapterCount = $derived(novel?.chapters?.length ?? 0);
const canRefresh = $derived(() => {
if (status === 'COMPLETED') return false;
if (!lastUpdated) return true;
const sixHoursAgo = Date.now() - 6 * 60 * 60 * 1000;
return lastUpdated.getTime() < sixHoursAgo;
});
async function fetchNovel() {
if (!novelId) {
error = 'No novel ID provided';
@@ -123,6 +135,31 @@
}
}
async function refreshNovel() {
if (!novel?.url) return;
refreshing = true;
refreshError = null;
refreshSuccess = false;
try {
const result = await client
.mutation(ImportNovelDocument, { input: { novelUrl: novel.url } })
.toPromise();
if (result.error) {
refreshError = result.error.message;
} else {
refreshSuccess = true;
setTimeout(() => (refreshSuccess = false), 2000);
}
} catch (e) {
refreshError = e instanceof Error ? e.message : 'Failed to refresh';
} finally {
refreshing = false;
}
}
onMount(() => {
fetchNovel();
});
@@ -197,27 +234,53 @@
{#if novel.author}
<p class="text-muted-foreground mt-1">
by
{#if novel.author.externalUrl}
<a
href={novel.author.externalUrl}
target="_blank"
rel="noopener noreferrer"
class="text-primary hover:underline inline-flex items-center gap-1"
href="/novels?author={encodeURIComponent(novel.author.name)}"
class="text-primary hover:underline"
>
{novel.author.name}
<ExternalLink class="h-3 w-3" />
</a>
{:else}
<span>{novel.author.name}</span>
{/if}
</p>
{/if}
</div>
<!-- Badges -->
<div class="flex flex-wrap gap-2">
<div class="flex flex-wrap gap-2 items-center">
<Badge class={statusColor}>{statusLabel}</Badge>
<Badge variant="outline">{languageLabel}</Badge>
{#if $isAuthenticated}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
onclick={refreshNovel}
disabled={refreshing || !canRefresh()}
class="gap-1.5 h-6 text-xs"
>
<RefreshCw class="h-3 w-3 {refreshing ? 'animate-spin' : ''}" />
{refreshing ? 'Refreshing...' : 'Refresh'}
</Button>
</TooltipTrigger>
{#if !canRefresh()}
<TooltipContent>
{status === 'COMPLETED' ? 'Cannot refresh completed novels' : 'Updated less than 6 hours ago'}
</TooltipContent>
{/if}
</Tooltip>
</TooltipProvider>
{/if}
{#if refreshSuccess}
<Badge variant="outline" class="bg-green-500/10 text-green-600 border-green-500/30">
Refresh queued
</Badge>
{/if}
{#if refreshError}
<Badge variant="outline" class="bg-destructive/10 text-destructive border-destructive/30">
{refreshError}
</Badge>
{/if}
</div>
<!-- Stats (inline) -->

View File

@@ -21,7 +21,9 @@
// Local state for search input (for debouncing)
let searchInput = $state(filters.search);
let authorInput = $state(filters.authorName);
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
let authorTimeout: ReturnType<typeof setTimeout> | null = null;
// Status options
const statusOptions: { value: NovelStatus; label: string }[] = [
@@ -50,6 +52,15 @@
}, 300);
}
// Debounced author handler
function handleAuthorInput(value: string) {
authorInput = value;
if (authorTimeout) clearTimeout(authorTimeout);
authorTimeout = setTimeout(() => {
onFilterChange({ ...filters, authorName: value });
}, 300);
}
// Status selection handler
function handleStatusChange(selected: NovelStatus[]) {
onFilterChange({ ...filters, statuses: selected });
@@ -63,6 +74,7 @@
// Clear all filters
function clearFilters() {
searchInput = '';
authorInput = '';
onFilterChange({ ...EMPTY_FILTERS });
}
@@ -72,6 +84,13 @@
searchInput = filters.search;
}
});
// Sync author input when filters prop changes externally
$effect(() => {
if (filters.authorName !== authorInput && !authorTimeout) {
authorInput = filters.authorName;
}
});
</script>
<div class="flex flex-wrap items-center gap-3">
@@ -87,6 +106,16 @@
/>
</div>
<!-- Author Input -->
<div class="min-w-[150px]">
<Input
type="text"
placeholder="Author..."
value={authorInput}
oninput={(e) => handleAuthorInput(e.currentTarget.value)}
/>
</div>
<!-- Status Filter -->
<Select.Root
type="multiple"
@@ -194,6 +223,21 @@
</Badge>
{/if}
{#if filters.authorName}
<Badge variant="secondary" class="gap-1">
Author: {filters.authorName}
<button
onclick={() => {
authorInput = '';
onFilterChange({ ...filters, authorName: '' });
}}
class="hover:bg-secondary-foreground/20 ml-1 rounded-full p-0.5"
>
<X class="h-3 w-3" />
</button>
</Badge>
{/if}
{#each filters.statuses as status (status)}
<Badge variant="secondary" class="gap-1">
{statusOptions.find((o) => o.value === status)?.label ?? status}

View File

@@ -5,8 +5,10 @@
import { NovelsDocument, type NovelsQuery, type NovelTagDto } from '$lib/graphql/__generated__/graphql';
import NovelCard from './NovelCard.svelte';
import NovelFilters from './NovelFilters.svelte';
import ImportNovelModal from './ImportNovelModal.svelte';
import { Button } from '$lib/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '$lib/components/ui/card';
import { isAuthenticated } from '$lib/auth/authStore';
import {
type NovelFilters as NovelFiltersType,
parseFiltersFromURL,
@@ -26,6 +28,7 @@
let error: string | null = $state(null);
let initialLoad = $state(true);
let filters: NovelFiltersType = $state({ ...EMPTY_FILTERS });
let showImportModal = $state(false);
const hasNextPage = $derived(pageInfo?.hasNextPage ?? false);
const novels = $derived(edges.map((edge) => edge.node).filter(Boolean));
@@ -112,7 +115,14 @@
<div class="space-y-4">
<Card class="shadow-md shadow-primary/10">
<CardHeader>
<div class="flex items-center justify-between">
<CardTitle>Novels</CardTitle>
{#if $isAuthenticated}
<Button variant="outline" onclick={() => (showImportModal = true)}>
Import Novel
</Button>
{/if}
</div>
<p class="text-muted-foreground text-sm">
{#if hasActiveFilters(filters)}
Showing filtered results
@@ -177,3 +187,9 @@
</div>
{/if}
</div>
<ImportNovelModal
bind:open={showImportModal}
onClose={() => (showImportModal = false)}
onSuccess={() => fetchNovels()}
/>

View File

@@ -710,6 +710,13 @@ export type UuidOperationFilterInput = {
nlte?: InputMaybe<Scalars['UUID']['input']>;
};
export type ImportNovelMutationVariables = Exact<{
input: ImportNovelInput;
}>;
export type ImportNovelMutation = { importNovel: { novelUpdateRequestedEvent: { novelUrl: string } | null } };
export type GetChapterQueryVariables = Exact<{
novelId: Scalars['UnsignedInt']['input'];
chapterOrder: Scalars['UnsignedInt']['input'];
@@ -735,6 +742,7 @@ export type NovelsQueryVariables = Exact<{
export type NovelsQuery = { novels: { edges: Array<{ cursor: string, node: { id: any, url: string, name: string, description: string, rawStatus: NovelStatus, lastUpdatedTime: any, coverImage: { newPath: string | null } | null, chapters: Array<{ order: any, name: string }>, tags: Array<{ key: string, displayName: string }> } }> | null, pageInfo: { hasNextPage: boolean, endCursor: string | null } } | null };
export const ImportNovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ImportNovel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ImportNovelInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"importNovel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUpdateRequestedEvent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novelUrl"}}]}}]}}]}}]} as unknown as DocumentNode<ImportNovelMutation, ImportNovelMutationVariables>;
export const GetChapterDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChapter"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chapter"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"novelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"novelId"}}},{"kind":"Argument","name":{"kind":"Name","value":"chapterOrder"},"value":{"kind":"Variable","name":{"kind":"Name","value":"chapterOrder"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"body"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"revision"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"images"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"novelId"}},{"kind":"Field","name":{"kind":"Name","value":"novelName"}},{"kind":"Field","name":{"kind":"Name","value":"totalChapters"}},{"kind":"Field","name":{"kind":"Name","value":"prevChapterOrder"}},{"kind":"Field","name":{"kind":"Name","value":"nextChapterOrder"}}]}}]}}]} as unknown as DocumentNode<GetChapterQuery, GetChapterQueryVariables>;
export const NovelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UnsignedInt"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"id"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"eq"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}}]}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"nodes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"rawLanguage"}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"statusOverride"}},{"kind":"Field","name":{"kind":"Name","value":"externalId"}},{"kind":"Field","name":{"kind":"Name","value":"createdTime"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"author"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"externalUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"source"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"tagType"}}]}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}}]}}]}}]}}]}}]} as unknown as DocumentNode<NovelQuery, NovelQueryVariables>;
export const NovelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Novels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"where"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"NovelDtoFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"novels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"where"},"value":{"kind":"Variable","name":{"kind":"Name","value":"where"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"url"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"coverImage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"newPath"}}]}},{"kind":"Field","name":{"kind":"Name","value":"rawStatus"}},{"kind":"Field","name":{"kind":"Name","value":"lastUpdatedTime"}},{"kind":"Field","name":{"kind":"Name","value":"chapters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"order"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<NovelsQuery, NovelsQueryVariables>;

View File

@@ -0,0 +1,7 @@
mutation ImportNovel($input: ImportNovelInput!) {
importNovel(input: $input) {
novelUpdateRequestedEvent {
novelUrl
}
}
}

View File

@@ -4,12 +4,14 @@ export interface NovelFilters {
search: string;
statuses: NovelStatus[];
tags: string[];
authorName: string;
}
export const EMPTY_FILTERS: NovelFilters = {
search: '',
statuses: [],
tags: []
tags: [],
authorName: ''
};
const VALID_STATUSES: NovelStatus[] = ['ABANDONED', 'COMPLETED', 'HIATUS', 'IN_PROGRESS', 'UNKNOWN'];
@@ -30,7 +32,9 @@ export function parseFiltersFromURL(searchParams?: URLSearchParams): NovelFilter
const tagsParam = params.get('tags') ?? '';
const tags = tagsParam.split(',').filter((t) => t.length > 0);
return { search, statuses, tags };
const authorName = params.get('author') ?? '';
return { search, statuses, tags, authorName };
}
/**
@@ -51,6 +55,10 @@ export function filtersToURLParams(filters: NovelFilters): string {
params.set('tags', filters.tags.join(','));
}
if (filters.authorName.trim()) {
params.set('author', filters.authorName.trim());
}
return params.toString();
}
@@ -95,6 +103,15 @@ export function filtersToGraphQLWhere(filters: NovelFilters): NovelDtoFilterInpu
});
}
// Author filter (exact match on author name)
if (filters.authorName.trim()) {
conditions.push({
author: {
name: { eq: filters.authorName.trim() }
}
});
}
// Return null if no filters, single condition if one filter, AND for multiple
if (conditions.length === 0) {
return null;
@@ -111,5 +128,10 @@ export function filtersToGraphQLWhere(filters: NovelFilters): NovelDtoFilterInpu
* Check if any filters are active
*/
export function hasActiveFilters(filters: NovelFilters): boolean {
return filters.search.trim().length > 0 || filters.statuses.length > 0 || filters.tags.length > 0;
return (
filters.search.trim().length > 0 ||
filters.statuses.length > 0 ||
filters.tags.length > 0 ||
filters.authorName.trim().length > 0
);
}

View File

@@ -1,6 +1,7 @@
import { defineMiddleware } from 'astro:middleware';
const STATIC_PATHS = ['/_astro/', '/favicon.svg', '/favicon.ico'];
const AUTH_BYPASS_PATHS = ['/gated-404'];
export const onRequest = defineMiddleware(async (context, next) => {
const { request, url } = context;
@@ -10,6 +11,11 @@ export const onRequest = defineMiddleware(async (context, next) => {
return next();
}
// Bypass auth for gated pages to prevent redirect loops
if (AUTH_BYPASS_PATHS.includes(url.pathname)) {
return next();
}
// Simple presence check for fa_session cookie
const cookieHeader = request.headers.get('cookie') || '';
const hasSession = /fa_session=[^;]+/.test(cookieHeader);