feat(v3): add v3 stack — backend rewrite, renamed env vars, docs

- New Go backend binary (backend + runner) replacing old scraper/
- Rename SCRAPER_API_URL → BACKEND_API_URL in UI env and docker-compose
- Rename scraperFetch → backendFetch across all 19 UI server files
- Remove SCRAPER_PROXY env var and proxy transport from browser.Config
- Add Meilisearch, Valkey, Caddy to docker-compose
- Add docs/: api-endpoints.md, request-flow.mermaid.md, data-flow.mermaid.md
This commit is contained in:
Admin
2026-03-22 17:27:32 +05:00
parent 29d0eeb7e8
commit a85636d5db
178 changed files with 25951 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/admin/scrape/status
* Admin-only proxy to the Go backend's /api/scrape/status endpoint.
*/
export const GET: RequestHandler = async ({ locals }) => {
if (!locals.user || locals.user.role !== 'admin') {
throw error(403, 'Forbidden');
}
try {
const res = await backendFetch('/api/scrape/status');
if (!res.ok) return json({ running: false });
const data = await res.json();
return json({ running: data.running ?? false });
} catch {
return json({ running: false });
}
};

View File

@@ -0,0 +1,65 @@
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* POST /api/audio/[slug]/[n]
* Proxies the audio generation request to the backend's /api/audio endpoint.
* Keeps the backend URL server-side — the browser never needs to know it.
*
* Body: { voice?: string }
*
* Responses:
* 200 { status: "done" } — audio already cached; client should call
* GET /api/presign/audio to obtain a direct MinIO presigned URL.
* 202 { task_id: string, status: "pending"|"generating" } — generation
* enqueued; poll GET /api/audio/status/[slug]/[n]?voice=... until done.
*/
export const POST: RequestHandler = async ({ params, request }) => {
const { slug, n } = params;
const chapter = parseInt(n, 10);
if (!slug || !chapter || chapter < 1) {
error(400, 'Invalid slug or chapter number');
}
let body: { voice?: string } = {};
try {
body = await request.json();
} catch {
// empty body is fine — scraper will use defaults
}
const scraperRes = await backendFetch(`/api/audio/${slug}/${chapter}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!scraperRes.ok) {
const text = await scraperRes.text().catch(() => '');
log.error('audio', 'backend audio generation failed', { slug, chapter, status: scraperRes.status, body: text });
error(scraperRes.status as Parameters<typeof error>[0], text || 'Audio generation failed');
}
const data = (await scraperRes.json()) as
| { url: string; status: 'done' }
| { task_id: string; status: string };
// 202 Accepted: generation enqueued — return task_id + status for polling.
if (scraperRes.status === 202 || 'task_id' in data) {
return new Response(JSON.stringify(data), {
status: 202,
headers: { 'Content-Type': 'application/json' }
});
}
// 200: audio was already cached.
// Return status only — no url — so the client calls GET /api/presign/audio
// and streams directly from MinIO instead of through the Node.js server.
return new Response(
JSON.stringify({ status: 'done' }),
{ headers: { 'Content-Type': 'application/json' } }
);
};

View File

@@ -0,0 +1,64 @@
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/audio/status/[slug]/[n]?voice=...
* Proxies the audio generation status check to the backend's
* GET /api/audio/status/{slug}/{n} endpoint.
*
* Possible responses passed through to the client:
* {"status":"done"} — audio ready; no url
* {"status":"pending"|"generating","task_id":"..."} — in progress
* {"status":"idle"} — no job yet
* {"status":"failed","error":"..."} — last job failed
*
* When status is "done" the scraper's internal proxy URL is stripped — the
* client must call GET /api/presign/audio to obtain a direct MinIO presigned
* URL. This avoids streaming audio through the Node.js server.
*/
export const GET: RequestHandler = async ({ params, url }) => {
const { slug, n } = params;
const chapter = parseInt(n, 10);
if (!slug || !chapter || chapter < 1) {
error(400, 'Invalid slug or chapter number');
}
const voice = url.searchParams.get('voice') ?? '';
const qs = new URLSearchParams();
if (voice) qs.set('voice', voice);
const scraperRes = await backendFetch(
`/api/audio/status/${slug}/${chapter}?${qs.toString()}`
);
if (!scraperRes.ok) {
const text = await scraperRes.text().catch(() => '');
log.error('audio', 'backend audio status check failed', {
slug,
chapter,
status: scraperRes.status,
body: text
});
error(scraperRes.status as Parameters<typeof error>[0], text || 'Status check failed');
}
const data = (await scraperRes.json()) as {
status: string;
task_id?: string;
url?: string;
error?: string;
};
// Strip the backend's internal proxy URL from "done" responses.
// The client will call GET /api/presign/audio to get a direct MinIO URL,
// avoiding streaming audio through the Node.js server.
if (data.status === 'done') {
delete data.url;
}
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
};

View File

@@ -0,0 +1,47 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { changePassword } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/auth/change-password
* Body: { currentPassword: string, newPassword: string }
* Requires authentication.
*/
export const POST: RequestHandler = async ({ request, locals }) => {
if (!locals.user) {
error(401, 'Not authenticated');
}
let body: { currentPassword?: string; newPassword?: string };
try {
body = await request.json();
} catch {
error(400, 'Invalid JSON body');
}
const currentPassword = body.currentPassword ?? '';
const newPassword = body.newPassword ?? '';
if (!currentPassword || !newPassword) {
error(400, 'currentPassword and newPassword are required');
}
if (newPassword.length < 4) {
error(400, 'New password must be at least 4 characters');
}
try {
const ok = await changePassword(locals.user.id, currentPassword, newPassword);
if (!ok) {
error(401, 'Current password is incorrect');
}
} catch (e: unknown) {
// Re-throw SvelteKit errors as-is
if (e && typeof e === 'object' && 'status' in e) throw e;
log.error('api/auth/change-password', 'unexpected error', { err: String(e) });
error(500, 'An error occurred. Please try again.');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,75 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { loginUser, mergeSessionProgress, createUserSession } from '$lib/server/pocketbase';
import { createAuthToken } from '../../../../hooks.server';
import { log } from '$lib/server/logger';
import { randomBytes } from 'node:crypto';
const AUTH_COOKIE = 'libnovel_auth';
const ONE_YEAR = 60 * 60 * 24 * 365;
/**
* POST /api/auth/login
* Body: { username: string, password: string }
* Returns: { token: string, user: { id, username, role } }
*
* Sets the libnovel_auth cookie and returns the raw token value so the
* iOS app can persist it for subsequent requests.
*/
export const POST: RequestHandler = async ({ request, cookies, locals }) => {
let body: { username?: string; password?: string };
try {
body = await request.json();
} catch {
error(400, 'Invalid JSON body');
}
const username = (body.username ?? '').trim();
const password = body.password ?? '';
if (!username || !password) {
error(400, 'Username and password are required');
}
let user;
try {
user = await loginUser(username, password);
} catch (e) {
log.error('api/auth/login', 'unexpected error', { username, err: String(e) });
error(500, 'An error occurred. Please try again.');
}
if (!user) {
error(401, 'Invalid username or password');
}
// Merge anonymous session progress (non-fatal)
mergeSessionProgress(locals.sessionId, user.id).catch((e) =>
log.warn('api/auth/login', 'mergeSessionProgress failed (non-fatal)', { err: String(e) })
);
const authSessionId = randomBytes(16).toString('hex');
const userAgent = request.headers.get('user-agent') ?? '';
const ip =
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
request.headers.get('x-real-ip') ??
'';
createUserSession(user.id, authSessionId, userAgent, ip).catch((e) =>
log.warn('api/auth/login', 'createUserSession failed (non-fatal)', { err: String(e) })
);
const token = createAuthToken(user.id, user.username, user.role ?? 'user', authSessionId);
cookies.set(AUTH_COOKIE, token, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: ONE_YEAR
});
return json({
token,
user: { id: user.id, username: user.username, role: user.role ?? 'user' }
});
};

View File

@@ -0,0 +1,15 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
const AUTH_COOKIE = 'libnovel_auth';
/**
* POST /api/auth/logout
* Clears the auth cookie and returns { ok: true }.
* Does not revoke the session record from PocketBase —
* for full revocation use DELETE /api/sessions/[id] first.
*/
export const POST: RequestHandler = async ({ cookies }) => {
cookies.delete(AUTH_COOKIE, { path: '/' });
return json({ ok: true });
};

View File

@@ -0,0 +1,22 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getUserByUsername } from '$lib/server/pocketbase';
/**
* GET /api/auth/me
* Returns the currently authenticated user from the request's auth cookie.
* Returns 401 if not authenticated.
*/
export const GET: RequestHandler = async ({ locals }) => {
if (!locals.user) {
error(401, 'Not authenticated');
}
// Fetch full record from PocketBase to get avatar_url
const record = await getUserByUsername(locals.user.username).catch(() => null);
return json({
id: locals.user.id,
username: locals.user.username,
role: locals.user.role,
avatar_url: record?.avatar_url ?? null
});
};

View File

@@ -0,0 +1,84 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { createUser, mergeSessionProgress, createUserSession } from '$lib/server/pocketbase';
import { createAuthToken } from '../../../../hooks.server';
import { log } from '$lib/server/logger';
import { randomBytes } from 'node:crypto';
const AUTH_COOKIE = 'libnovel_auth';
const ONE_YEAR = 60 * 60 * 24 * 365;
/**
* POST /api/auth/register
* Body: { username: string, password: string }
* Returns: { token: string, user: { id, username, role } }
*
* Sets the libnovel_auth cookie and returns the raw token value so the
* iOS app can persist it for subsequent requests.
*/
export const POST: RequestHandler = async ({ request, cookies, locals }) => {
let body: { username?: string; password?: string };
try {
body = await request.json();
} catch {
error(400, 'Invalid JSON body');
}
const username = (body.username ?? '').trim();
const password = body.password ?? '';
if (!username || !password) {
error(400, 'Username and password are required');
}
if (username.length < 3 || username.length > 32) {
error(400, 'Username must be between 3 and 32 characters');
}
if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
error(400, 'Username may only contain letters, numbers, underscores and hyphens');
}
if (password.length < 8) {
error(400, 'Password must be at least 8 characters');
}
let user;
try {
user = await createUser(username, password);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : 'Registration failed.';
if (msg.includes('Username already taken')) {
error(409, 'That username is already taken');
}
log.error('api/auth/register', 'unexpected error', { username, err: String(e) });
error(500, 'An error occurred. Please try again.');
}
// Merge anonymous session progress (non-fatal)
mergeSessionProgress(locals.sessionId, user.id).catch((e) =>
log.warn('api/auth/register', 'mergeSessionProgress failed (non-fatal)', { err: String(e) })
);
const authSessionId = randomBytes(16).toString('hex');
const userAgent = request.headers.get('user-agent') ?? '';
const ip =
request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
request.headers.get('x-real-ip') ??
'';
createUserSession(user.id, authSessionId, userAgent, ip).catch((e) =>
log.warn('api/auth/register', 'createUserSession failed (non-fatal)', { err: String(e) })
);
const token = createAuthToken(user.id, user.username, user.role ?? 'user', authSessionId);
cookies.set(AUTH_COOKIE, token, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: ONE_YEAR
});
return json({
token,
user: { id: user.id, username: user.username, role: user.role ?? 'user' }
});
};

View File

@@ -0,0 +1,109 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getBook, listChapterIdx, getProgress, isBookSaved } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/book/[slug]
* Returns book metadata, chapter list, progress, and library status.
*
* If the book is not yet in PocketBase, asks the backend to enqueue a scrape
* task and returns 202 with { scraping: true, task_id }.
* The client should poll and retry once the task completes.
*/
export const GET: RequestHandler = async ({ params, locals }) => {
const { slug } = params;
// Try PocketBase first
let book = await getBook(slug).catch((e) => {
log.error('api/book', 'getBook failed', { slug, err: String(e) });
return null;
});
if (book) {
let chapters, progress, saved;
try {
[chapters, progress, saved] = await Promise.all([
listChapterIdx(slug),
getProgress(locals.sessionId, slug, locals.user?.id),
isBookSaved(locals.sessionId, slug, locals.user?.id)
]);
} catch (e) {
log.error('api/book', 'failed to load book detail data', { slug, err: String(e) });
error(500, 'Failed to load book');
}
return json({
book,
chapters,
in_lib: true,
saved,
last_chapter: progress?.chapter ?? null,
scraping: false,
task_id: null
});
}
// Fall back to backend: enqueue scrape task if not in library.
try {
const res = await backendFetch(`/api/book-preview/${encodeURIComponent(slug)}`);
if (res.status === 202) {
const body: { task_id: string; message: string } = await res.json();
log.info('api/book', 'scrape task enqueued', { slug, task_id: body.task_id });
return json({ scraping: true, task_id: body.task_id, in_lib: false }, { status: 202 });
}
if (!res.ok) {
log.warn('api/book', 'book-preview returned error', { slug, status: res.status });
error(404, `Book "${slug}" not found`);
}
// 200 — book was already in library
const preview: {
in_lib: boolean;
meta: {
slug: string;
title: string;
author: string;
cover: string;
status: string;
genres: string[];
summary: string;
total_chapters: number;
source_url: string;
};
chapters: { number: number; title: string; date?: string }[];
} = await res.json();
const previewBook = {
id: '',
slug: preview.meta.slug || slug,
title: preview.meta.title,
author: preview.meta.author,
cover: preview.meta.cover,
status: preview.meta.status,
genres: preview.meta.genres ?? [],
summary: preview.meta.summary,
total_chapters: preview.meta.total_chapters,
source_url: preview.meta.source_url,
ranking: 0,
meta_updated: ''
};
return json({
book: previewBook,
chapters: preview.chapters,
in_lib: true,
saved: false,
last_chapter: null,
scraping: false,
task_id: null
});
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('api/book', 'book-preview fetch failed', { slug, err: String(e) });
error(404, `Book "${slug}" not found`);
}
};

View File

@@ -0,0 +1,76 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/browse-page?page=2&genre=all&sort=popular&status=all&q=
*
* Thin proxy to the Go backend's /api/catalogue endpoint.
* Used by the infinite-scroll browse page to append subsequent pages
* without a full SSR navigation.
*
* Normalises the catalogue response to the { novels, page, hasNext } shape
* expected by the client-side infinite scroll in +page.svelte.
*/
export const GET: RequestHandler = async ({ url }) => {
const page = url.searchParams.get('page') ?? '1';
const genre = url.searchParams.get('genre') ?? 'all';
const sort = url.searchParams.get('sort') ?? 'popular';
const status = url.searchParams.get('status') ?? 'all';
const q = url.searchParams.get('q') ?? '';
const params = new URLSearchParams({ page, genre, sort, status });
if (q.trim().length >= 2) {
params.set('q', q.trim());
}
try {
const res = await backendFetch(`/api/catalogue?${params.toString()}`);
if (!res.ok) {
log.error('browse-page', 'backend returned error', { status: res.status });
throw error(502, `Browse fetch failed: ${res.status}`);
}
const data: {
books: Array<{
slug: string;
title: string;
author: string;
cover: string;
status: string;
genres: string[];
total_chapters: number;
source_url: string;
ranking: number;
rating: number;
}>;
page: number;
has_next: boolean;
} = await res.json();
// Normalise to the shape the +page.svelte client-side fetch expects.
const novels = (data.books ?? []).map((book) => ({
slug: book.slug,
title: book.title,
cover: book.cover,
rank: book.ranking > 0 ? `#${book.ranking}` : '',
rating: book.rating > 0 ? String(book.rating) : '',
chapters: book.total_chapters > 0 ? `${book.total_chapters} chapters` : '',
url: book.source_url ?? '',
author: book.author,
status: book.status,
genres: book.genres ?? [],
source_url: book.source_url
}));
return json({
novels,
page: data.page ?? (parseInt(page, 10) || 1),
hasNext: data.has_next ?? false
});
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('browse-page', 'network error', { err: String(e) });
throw error(502, 'Could not reach browse service');
}
};

View File

@@ -0,0 +1,44 @@
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/chapter-text-preview/[slug]/[n]
* Proxies to the backend's /api/chapter-text-preview endpoint.
* Used client-side when the normal chapter path returns no content
* (chapter indexed but not yet scraped to MinIO).
*/
export const GET: RequestHandler = async ({ params, url }) => {
const { slug, n } = params;
const chapter = parseInt(n, 10);
if (!slug || !chapter || chapter < 1) {
error(400, 'Invalid slug or chapter number');
}
// Forward optional query params (chapter_url, title) if present
const qs = new URLSearchParams();
const chapterUrl = url.searchParams.get('chapter_url');
const title = url.searchParams.get('title');
if (chapterUrl) qs.set('chapter_url', chapterUrl);
if (title) qs.set('title', title);
const scraperRes = await backendFetch(
`/api/chapter-text-preview/${encodeURIComponent(slug)}/${chapter}?${qs.toString()}`
).catch((e) => {
log.error('chapter-preview', 'scraper fetch failed', { slug, chapter, err: String(e) });
return null;
});
if (!scraperRes || !scraperRes.ok) {
const status = scraperRes?.status ?? 502;
log.error('chapter-preview', 'scraper returned error', { slug, chapter, status });
error(status as Parameters<typeof error>[0], 'Chapter preview not available');
}
const data = await scraperRes.json();
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
};

View File

@@ -0,0 +1,126 @@
import { json, error } from '@sveltejs/kit';
import { marked } from 'marked';
import type { RequestHandler } from './$types';
import { getBook, listChapterIdx } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/chapter/[slug]/[n]
* Returns rendered chapter HTML, navigation info, and voice list.
* Supports ?preview=1&chapter_url=...&title=... for un-scraped books.
*
* Response shape mirrors ChapterResponse in the iOS APIClient.
*/
export const GET: RequestHandler = async ({ params, url, locals }) => {
const { slug } = params;
const n = parseInt(params.n, 10);
if (!n || n < 1) error(400, 'Invalid chapter number');
const isPreview = url.searchParams.get('preview') === '1';
const chapterUrl = url.searchParams.get('chapter_url') ?? '';
const chapterTitle = url.searchParams.get('title') ?? '';
if (isPreview) {
// Preview path: scrape live, nothing from PocketBase/MinIO
const previewParams = new URLSearchParams();
if (chapterUrl) previewParams.set('chapter_url', chapterUrl);
if (chapterTitle) previewParams.set('title', chapterTitle);
let chapterData: { slug: string; number: number; title: string; text: string; url: string };
try {
const res = await backendFetch(
`/api/chapter-text-preview/${encodeURIComponent(slug)}/${n}?${previewParams.toString()}`
);
if (!res.ok) {
log.error('api/chapter', 'chapter-text-preview returned error', { slug, n, status: res.status });
error(404, `Chapter ${n} not found`);
}
chapterData = await res.json();
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('api/chapter', 'chapter-text-preview fetch failed', { slug, n, err: String(e) });
error(502, 'Could not fetch chapter preview');
}
const html = chapterData.text
? '<p>' + chapterData.text.replace(/\n{2,}/g, '</p><p>').replace(/\n/g, '<br>') + '</p>'
: '';
let voices: string[] = [];
try {
const vRes = await backendFetch('/api/voices');
if (vRes.ok) {
const d = (await vRes.json()) as { voices: string[] };
voices = d.voices ?? [];
}
} catch {
// Non-critical
}
const pb = await getBook(slug).catch(() => null);
return json({
book: { slug, title: pb?.title ?? slug, cover: pb?.cover ?? '' },
chapter: { id: '', slug, number: n, title: chapterData.title || `Chapter ${n}`, date_label: '' },
html,
voices,
prev: null,
next: null,
chapters: [],
is_preview: true
});
}
// Normal path: PocketBase + MinIO
const [book, chapters, voicesRes] = await Promise.all([
getBook(slug),
listChapterIdx(slug),
backendFetch('/api/voices').catch(() => null)
]);
if (!book) error(404, `Book "${slug}" not found`);
const chapterIdx = chapters.find((c) => c.number === n);
if (!chapterIdx) error(404, `Chapter ${n} not found`);
let voices: string[] = [];
try {
if (voicesRes?.ok) {
const data = (await voicesRes.json()) as { voices: string[] };
voices = data.voices ?? [];
}
} catch {
// Non-critical
}
let html = '';
try {
const res = await backendFetch(`/api/chapter-markdown/${encodeURIComponent(slug)}/${n}`);
if (!res.ok) {
log.error('api/chapter', 'chapter-markdown returned error', { slug, n, status: res.status });
error(res.status === 404 ? 404 : 502, res.status === 404 ? `Chapter ${n} not found` : 'Could not fetch chapter content');
}
const markdown = await res.text();
html = marked(markdown) as string;
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('api/chapter', 'failed to fetch chapter content', { slug, n, err: String(e) });
error(502, 'Could not fetch chapter content');
}
const prevChapter = chapters.find((c) => c.number === n - 1) ?? null;
const nextChapter = chapters.find((c) => c.number === n + 1) ?? null;
return json({
book: { slug: book.slug, title: book.title, cover: book.cover ?? '' },
chapter: chapterIdx,
html,
voices,
prev: prevChapter ? prevChapter.number : null,
next: nextChapter ? nextChapter.number : null,
chapters: chapters.map((c) => ({ number: c.number, title: c.title })),
is_preview: false
});
};

View File

@@ -0,0 +1,26 @@
import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { deleteComment } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* DELETE /api/comment/[id]
* Deletes a comment and its replies. Only the comment owner may delete.
* Requires authentication.
*/
export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!locals.user) error(401, 'Login required');
const { id } = params;
try {
await deleteComment(id, locals.user.id);
return new Response(null, { status: 204 });
} catch (e) {
const msg = String(e);
if (msg.includes('Not authorized')) error(403, 'Not authorized to delete this comment');
if (msg.includes('not found')) error(404, 'Comment not found');
log.error('api/comment/[id]', 'deleteComment failed', { id, err: msg });
error(500, 'Failed to delete comment');
}
};

View File

@@ -0,0 +1,33 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { voteComment } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/comment/[id]/vote
* Body: { vote: 'up' | 'down' }
* Casts, changes, or toggles off a vote on a comment.
* Works for both authenticated and anonymous users (session-scoped).
* Returns the updated comment.
*/
export const POST: RequestHandler = async ({ params, request, locals }) => {
const { id } = params;
let body: { vote?: string };
try {
body = await request.json();
} catch {
error(400, 'Invalid JSON body');
}
if (body.vote !== 'up' && body.vote !== 'down') {
error(400, 'vote must be "up" or "down"');
}
try {
const updated = await voteComment(id, body.vote, locals.sessionId, locals.user?.id);
return json(updated);
} catch (e) {
log.error('api/comment/[id]/vote', 'voteComment failed', { id, err: String(e) });
error(500, 'Failed to record vote');
}
};

View File

@@ -0,0 +1,102 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
listComments,
listReplies,
createComment,
getMyVotes,
type CommentSort
} from '$lib/server/pocketbase';
import { presignAvatarUrl } from '$lib/server/minio';
import { log } from '$lib/server/logger';
/**
* GET /api/comments/[slug]?sort=new|top
* Returns top-level comments + their replies + current visitor's votes + avatar URLs.
* Response: { comments: BookComment[], myVotes: Record<string, 'up'|'down'>, avatarUrls: Record<string, string> }
* Each top-level comment has a `replies` array attached.
*/
export const GET: RequestHandler = async ({ params, url, locals }) => {
const { slug } = params;
const sortParam = url.searchParams.get('sort') ?? 'new';
const sort: CommentSort = sortParam === 'top' ? 'top' : 'new';
try {
const topLevel = await listComments(slug, sort);
// Fetch replies for all top-level comments in parallel
const repliesPerComment = await Promise.all(topLevel.map((c) => listReplies(c.id)));
const allReplies = repliesPerComment.flat();
// Build comment+reply list for vote lookup
const allIds = [...topLevel.map((c) => c.id), ...allReplies.map((r) => r.id)];
const myVotes = await getMyVotes(allIds, locals.sessionId, locals.user?.id);
// Attach replies to each top-level comment
const comments = topLevel.map((c, i) => ({
...c,
replies: repliesPerComment[i]
}));
// Batch-resolve avatar presign URLs for all unique user_ids
const allComments = [...topLevel, ...allReplies];
const uniqueUserIds = [...new Set(allComments.map((c) => c.user_id).filter(Boolean))];
const avatarEntries = await Promise.all(
uniqueUserIds.map(async (userId) => {
try {
const url = await presignAvatarUrl(userId);
return [userId, url] as [string, string | null];
} catch {
return [userId, null] as [string, null];
}
})
);
const avatarUrls: Record<string, string> = {};
for (const [userId, url] of avatarEntries) {
if (url) avatarUrls[userId] = url;
}
return json({ comments, myVotes, avatarUrls });
} catch (e) {
log.error('api/comments/[slug]', 'listComments failed', { slug, err: String(e) });
error(500, 'Failed to load comments');
}
};
/**
* POST /api/comments/[slug]
* Body: { body: string, parent_id?: string }
* Creates a new comment or reply. Requires authentication.
*/
export const POST: RequestHandler = async ({ params, request, locals }) => {
if (!locals.user) error(401, 'Login required to comment');
const { slug } = params;
let body: { body?: string; parent_id?: string };
try {
body = await request.json();
} catch {
error(400, 'Invalid JSON body');
}
const text = (body.body ?? '').trim();
if (!text) error(400, 'Comment body is required');
if (text.length > 2000) error(400, 'Comment is too long (max 2000 characters)');
// Enforce 1-level depth: parent_id must be a top-level comment
const parentId = body.parent_id?.trim() || undefined;
try {
const comment = await createComment(
slug,
text,
locals.user.id,
locals.user.username,
parentId
);
return json(comment, { status: 201 });
} catch (e) {
log.error('api/comments/[slug]', 'createComment failed', { slug, err: String(e) });
error(500, 'Failed to post comment');
}
};

View File

@@ -0,0 +1,65 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
listBooks,
recentlyAddedBooks,
allProgress,
getHomeStats,
getSubscriptionFeed
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import type { Book, Progress } from '$lib/server/pocketbase';
/**
* GET /api/home
* Returns home screen data: continue-reading list, recently updated books, stats,
* and subscription feed (books recently read by followed users).
* Requires authentication (enforced by layout guard).
*/
export const GET: RequestHandler = async ({ locals }) => {
let allBooks: Book[] = [];
let recentBooks: Book[] = [];
let progressList: Progress[] = [];
let stats = { totalBooks: 0, totalChapters: 0 };
try {
[allBooks, recentBooks, progressList, stats] = await Promise.all([
listBooks(),
recentlyAddedBooks(8),
allProgress(locals.sessionId, locals.user?.id),
getHomeStats()
]);
} catch (e) {
log.error('api/home', 'failed to load home data', { err: String(e) });
}
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
const continueReading = progressList
.filter((p) => bookMap.has(p.slug))
.slice(0, 6)
.map((p) => ({ book: bookMap.get(p.slug)!, chapter: p.chapter }));
const inProgressSlugs = new Set(continueReading.map((c) => c.book.slug));
const recentlyUpdated = recentBooks.filter((b) => !inProgressSlugs.has(b.slug)).slice(0, 6);
// Subscription feed — only available for logged-in users with following
let subscriptionFeed: Array<{ book: Book; readerUsername: string }> = [];
if (locals.user?.id) {
subscriptionFeed = await getSubscriptionFeed(locals.user.id).catch(() => []);
}
return json({
continue_reading: continueReading,
recently_updated: recentlyUpdated,
stats: {
totalBooks: stats.totalBooks,
totalChapters: stats.totalChapters,
booksInProgress: continueReading.length
},
subscription_feed: subscriptionFeed.map((item) => ({
book: item.book,
readerUsername: item.readerUsername
}))
});
};

View File

@@ -0,0 +1,61 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { listBooks, allProgress, getSavedSlugs } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* GET /api/library
* Returns the user's library: books they have started reading or explicitly saved.
* Each item includes the book record, the last chapter read, and saved_at timestamp.
*
* Response shape mirrors LibraryItem in the iOS APIClient.
*/
export const GET: RequestHandler = async ({ locals }) => {
let allBooks: Awaited<ReturnType<typeof listBooks>>;
let progressList: Awaited<ReturnType<typeof allProgress>>;
let savedSlugs: Set<string>;
try {
[allBooks, progressList, savedSlugs] = await Promise.all([
listBooks(),
allProgress(locals.sessionId, locals.user?.id),
getSavedSlugs(locals.sessionId, locals.user?.id)
]);
} catch (e) {
log.error('api/library', 'failed to load library data', { err: String(e) });
allBooks = [];
progressList = [];
savedSlugs = new Set();
}
const progressMap: Record<string, number> = {};
const progressUpdatedMap: Record<string, string> = {};
for (const p of progressList) {
progressMap[p.slug] = p.chapter;
progressUpdatedMap[p.slug] = p.updated;
}
const progressSlugs = new Set(progressList.map((p) => p.slug));
const books = allBooks.filter((b) => progressSlugs.has(b.slug) || savedSlugs.has(b.slug));
const withProgress = books.filter((b) => progressSlugs.has(b.slug));
const savedOnly = books
.filter((b) => !progressSlugs.has(b.slug))
.sort((a, b) => (a.title ?? '').localeCompare(b.title ?? ''));
withProgress.sort((a, b) => {
const ta = progressUpdatedMap[a.slug] ?? '';
const tb = progressUpdatedMap[b.slug] ?? '';
return tb.localeCompare(ta);
});
const ordered = [...withProgress, ...savedOnly];
const items = ordered.map((book) => ({
book,
last_chapter: progressMap[book.slug] ?? null,
saved_at: progressUpdatedMap[book.slug] ?? new Date().toISOString()
}));
return json(items);
};

View File

@@ -0,0 +1,34 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { saveBook, unsaveBook } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/library/[slug]
* Save a book to the user's personal library.
*/
export const POST: RequestHandler = async ({ params, locals }) => {
const { slug } = params;
try {
await saveBook(locals.sessionId, slug, locals.user?.id);
} catch (e) {
log.error('library', 'saveBook failed', { slug, err: String(e) });
error(500, 'Failed to save book');
}
return json({ ok: true });
};
/**
* DELETE /api/library/[slug]
* Remove a book from the user's personal library.
*/
export const DELETE: RequestHandler = async ({ params, locals }) => {
const { slug } = params;
try {
await unsaveBook(locals.sessionId, slug, locals.user?.id);
} catch (e) {
log.error('library', 'unsaveBook failed', { slug, err: String(e) });
error(500, 'Failed to remove book');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,47 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { presignAudio } from '$lib/server/minio';
import { log } from '$lib/server/logger';
import * as cache from '$lib/server/presignCache';
/**
* GET /api/presign/audio?slug=...&n=...&voice=...
* Returns a presigned MinIO URL for the audio file so the browser
* can stream it directly without going through the server.
* Returns 404 when the audio has not been generated yet.
*
* Results are cached in-process for 50 minutes (MinIO URLs are valid 1 hour)
* to avoid a backend + MinIO round-trip on every "Play" click.
*/
export const GET: RequestHandler = async ({ url }) => {
const slug = url.searchParams.get('slug');
// Accept both 'n' (web) and 'chapter' (iOS) as the chapter number param
const n = parseInt(url.searchParams.get('n') ?? url.searchParams.get('chapter') ?? '', 10);
const voice = url.searchParams.get('voice') ?? '';
if (!slug || !n || n < 1) {
error(400, 'Missing slug or n');
}
const cacheKey = cache.audioKey(slug, n, voice);
// Fast path: return cached URL if still valid.
const cached = await cache.get(cacheKey);
if (cached) {
return json({ url: cached });
}
// Slow path: call backend → MinIO presign.
try {
const presignedUrl = await presignAudio(slug, n, voice || undefined);
await cache.set(cacheKey, presignedUrl);
return json({ url: presignedUrl });
} catch (e) {
const status = (e as { status?: number }).status;
if (status === 404) {
error(404, 'Audio not found');
}
log.error('presign', 'presign audio failed', { slug, n, err: String(e) });
error(500, `Could not get presigned URL: ${e}`);
}
};

View File

@@ -0,0 +1,40 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { presignVoiceSample } from '$lib/server/minio';
import * as cache from '$lib/server/presignCache';
/**
* GET /api/presign/voice-sample?voice=af_bella
* Returns a presigned URL for the voice sample audio file.
* Returns 404 if the sample has not been generated yet.
*
* Results are cached in-process for 50 minutes to avoid a backend + MinIO
* round-trip on every voice-selection preview play.
*/
export const GET: RequestHandler = async ({ url }) => {
const voice = url.searchParams.get('voice');
if (!voice) {
error(400, 'Missing voice parameter');
}
const cacheKey = cache.sampleKey(voice);
// Fast path: return cached URL if still valid.
const cached = await cache.get(cacheKey);
if (cached) {
return json({ url: cached });
}
// Slow path: call backend → MinIO presign.
try {
const presignedUrl = await presignVoiceSample(voice);
await cache.set(cacheKey, presignedUrl);
return json({ url: presignedUrl });
} catch (e) {
const status = (e as { status?: number }).status;
if (status === 404) {
error(404, 'Voice sample not found');
}
error(502, `Failed to presign voice sample: ${e}`);
}
};

View File

@@ -0,0 +1,81 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { presignAvatarUploadUrl, presignAvatarUrl } from '$lib/server/minio';
import { updateUserAvatarUrl, getUserByUsername } from '$lib/server/pocketbase';
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
/**
* POST /api/profile/avatar
* Body: JSON { mime_type: "image/jpeg" | "image/png" | "image/webp" }
*
* Returns a short-lived presigned PUT URL pointing at MinIO (public endpoint)
* so the client can upload the image bytes directly, bypassing the server.
* After the PUT completes, the client must call PATCH /api/profile/avatar
* with the returned key to record it in PocketBase.
*
* Returns: { upload_url: string, key: string }
*/
export const POST: RequestHandler = async ({ request, locals }) => {
if (!locals.user) error(401, 'Not authenticated');
let mimeType = 'image/jpeg';
try {
const body = await request.json();
if (body?.mime_type) mimeType = body.mime_type;
} catch {
// default to jpeg if body is missing/invalid
}
if (!ALLOWED_TYPES.includes(mimeType)) {
error(400, `Unsupported image type: ${mimeType}. Allowed: jpeg, png, webp`);
}
const { uploadUrl, key } = await presignAvatarUploadUrl(locals.user.id, mimeType);
return json({ upload_url: uploadUrl, key });
};
/**
* PATCH /api/profile/avatar
* Body: JSON { key: string }
*
* Called after the client has successfully PUT the image to MinIO via the
* presigned URL. Records the object key in PocketBase and returns a fresh
* presigned GET URL for immediate display.
*
* Returns: { avatar_url: string | null }
*/
export const PATCH: RequestHandler = async ({ request, locals }) => {
if (!locals.user) error(401, 'Not authenticated');
let key: string | undefined;
try {
const body = await request.json();
if (typeof body?.key === 'string') key = body.key;
} catch {
error(400, 'Invalid JSON body');
}
if (!key) error(400, 'Missing "key" field');
await updateUserAvatarUrl(locals.user.id, key);
const avatarUrl = await presignAvatarUrl(locals.user.id);
return json({ avatar_url: avatarUrl });
};
/**
* GET /api/profile/avatar
* Returns a presigned GET URL for the current user's avatar, or null if none set.
*/
export const GET: RequestHandler = async ({ locals }) => {
if (!locals.user) error(401, 'Not authenticated');
const record = await getUserByUsername(locals.user.username).catch(() => null);
if (!record?.avatar_url) {
return json({ avatar_url: null });
}
const avatarUrl = await presignAvatarUrl(locals.user.id);
return json({ avatar_url: avatarUrl });
};

View File

@@ -0,0 +1,27 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { setProgress } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/progress
* Body: { slug: string, chapter: number }
* Records the user's reading position.
* When the user is logged in, progress is keyed by user_id so it syncs across devices.
* When anonymous, progress is keyed by the session cookie.
*/
export const POST: RequestHandler = async ({ request, locals }) => {
const body = await request.json().catch(() => null);
if (!body || typeof body.slug !== 'string' || typeof body.chapter !== 'number') {
error(400, 'Invalid body — expected { slug, chapter }');
}
try {
await setProgress(locals.sessionId, body.slug, body.chapter, locals.user?.id);
} catch (e) {
log.error('progress', 'setProgress failed', { slug: body.slug, chapter: body.chapter, err: String(e) });
error(500, 'Failed to save progress');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,54 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { setProgress, deleteProgress } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/progress/[slug]
* Body: { chapter: number }
* Records the user's reading position for a specific book.
*
* This is a slug-in-path variant of POST /api/progress (which takes slug in body).
* Used by the iOS app where slug is part of the URL path.
*/
export const POST: RequestHandler = async ({ params, request, locals }) => {
const { slug } = params;
const body = await request.json().catch(() => null);
if (!body || typeof body.chapter !== 'number') {
error(400, 'Invalid body — expected { chapter: number }');
}
try {
await setProgress(locals.sessionId, slug, body.chapter, locals.user?.id);
} catch (e) {
log.error('api/progress/[slug]', 'setProgress failed', {
slug,
chapter: body.chapter,
err: String(e)
});
error(500, 'Failed to save progress');
}
return json({ ok: true });
};
/**
* DELETE /api/progress/[slug]
* Removes reading progress for a specific book (removes from library/continue reading).
*/
export const DELETE: RequestHandler = async ({ params, locals }) => {
const { slug } = params;
try {
await deleteProgress(locals.sessionId, slug, locals.user?.id);
} catch (e) {
log.error('api/progress/[slug]', 'deleteProgress failed', {
slug,
err: String(e)
});
error(500, 'Failed to delete progress');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,56 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { setAudioTime, getAudioTime } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* GET /api/progress/audio-time?slug=&chapter=
* Returns the last saved audio position for a chapter, or null.
*/
export const GET: RequestHandler = async ({ url, locals }) => {
const slug = url.searchParams.get('slug');
const chapterParam = url.searchParams.get('chapter');
if (!slug || !chapterParam) {
error(400, 'Missing slug or chapter query params');
}
const chapter = parseInt(chapterParam, 10);
if (isNaN(chapter)) {
error(400, 'chapter must be a number');
}
try {
const audioTime = await getAudioTime(locals.sessionId, slug, chapter, locals.user?.id);
return json({ audioTime });
} catch (e) {
log.error('audio-time', 'GET failed', { slug, chapter, err: String(e) });
error(500, 'Failed to load audio time');
}
};
/**
* PATCH /api/progress/audio-time
* Body: { slug: string, chapter: number, audioTime: number }
* Saves the current audio playback position.
*/
export const PATCH: RequestHandler = async ({ request, locals }) => {
const body = await request.json().catch(() => null);
if (
!body ||
typeof body.slug !== 'string' ||
typeof body.chapter !== 'number' ||
typeof body.audioTime !== 'number'
) {
error(400, 'Invalid body — expected { slug, chapter, audioTime }');
}
try {
await setAudioTime(locals.sessionId, body.slug, body.chapter, body.audioTime, locals.user?.id);
} catch (e) {
log.error('audio-time', 'PATCH failed', { slug: body.slug, chapter: body.chapter, err: String(e) });
error(500, 'Failed to save audio time');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,25 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/ranking
* Proxies to the Go backend's /api/ranking endpoint.
* Returns the top-ranked novels list as JSON.
*/
export const GET: RequestHandler = async () => {
try {
const res = await backendFetch('/api/ranking');
if (!res.ok) {
log.error('api/ranking', 'backend returned error', { status: res.status });
error(502, `Ranking fetch failed: ${res.status}`);
}
const data = await res.json();
return json(data);
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('api/ranking', 'network error', { err: String(e) });
error(502, 'Could not load ranking');
}
};

View File

@@ -0,0 +1,61 @@
/**
* POST /api/scrape
*
* Proxies scrape requests to the Go backend.
* Admin-only — returns 403 if the authenticated user is not an admin.
*
* Request body (JSON):
* { "url": "https://novelfire.net/book/..." } — scrape a single book
* {} — scrape the full catalogue
*
* Responses mirror the Go scraper:
* 202 Accepted — job enqueued
* 409 Conflict — a scrape job is already running
* 400 Bad Request
* 403 Forbidden — not an admin
*/
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
export const POST: RequestHandler = async ({ request, locals }) => {
// Admin guard
if (!locals.user || locals.user.role !== 'admin') {
throw error(403, 'Forbidden');
}
let body: { url?: string } = {};
try {
body = await request.json();
} catch {
// empty body is fine — means "scrape all"
}
// Decide which scraper endpoint to call
const isBookScrape = typeof body.url === 'string' && body.url.length > 0;
const endpoint = isBookScrape ? '/scrape/book' : '/scrape';
let res: Response;
try {
res = await backendFetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: isBookScrape ? JSON.stringify({ url: body.url }) : undefined
});
} catch (e) {
log.error('scrape', 'backend proxy network error', { endpoint, err: String(e) });
throw error(502, 'Could not reach backend');
}
if (!res.ok && res.status >= 500) {
const text = await res.text().catch(() => '');
log.error('scrape', 'backend returned error', { endpoint, status: res.status, body: text });
}
const data = await res.json().catch(() => ({}));
// Pass through the status code from the Go backend (202, 409, 400, …)
return json(data, { status: res.status });
};

View File

@@ -0,0 +1,40 @@
/**
* POST /api/scrape/cancel/[id]
*
* Admin-only proxy that cancels a pending scrape (or audio) task by ID.
* Forwards the request to the Go backend POST /api/cancel-task/{id}.
*
* Responses:
* 200 OK — task cancelled
* 403 Forbidden — not an admin
* 409 Conflict — task cannot be cancelled (already running/done/not found)
*/
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
export const POST: RequestHandler = async ({ params, locals }) => {
if (!locals.user || locals.user.role !== 'admin') {
throw error(403, 'Forbidden');
}
const { id } = params;
if (!id) {
throw error(400, 'Missing task id');
}
let res: Response;
try {
res = await backendFetch(`/api/cancel-task/${encodeURIComponent(id)}`, {
method: 'POST'
});
} catch (e) {
log.error('scrape/cancel', 'network error cancelling task', { id, err: String(e) });
throw error(502, 'Could not reach backend');
}
const data = await res.json().catch(() => ({}));
return json(data, { status: res.status });
};

View File

@@ -0,0 +1,59 @@
/**
* POST /api/scrape/range
*
* Proxies range-scrape requests to the Go backend at POST /scrape/book/range.
* Admin-only.
*
* Request body (JSON):
* { "url": "https://novelfire.net/book/...", "from": 50, "to": 100 }
* "to" is optional — omit to scrape from "from" to the end.
*
* Responses mirror the Go scraper:
* 202 Accepted — job enqueued
* 409 Conflict — a scrape job is already running
* 400 Bad Request
* 403 Forbidden — not an admin
*/
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
export const POST: RequestHandler = async ({ request, locals }) => {
// Admin guard
if (!locals.user || locals.user.role !== 'admin') {
throw error(403, 'Forbidden');
}
let body: { url?: string; from?: number; to?: number } = {};
try {
body = await request.json();
} catch {
throw error(400, 'Invalid JSON body');
}
if (!body.url || typeof body.from !== 'number') {
throw error(400, 'url and from are required');
}
let res: Response;
try {
res = await backendFetch('/scrape/book/range', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: body.url, from: body.from, to: body.to })
});
} catch (e) {
log.error('scrape/range', 'backend proxy network error', { err: String(e) });
throw error(502, 'Could not reach backend');
}
if (!res.ok && res.status >= 500) {
const text = await res.text().catch(() => '');
log.error('scrape/range', 'backend returned error', { status: res.status, body: text });
}
const data = await res.json().catch(() => ({}));
return json(data, { status: res.status });
};

View File

@@ -0,0 +1,34 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/search?q=<query>
* Proxies to the Go backend's /api/search endpoint.
* Returns: { results, local_count, remote_count }
*
* Response shape mirrors SearchResponse in the iOS APIClient.
*/
export const GET: RequestHandler = async ({ url }) => {
const q = url.searchParams.get('q') ?? '';
if (q.trim().length < 2) {
return json({ results: [], local_count: 0, remote_count: 0 });
}
const apiURL = `/api/search?q=${encodeURIComponent(q.trim())}`;
try {
const res = await backendFetch(apiURL);
if (!res.ok) {
log.error('api/search', 'backend returned error', { status: res.status, q });
error(502, `Search failed: ${res.status}`);
}
const data = await res.json();
return json(data);
} catch (e) {
if (e instanceof Error && 'status' in e) throw e;
log.error('api/search', 'network error', { q, err: String(e) });
error(502, 'Could not reach backend');
}
};

View File

@@ -0,0 +1,32 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { listUserSessions } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* GET /api/sessions
* Returns all active sessions for the logged-in user.
*/
export const GET: RequestHandler = async ({ locals }) => {
if (!locals.user) {
error(401, 'Not logged in');
}
try {
const sessions = await listUserSessions(locals.user.id);
// Don't expose raw session_id to the client — only the record ID for revocation
const safe = sessions.map((s) => ({
id: s.id,
user_agent: s.user_agent,
ip: s.ip,
created_at: s.created_at,
last_seen: s.last_seen,
// Tell the client whether this is the currently active session
is_current: s.session_id === locals.user!.authSessionId
}));
return json({ sessions: safe });
} catch (e) {
log.error('sessions', 'GET failed', { err: String(e) });
error(500, 'Failed to load sessions');
}
};

View File

@@ -0,0 +1,41 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { revokeUserSession } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* DELETE /api/sessions/[id]
* Revokes a specific session by its PocketBase record ID.
* Only the owner can revoke their own sessions.
*/
export const DELETE: RequestHandler = async ({ params, locals, cookies }) => {
if (!locals.user) {
error(401, 'Not logged in');
}
const recordId = params.id;
if (!recordId) {
error(400, 'Session ID required');
}
try {
const ok = await revokeUserSession(recordId, locals.user.id);
if (!ok) {
error(404, 'Session not found or not yours');
}
// If the user is terminating their own current session, clear their auth cookie
// so they get logged out immediately (the hook would do this on the next request anyway,
// but clearing it here gives instant feedback for the "end this session" flow).
// For other sessions, we leave the cookie intact.
// We detect "current session" via authSessionId — but since the client sends the
// record ID (not the session_id), we rely on the UI to redirect after ending its own session.
log.info('sessions', 'session revoked', { recordId, userId: locals.user.id });
return json({ ok: true });
} catch (e) {
if (e instanceof Error && 'status' in e) throw e; // re-throw SvelteKit errors
log.error('sessions', 'DELETE failed', { recordId, err: String(e) });
error(500, 'Failed to revoke session');
}
};

View File

@@ -0,0 +1,49 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getSettings, saveSettings } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* GET /api/settings
* Returns the current user's settings (auto_next, voice, speed).
* Returns defaults if no settings record exists yet.
*/
export const GET: RequestHandler = async ({ locals }) => {
try {
const settings = await getSettings(locals.sessionId, locals.user?.id);
return json({
autoNext: settings?.auto_next ?? false,
voice: settings?.voice ?? 'af_bella',
speed: settings?.speed ?? 1.0
});
} catch (e) {
log.error('settings', 'GET failed', { err: String(e) });
error(500, 'Failed to load settings');
}
};
/**
* PUT /api/settings
* Body: { autoNext: boolean, voice: string, speed: number }
* Saves user preferences.
*/
export const PUT: RequestHandler = async ({ request, locals }) => {
const body = await request.json().catch(() => null);
if (
!body ||
typeof body.autoNext !== 'boolean' ||
typeof body.voice !== 'string' ||
typeof body.speed !== 'number'
) {
error(400, 'Invalid body — expected { autoNext, voice, speed }');
}
try {
await saveSettings(locals.sessionId, body, locals.user?.id);
} catch (e) {
log.error('settings', 'PUT failed', { err: String(e) });
error(500, 'Failed to save settings');
}
return json({ ok: true });
};

View File

@@ -0,0 +1,46 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getPublicProfile, getSubscription } from '$lib/server/pocketbase';
import { presignAvatarUrl } from '$lib/server/minio';
import { log } from '$lib/server/logger';
/**
* GET /api/users/[username]
* Returns public profile info + whether the current user is subscribed.
*/
export const GET: RequestHandler = async ({ params, locals }) => {
const { username } = params;
try {
const profile = await getPublicProfile(username);
if (!profile) error(404, `User "${username}" not found`);
// Resolve avatar presigned URL if set
let avatarUrl: string | null = null;
if (profile.avatar_url) {
avatarUrl = await presignAvatarUrl(profile.id).catch(() => null);
}
// Is the current logged-in user subscribed?
let isSubscribed = false;
if (locals.user && locals.user.id !== profile.id) {
const sub = await getSubscription(locals.user.id, profile.id).catch(() => null);
isSubscribed = !!sub;
}
return json({
id: profile.id,
username: profile.username,
avatarUrl,
created: profile.created,
followerCount: profile.followerCount,
followingCount: profile.followingCount,
isSubscribed,
isSelf: locals.user?.id === profile.id
});
} catch (e) {
if ((e as { status?: number }).status === 404) throw e;
log.error('api/users', 'failed to load profile', { username, err: String(e) });
error(500, 'Failed to load profile');
}
};

View File

@@ -0,0 +1,43 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
getUserByUsername,
getUserPublicLibrary,
getUserCurrentlyReading
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* GET /api/users/[username]/library
* Returns the public library + currently-reading list for a user.
* Does not require authentication — all data is public.
*/
export const GET: RequestHandler = async ({ params }) => {
const { username } = params;
const user = await getUserByUsername(username).catch(() => null);
if (!user) error(404, `User "${username}" not found`);
try {
const [currentlyReading, library] = await Promise.all([
getUserCurrentlyReading(user.id),
getUserPublicLibrary(user.id)
]);
return json({
currently_reading: currentlyReading.map((item) => ({
book: item.book,
last_chapter: item.chapter,
saved: false
})),
library: library.map((item) => ({
book: item.book,
last_chapter: item.chapter,
saved: item.saved
}))
});
} catch (e) {
log.error('api/users/library', 'failed to load library', { username, err: String(e) });
error(500, 'Failed to load library');
}
};

View File

@@ -0,0 +1,48 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
getUserByUsername,
subscribe,
unsubscribe,
getSubscription
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
/**
* POST /api/users/[username]/subscribe — subscribe to a user
* DELETE /api/users/[username]/subscribe — unsubscribe
* Requires authentication.
*/
export const POST: RequestHandler = async ({ params, locals }) => {
if (!locals.user) error(401, 'Login required');
const { username } = params;
const target = await getUserByUsername(username).catch(() => null);
if (!target) error(404, `User "${username}" not found`);
if (locals.user.id === target.id) error(400, 'Cannot subscribe to yourself');
try {
await subscribe(locals.user.id, target.id);
const sub = await getSubscription(locals.user.id, target.id);
return json({ subscribed: true, subId: sub?.id ?? null });
} catch (e) {
log.error('api/users/subscribe', 'subscribe failed', { username, err: String(e) });
error(500, 'Failed to subscribe');
}
};
export const DELETE: RequestHandler = async ({ params, locals }) => {
if (!locals.user) error(401, 'Login required');
const { username } = params;
const target = await getUserByUsername(username).catch(() => null);
if (!target) error(404, `User "${username}" not found`);
try {
await unsubscribe(locals.user.id, target.id);
return json({ subscribed: false });
} catch (e) {
log.error('api/users/subscribe', 'unsubscribe failed', { username, err: String(e) });
error(500, 'Failed to unsubscribe');
}
};

View File

@@ -0,0 +1,21 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { backendFetch } from '$lib/server/scraper';
/**
* GET /api/voices
* Proxies the voice list from the backend → Kokoro.
* Returns { voices: string[] }
*/
export const GET: RequestHandler = async () => {
try {
const res = await backendFetch('/api/voices');
if (!res.ok) {
return json({ voices: [] });
}
const data = (await res.json()) as { voices: string[] };
return json({ voices: data.voices ?? [] });
} catch {
return json({ voices: [] });
}
};