Add EPUB upload + DB integration

Add server-side EPUB import and integrate Prisma + Mongo for novels/chapters. Introduces a new moderator API route (app/api/mod/epub/route.ts) that parses .epub files, creates a novel record in Prisma, and inserts chapter documents into MongoDB via the Chapter Mongoose model. Frontend: novel management UI now supports EPUB upload (app/mod/truyen/novel-client.tsx) with progress/toasts and preserves the manual 'Add novel' dialog. Convert app pages to fetch real data from Prisma and Mongo (app/page.tsx, app/truyen/[slug]/page.tsx, app/truyen/[slug]/[chapterId]/page.tsx), adapt types/props to use authorName, and adjust chapter/comment IDs to use Mongo _id strings. Minor fixes: TTS player logs playback errors, UI text fixes (e.g. "Chương"), and novel-card/other components updated for authorName. package.json updated with epub2, html-to-text and types; pnpm lock updated. Adds tsconfig.tsbuildinfo.
This commit is contained in:
2026-03-05 18:02:11 +07:00
parent 112e8604e2
commit ce805adb08
13 changed files with 582 additions and 138 deletions
+24 -20
View File
@@ -1,42 +1,46 @@
"use client"
import { use, useMemo } from "react"
import Link from "next/link"
import { notFound } from "next/navigation"
import { ChevronLeft, ChevronRight, List } from "lucide-react"
import { getNovelBySlug, getChapter, getChaptersByNovelId, getCommentsByChapterId } from "@/lib/data"
import { Button } from "@/components/ui/button"
import { ReadingSettings } from "@/components/reading-settings"
import { CommentSection } from "@/components/comment-section"
import { TTSPlayer } from "@/components/tts-player"
import { ChapterReaderProgress } from "./chapter-reader-progress"
import { prisma } from "@/lib/prisma"
import connectToMongoDB from "@/lib/mongoose"
import { Chapter as ChapterModel } from "@/lib/models/chapter"
export default function ChapterReaderPage({ params }: { params: Promise<{ slug: string; chapterId: string }> }) {
const { slug, chapterId } = use(params)
export default async function ChapterReaderPage({ params }: { params: Promise<{ slug: string; chapterId: string }> }) {
const { slug, chapterId } = await params
const chapterNumber = parseInt(chapterId, 10)
const novel = getNovelBySlug(slug)
if (!novel || isNaN(chapterNumber)) {
if (isNaN(chapterNumber)) {
notFound()
}
const chapter = getChapter(novel.id, chapterNumber)
const allChapters = getChaptersByNovelId(novel.id)
const maxChapter = allChapters.length
const novel = await prisma.novel.findUnique({
where: { slug }
})
if (!novel) {
notFound()
}
await connectToMongoDB()
const chapter = await ChapterModel.findOne({ novelId: novel.id, number: chapterNumber }).lean()
if (!chapter) {
notFound()
}
const comments = getCommentsByChapterId(chapter.id)
const maxChapter = await ChapterModel.countDocuments({ novelId: novel.id })
const comments: any[] = [] // Temporarily empty
const hasPrev = chapterNumber > 1
const hasNext = chapterNumber < maxChapter
// Extract paragraphs for TTS
const paragraphs = useMemo(
() => chapter.content.split("\n").map((p) => p.trim()).filter(Boolean),
[chapter.content]
)
const paragraphs = chapter.content.split("\n").map((p: string) => p.trim()).filter(Boolean)
return (
<div className="mx-auto max-w-3xl px-4 py-6">
@@ -85,7 +89,7 @@ export default function ChapterReaderPage({ params }: { params: Promise<{ slug:
{/* Chapter content */}
<article className="chapter-content mb-8 rounded-lg border border-border bg-card p-6 font-serif text-foreground/90 md:p-8">
{paragraphs.map((text, idx) => (
{paragraphs.map((text: string, idx: number) => (
<p key={idx} data-p-index={idx} className="mb-4 last:mb-0">
{text}
</p>
@@ -115,11 +119,11 @@ export default function ChapterReaderPage({ params }: { params: Promise<{ slug:
</div>
{/* Save reading progress */}
<ChapterReaderProgress novelId={novel.id} chapterId={chapter.id} chapterNumber={chapter.number} />
<ChapterReaderProgress novelId={novel.id} chapterId={chapter._id.toString()} chapterNumber={chapter.number} />
{/* Comments */}
<section className="border-t border-border pt-8">
<CommentSection comments={comments} novelId={novel.id} chapterId={chapter.id} />
<CommentSection comments={comments} novelId={novel.id} chapterId={chapter._id.toString()} />
</section>
{/* TTS Player */}
@@ -128,7 +132,7 @@ export default function ChapterReaderPage({ params }: { params: Promise<{ slug:
novelSlug={slug}
currentChapter={chapterNumber}
maxChapter={maxChapter}
chapterTitle={`Chuong ${chapter.number}: ${chapter.title}`}
chapterTitle={`Chương ${chapter.number}: ${chapter.title}`}
/>
</div>
)
+43 -22
View File
@@ -1,36 +1,58 @@
"use client"
import { use } from "react"
import { notFound } from "next/navigation"
import { BookOpen, Eye, BookMarked, User, Clock, Layers } from "lucide-react"
import { getNovelBySlug, getChaptersByNovelId, getCommentsByNovelId, genres, formatViews } from "@/lib/data"
import { genres, formatViews } from "@/lib/data"
import { GenreBadge } from "@/components/genre-badge"
import { StarRating } from "@/components/star-rating"
import { ChapterList } from "@/components/chapter-list"
import { CommentSection } from "@/components/comment-section"
import { NovelDetailActions } from "./novel-detail-actions"
import { prisma } from "@/lib/prisma"
import connectToMongoDB from "@/lib/mongoose"
import { Chapter } from "@/lib/models/chapter"
export default function NovelDetailPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = use(params)
const novel = getNovelBySlug(slug)
export default async function NovelDetailPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const novel = await prisma.novel.findUnique({
where: { slug },
include: {
genres: {
include: { genre: true }
}
}
})
if (!novel) {
notFound()
}
const chapters = getChaptersByNovelId(novel.id)
const comments = getCommentsByNovelId(novel.id)
// Fetch chapters from MongoDB
await connectToMongoDB()
const chapters = await Chapter.find({ novelId: novel.id })
.sort({ number: 1 })
.select("id novelId number title createdAt views")
.lean()
const novelGenres = novel.genres
.map((gSlug) => genres.find((g) => g.slug === gSlug))
.filter(Boolean) as typeof genres
// Convert Mongoose documents to plain objects for Server Component
const formattedChapters = chapters.map(c => ({
id: c._id.toString(),
novelId: c.novelId,
number: c.number,
title: c.title,
createdAt: (c.createdAt as Date).toISOString(),
views: c.views || 0,
content: "" // We don't fetch content for the list
}))
const comments: any[] = [] // Temporarily empty until we implement comments
const novelGenres = novel.genres.map(ng => ng.genre) || []
return (
<div className="mx-auto max-w-6xl px-4 py-6">
{/* Novel Header */}
<div className="flex flex-col gap-6 md:flex-row">
{/* Cover */}
<div className={`flex h-64 w-44 shrink-0 items-center justify-center self-center rounded-xl bg-gradient-to-br shadow-lg md:self-start ${novel.coverColor}`}>
<div className={`flex h-64 w-44 shrink-0 items-center justify-center self-center rounded-xl bg-gradient-to-br shadow-lg md:self-start ${novel.coverColor || "from-slate-700 to-slate-800"}`}>
<BookOpen className="h-14 w-14 text-background/80" />
</div>
@@ -39,19 +61,18 @@ export default function NovelDetailPage({ params }: { params: Promise<{ slug: st
<h1 className="text-2xl font-bold text-foreground text-balance md:text-3xl">{novel.title}</h1>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground">
<span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{novel.author}</span>
<span className="flex items-center gap-1"><User className="h-3.5 w-3.5" />{novel.authorName}</span>
<span className="flex items-center gap-1"><Layers className="h-3.5 w-3.5" />{novel.totalChapters} chương</span>
<span className="flex items-center gap-1"><Eye className="h-3.5 w-3.5" />{formatViews(novel.views)} lượt xem</span>
<span className="flex items-center gap-1"><BookMarked className="h-3.5 w-3.5" />{formatViews(novel.bookmarkCount)} bookmark</span>
<span className="flex items-center gap-1"><Clock className="h-3.5 w-3.5" />Cập nhật: {novel.lastUpdated}</span>
<span className="flex items-center gap-1"><Clock className="h-3.5 w-3.5" />Cập nhật: {novel.updatedAt.toLocaleDateString('vi-VN')}</span>
</div>
<div className="flex items-center gap-2">
<span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold ${
novel.status === "Hoàn thành" ? "bg-green-500/10 text-green-600 dark:text-green-400" :
<span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold ${novel.status === "Hoàn thành" ? "bg-green-500/10 text-green-600 dark:text-green-400" :
novel.status === "Đang ra" ? "bg-primary/10 text-primary" :
"bg-muted text-muted-foreground"
}`}>
"bg-muted text-muted-foreground"
}`}>
{novel.status}
</span>
</div>
@@ -64,7 +85,7 @@ export default function NovelDetailPage({ params }: { params: Promise<{ slug: st
))}
</div>
<NovelDetailActions novelId={novel.id} novelSlug={novel.slug} firstChapterNumber={chapters[0]?.number} />
<NovelDetailActions novelId={novel.id} novelSlug={novel.slug} firstChapterNumber={formattedChapters[0]?.number} />
</div>
</div>
@@ -78,13 +99,13 @@ export default function NovelDetailPage({ params }: { params: Promise<{ slug: st
<section className="mt-8">
<h2 className="mb-3 text-lg font-bold text-foreground">Danh Sách Chương</h2>
<div className="rounded-lg border border-border bg-card">
<ChapterList chapters={chapters} novelSlug={novel.slug} />
<ChapterList chapters={formattedChapters as any} novelSlug={novel.slug} />
</div>
</section>
{/* Comments */}
<section className="mt-8">
<CommentSection comments={comments} novelId={novel.id} />
<CommentSection comments={comments as any} novelId={novel.id} />
</section>
</div>
)