feat(reader): track reading progress per file with per-format navigation

This commit is contained in:
neon
2025-12-27 14:14:06 -06:00
parent cb39364440
commit 212434219e
15 changed files with 1092 additions and 64 deletions
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { Book } from '../composables/useBooks'
import type { Book, BookFile } from '../composables/useBooks'
import { bookCoverStyle } from '../composables/useBooks'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
@@ -9,29 +9,42 @@ const router = useRouter()
const props = defineProps<{ book: Book }>()
const coverStyle = computed(() => bookCoverStyle(props.book.title ?? String(props.book.id)))
const authorLine = computed(() => props.book.authors.join(', ') || null)
const seriesLine = computed(() => {
if (!props.book.seriesName) return null
const idx = props.book.seriesIndex
return idx != null ? `${props.book.seriesName} #${idx % 1 === 0 ? Math.floor(idx) : idx}` : props.book.seriesName
})
const primaryFile = computed(() => props.book.files.find((f) => f.role === 'primary') ?? props.book.files[0] ?? null)
// Only show format chips when there are multiple files
const extraFiles = computed(() => (props.book.files.length > 1 ? props.book.files : []))
const coverUrl = `/api/books/${props.book.id}/cover`
const coverLoaded = ref(false)
const coverFailed = ref(false)
function openFile(file: BookFile) {
router.push({
name: 'reader',
params: { bookId: props.book.id, fileId: file.id },
query: { format: file.format ?? 'epub' },
})
}
</script>
<template>
<div class="group cursor-pointer flex flex-col gap-1.5" @click="router.push(`/read/${props.book.id}`)">
<div
class="group flex flex-col gap-1.5"
:class="primaryFile ? 'cursor-pointer' : 'cursor-default opacity-60'"
@click="primaryFile && openFile(primaryFile)"
>
<!-- Cover -->
<div
class="relative w-full rounded-sm overflow-hidden shadow-md group-hover:shadow-xl group-hover:scale-[1.02] transition-all duration-150"
style="aspect-ratio: 2/3"
:style="coverLoaded ? {} : coverStyle"
>
<!-- Real cover image -->
<img
v-if="!coverFailed"
:src="coverUrl"
@@ -42,7 +55,7 @@ const coverFailed = ref(false)
:alt="book.title ?? ''"
/>
<!-- Series badge top-left -->
<!-- Series badge -->
<div v-if="seriesLine" class="absolute top-1.5 left-1.5 right-1.5">
<span
class="text-[8px] font-semibold uppercase tracking-widest px-1.5 py-0.5 rounded bg-black/30 backdrop-blur-sm line-clamp-1"
@@ -52,6 +65,20 @@ const coverFailed = ref(false)
</span>
</div>
<!-- Format chips — only shown when book has multiple files -->
<div v-if="extraFiles.length > 0" class="absolute bottom-1.5 right-1.5 flex flex-col gap-1 items-end" @click.stop>
<button
v-for="file in extraFiles"
:key="file.id"
class="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-black/50 backdrop-blur-sm hover:bg-black/70 transition-colors"
:class="file.role === 'primary' ? 'text-white' : 'text-white/70'"
:title="`Open as ${file.format?.toUpperCase() ?? 'unknown'}`"
@click="openFile(file)"
>
{{ file.format ?? '?' }}
</button>
</div>
<!-- Missing overlay -->
<div v-if="book.status === 'missing'" class="absolute inset-0 bg-black/60 flex items-center justify-center">
<span class="text-[10px] font-semibold uppercase tracking-widest text-destructive-foreground bg-destructive px-2 py-0.5 rounded">
@@ -59,7 +86,7 @@ const coverFailed = ref(false)
</span>
</div>
<!-- Title + author pinned to bottom (shown when no real cover) -->
<!-- Title + author (shown when no real cover) -->
<div v-if="!coverLoaded" class="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/60 to-transparent">
<p class="text-xs font-bold leading-tight line-clamp-3" :style="{ color: coverStyle.color }">
{{ book.title ?? '—' }}
@@ -1,5 +1,11 @@
import { ref, computed, type Ref } from 'vue'
export interface BookFile {
id: number
format: string | null
role: string
}
export interface Book {
id: number
status: string
@@ -7,6 +13,7 @@ export interface Book {
authors: string[]
seriesName: string | null
seriesIndex: number | null
files: BookFile[]
}
interface BooksPage {
+12 -4
View File
@@ -22,7 +22,9 @@ import type { FoliateRenderer } from './composables/useFoliate'
const route = useRoute()
const router = useRouter()
const bookId = Number(route.params.id)
const bookId = Number(route.params.bookId)
const fileId = Number(route.params.fileId)
const fileFormat = (route.query.format as string) || 'epub'
const containerRef = ref<HTMLElement | null>(null)
const showSidebar = ref(false)
@@ -51,7 +53,7 @@ const {
setFlow,
} = readerState
const progress = useReaderProgress(bookId)
const progress = useReaderProgress(bookId, fileId)
const { cfi, chapterTitle, sectionIndex, totalSections, fraction, updateHeadsFeet } = progress
const visibility = useVisibility()
@@ -115,7 +117,7 @@ onMounted(async () => {
onUnmounted(() => document.removeEventListener('fullscreenchange', onFullscreenChange))
await progress.load()
await open(bookId, progress.cfi.value)
await open(fileId, fileFormat, progress.cfi.value)
setChapters(getChapters())
sectionFractions.value = getSectionFractions()
await bookmarks.load(bookId)
@@ -306,7 +308,13 @@ function navigateSearch(cfiTarget: string) {
@search="onSearchQuery"
@clear="onSearchClear"
@navigate="navigateSearch($event)"
@close="() => { onSearchClear(); searchInitialQuery = ''; showSearch = false }"
@close="
() => {
onSearchClear()
searchInitialQuery = ''
showSearch = false
}
"
/>
<ReaderSettingsPanel v-if="showSettings" :state="state" @update="applyUpdate" @close="showSettings = false" />
@@ -48,7 +48,7 @@ export function useFoliate(
await customElements.whenDefined('foliate-view')
}
async function open(bookId: number, cfi?: string | null) {
async function open(fileId: number, format: string, cfi?: string | null) {
const el = container()
if (!el) return
@@ -103,10 +103,12 @@ export function useFoliate(
loading.value = false
})
const res = await fetch(`/api/books/${bookId}/file`)
if (!res.ok) throw new Error(`Failed to fetch book: ${res.status}`)
const mimeType = format === 'pdf' ? 'application/pdf' : format === 'cbz' ? 'application/zip' : 'application/epub+zip'
const ext = format === 'pdf' ? 'pdf' : format === 'cbz' ? 'cbz' : 'epub'
const res = await fetch(`/api/books/files/${fileId}/serve`)
if (!res.ok) throw new Error(`Failed to fetch book file: ${res.status}`)
const blob = await res.blob()
const file = new File([blob], `book-${bookId}.epub`, { type: 'application/epub+zip' })
const file = new File([blob], `book-file-${fileId}.${ext}`, { type: mimeType })
await view.open(file)
if (onApplyStyles) onApplyStyles(view.renderer)
await view.goTo(cfi ?? 0).catch(() => {})
@@ -1,8 +1,9 @@
import { ref } from 'vue'
import type { FoliateRenderer, RelocateDetail } from './useFoliate'
export function useReaderProgress(bookId: number) {
export function useReaderProgress(bookId: number, fileId: number) {
const cfi = ref<string | null>(null)
const pageNumber = ref<number | null>(null)
const percentage = ref(0)
const chapterTitle = ref('')
const sectionIndex = ref(0)
@@ -12,10 +13,11 @@ export function useReaderProgress(bookId: number) {
let saveTimer: ReturnType<typeof setTimeout> | null = null
async function load() {
const res = await fetch(`/api/books/${bookId}/progress`)
const res = await fetch(`/api/books/files/${fileId}/progress`)
if (!res.ok) return
const data = await res.json()
cfi.value = data.cfi ?? null
pageNumber.value = data.pageNumber ?? null
percentage.value = data.percentage ?? 0
}
@@ -32,10 +34,10 @@ export function useReaderProgress(bookId: number) {
}
async function save() {
await fetch(`/api/books/${bookId}/progress`, {
await fetch(`/api/books/files/${fileId}/progress`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cfi: cfi.value, percentage: percentage.value }),
body: JSON.stringify({ cfi: cfi.value, pageNumber: pageNumber.value, percentage: percentage.value }),
})
}
@@ -122,6 +124,7 @@ export function useReaderProgress(bookId: number) {
return {
cfi,
pageNumber,
percentage,
chapterTitle,
sectionIndex,
+1 -1
View File
@@ -10,7 +10,7 @@ const router = createRouter({
component: HomeView,
},
{
path: '/read/:id',
path: '/read/:bookId/:fileId',
name: 'reader',
component: () => import('@/features/reader/ReaderView.vue'),
},
@@ -0,0 +1,11 @@
DROP TABLE "reading_progress";
--> statement-breakpoint
CREATE TABLE "reading_progress" (
"book_file_id" integer PRIMARY KEY NOT NULL,
"percentage" real DEFAULT 0 NOT NULL,
"cfi" varchar(2000),
"page_number" integer,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "reading_progress" ADD CONSTRAINT "reading_progress_book_file_id_book_files_id_fk" FOREIGN KEY ("book_file_id") REFERENCES "public"."book_files"("id") ON DELETE cascade ON UPDATE no action;
@@ -0,0 +1,933 @@
{
"id": "0496ecaa-687d-42db-982e-096c3f3605f7",
"prevId": "302f263f-9118-49fa-bb8e-9d1238b67a76",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.book_files": {
"name": "book_files",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"library_folder_id": {
"name": "library_folder_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"absolute_path": {
"name": "absolute_path",
"type": "varchar(4096)",
"primaryKey": false,
"notNull": true
},
"rel_path": {
"name": "rel_path",
"type": "varchar(4096)",
"primaryKey": false,
"notNull": false
},
"ino": {
"name": "ino",
"type": "bigint",
"primaryKey": false,
"notNull": true
},
"size_bytes": {
"name": "size_bytes",
"type": "bigint",
"primaryKey": false,
"notNull": false
},
"mtime": {
"name": "mtime",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"hash": {
"name": "hash",
"type": "varchar(64)",
"primaryKey": false,
"notNull": false
},
"format": {
"name": "format",
"type": "varchar(20)",
"primaryKey": false,
"notNull": false
},
"role": {
"name": "role",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'primary'"
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"book_files_book_id_books_id_fk": {
"name": "book_files_book_id_books_id_fk",
"tableFrom": "book_files",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"book_files_library_folder_id_library_folders_id_fk": {
"name": "book_files_library_folder_id_library_folders_id_fk",
"tableFrom": "book_files",
"tableTo": "library_folders",
"columnsFrom": [
"library_folder_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.books": {
"name": "books",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"library_id": {
"name": "library_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"library_folder_id": {
"name": "library_folder_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"folder_path": {
"name": "folder_path",
"type": "varchar(4096)",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'present'"
},
"added_at": {
"name": "added_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"books_library_id_libraries_id_fk": {
"name": "books_library_id_libraries_id_fk",
"tableFrom": "books",
"tableTo": "libraries",
"columnsFrom": [
"library_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"books_library_folder_id_library_folders_id_fk": {
"name": "books_library_folder_id_library_folders_id_fk",
"tableFrom": "books",
"tableTo": "library_folders",
"columnsFrom": [
"library_folder_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.libraries": {
"name": "libraries",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"icon": {
"name": "icon",
"type": "varchar(100)",
"primaryKey": false,
"notNull": false
},
"scan_mode": {
"name": "scan_mode",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'auto'"
},
"poll_interval_seconds": {
"name": "poll_interval_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"default": 300
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.library_folders": {
"name": "library_folders",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"library_id": {
"name": "library_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"path": {
"name": "path",
"type": "varchar(4096)",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"library_folders_library_id_libraries_id_fk": {
"name": "library_folders_library_id_libraries_id_fk",
"tableFrom": "library_folders",
"tableTo": "libraries",
"columnsFrom": [
"library_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.authors": {
"name": "authors",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(500)",
"primaryKey": false,
"notNull": true
},
"sort_name": {
"name": "sort_name",
"type": "varchar(500)",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.book_authors": {
"name": "book_authors",
"schema": "",
"columns": {
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"author_id": {
"name": "author_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"display_order": {
"name": "display_order",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
}
},
"indexes": {},
"foreignKeys": {
"book_authors_book_id_books_id_fk": {
"name": "book_authors_book_id_books_id_fk",
"tableFrom": "book_authors",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"book_authors_author_id_authors_id_fk": {
"name": "book_authors_author_id_authors_id_fk",
"tableFrom": "book_authors",
"tableTo": "authors",
"columnsFrom": [
"author_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"book_authors_book_id_author_id_pk": {
"name": "book_authors_book_id_author_id_pk",
"columns": [
"book_id",
"author_id"
]
}
},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.book_metadata": {
"name": "book_metadata",
"schema": "",
"columns": {
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": true,
"notNull": true
},
"title": {
"name": "title",
"type": "varchar(1000)",
"primaryKey": false,
"notNull": false
},
"subtitle": {
"name": "subtitle",
"type": "varchar(1000)",
"primaryKey": false,
"notNull": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false
},
"isbn10": {
"name": "isbn10",
"type": "varchar(10)",
"primaryKey": false,
"notNull": false
},
"isbn13": {
"name": "isbn13",
"type": "varchar(13)",
"primaryKey": false,
"notNull": false
},
"publisher": {
"name": "publisher",
"type": "varchar(500)",
"primaryKey": false,
"notNull": false
},
"published_year": {
"name": "published_year",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"language": {
"name": "language",
"type": "varchar(10)",
"primaryKey": false,
"notNull": false
},
"page_count": {
"name": "page_count",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"series_name": {
"name": "series_name",
"type": "varchar(500)",
"primaryKey": false,
"notNull": false
},
"series_index": {
"name": "series_index",
"type": "real",
"primaryKey": false,
"notNull": false
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"book_metadata_book_id_books_id_fk": {
"name": "book_metadata_book_id_books_id_fk",
"tableFrom": "book_metadata",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.book_tags": {
"name": "book_tags",
"schema": "",
"columns": {
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"tag_id": {
"name": "tag_id",
"type": "integer",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {
"book_tags_book_id_books_id_fk": {
"name": "book_tags_book_id_books_id_fk",
"tableFrom": "book_tags",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"book_tags_tag_id_tags_id_fk": {
"name": "book_tags_tag_id_tags_id_fk",
"tableFrom": "book_tags",
"tableTo": "tags",
"columnsFrom": [
"tag_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"book_tags_book_id_tag_id_pk": {
"name": "book_tags_book_id_tag_id_pk",
"columns": [
"book_id",
"tag_id"
]
}
},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tags": {
"name": "tags",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(200)",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"tags_name_unique": {
"name": "tags_name_unique",
"nullsNotDistinct": false,
"columns": [
"name"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.scan_jobs": {
"name": "scan_jobs",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"library_id": {
"name": "library_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'running'"
},
"triggered_by": {
"name": "triggered_by",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true
},
"added_count": {
"name": "added_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"updated_count": {
"name": "updated_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"missing_count": {
"name": "missing_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false
},
"started_at": {
"name": "started_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"completed_at": {
"name": "completed_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {
"scan_jobs_library_id_libraries_id_fk": {
"name": "scan_jobs_library_id_libraries_id_fk",
"tableFrom": "scan_jobs",
"tableTo": "libraries",
"columnsFrom": [
"library_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.annotations": {
"name": "annotations",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"cfi": {
"name": "cfi",
"type": "varchar(2000)",
"primaryKey": false,
"notNull": true
},
"text": {
"name": "text",
"type": "text",
"primaryKey": false,
"notNull": true
},
"color": {
"name": "color",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'yellow'"
},
"style": {
"name": "style",
"type": "varchar(20)",
"primaryKey": false,
"notNull": true,
"default": "'highlight'"
},
"note": {
"name": "note",
"type": "text",
"primaryKey": false,
"notNull": false
},
"chapter_title": {
"name": "chapter_title",
"type": "varchar(500)",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"annotations_book_id_books_id_fk": {
"name": "annotations_book_id_books_id_fk",
"tableFrom": "annotations",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.bookmarks": {
"name": "bookmarks",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"book_id": {
"name": "book_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"cfi": {
"name": "cfi",
"type": "varchar(2000)",
"primaryKey": false,
"notNull": true
},
"title": {
"name": "title",
"type": "varchar(500)",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"bookmarks_book_id_books_id_fk": {
"name": "bookmarks_book_id_books_id_fk",
"tableFrom": "bookmarks",
"tableTo": "books",
"columnsFrom": [
"book_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.reading_progress": {
"name": "reading_progress",
"schema": "",
"columns": {
"book_file_id": {
"name": "book_file_id",
"type": "integer",
"primaryKey": true,
"notNull": true
},
"percentage": {
"name": "percentage",
"type": "real",
"primaryKey": false,
"notNull": true,
"default": 0
},
"cfi": {
"name": "cfi",
"type": "varchar(2000)",
"primaryKey": false,
"notNull": false
},
"page_number": {
"name": "page_number",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"reading_progress_book_file_id_book_files_id_fk": {
"name": "reading_progress_book_file_id_book_files_id_fk",
"tableFrom": "reading_progress",
"tableTo": "book_files",
"columnsFrom": [
"book_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+10 -3
View File
@@ -5,23 +5,30 @@
{
"idx": 0,
"version": "7",
"when": 1766774395691,
"when": 1766913138285,
"tag": "0000_init_schema",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1766774395691,
"when": 1766913138285,
"tag": "0001_lethal_pixie",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1766774395691,
"when": 1766913138285,
"tag": "0002_powerful_thundra",
"breakpoints": true
},
{
"idx": 3,
"version": "7",
"when": 1766913138285,
"tag": "0003_reading_progress_by_file",
"breakpoints": true
}
]
}
+7 -4
View File
@@ -1,13 +1,16 @@
import { integer, pgTable, real, serial, text, timestamp, varchar } from 'drizzle-orm/pg-core';
import { books } from './books';
import { bookFiles, books } from './books';
export const readingProgress = pgTable('reading_progress', {
bookId: integer('book_id')
bookFileId: integer('book_file_id')
.primaryKey()
.references(() => books.id, { onDelete: 'cascade' }),
cfi: varchar('cfi', { length: 2000 }),
.references(() => bookFiles.id, { onDelete: 'cascade' }),
percentage: real('percentage').notNull().default(0),
// EPUB: CFI string pinpoints exact location
cfi: varchar('cfi', { length: 2000 }),
// PDF / CBX / CBR: zero-based page index
pageNumber: integer('page_number'),
updatedAt: timestamp('updated_at').defaultNow().notNull(),
});
+14 -10
View File
@@ -25,24 +25,28 @@ export class BookController {
reply.send(createReadStream(coverPath));
}
@Get(':id/file')
async getFile(@Param('id', ParseIntPipe) id: number, @Res() reply: FastifyReply) {
const { stream, size, format } = await this.bookService.getFileStream(id);
// Flat file routes — no bookId needed since fileId is globally unique.
// These MUST come before `:id/*` routes to avoid NestJS matching 'files' as :id.
@Get('files/:fileId/serve')
async serveFile(@Param('fileId', ParseIntPipe) fileId: number, @Res() reply: FastifyReply) {
const { stream, size, format } = await this.bookService.getFileStream(fileId);
const mimeType = format === 'pdf' ? 'application/pdf' : format === 'cbz' ? 'application/zip' : 'application/epub+zip';
reply.header('Content-Length', size);
reply.header('Content-Disposition', 'inline');
reply.header('Accept-Ranges', 'bytes');
reply.type(format === 'pdf' ? 'application/pdf' : 'application/epub+zip');
reply.type(mimeType);
reply.send(stream);
}
@Get(':id/progress')
async getProgress(@Param('id', ParseIntPipe) id: number) {
return (await this.bookService.getProgress(id)) ?? { cfi: null, percentage: 0 };
@Get('files/:fileId/progress')
async getFileProgress(@Param('fileId', ParseIntPipe) fileId: number) {
return (await this.bookService.getProgress(fileId)) ?? { cfi: null, pageNumber: null, percentage: 0 };
}
@Post(':id/progress')
async saveProgress(@Param('id', ParseIntPipe) id: number, @Body() dto: SaveProgressDto) {
await this.bookService.saveProgress(id, dto.cfi, dto.percentage);
@Post('files/:fileId/progress')
async saveFileProgress(@Param('fileId', ParseIntPipe) fileId: number, @Body() dto: SaveProgressDto) {
await this.bookService.saveProgress(fileId, dto.cfi, dto.pageNumber, dto.percentage);
}
@Get(':id')
+21 -13
View File
@@ -40,17 +40,25 @@ export class BookRepository {
]);
const bookIds = rows.map((r) => r.id);
const authorRows =
const [authorRows, fileRows] = await Promise.all([
bookIds.length > 0
? await this.db
? this.db
.select({ bookId: bookAuthors.bookId, name: authors.name })
.from(bookAuthors)
.innerJoin(authors, eq(authors.id, bookAuthors.authorId))
.where(inArray(bookAuthors.bookId, bookIds))
.orderBy(bookAuthors.displayOrder)
: [];
: [],
bookIds.length > 0
? this.db
.select({ bookId: bookFiles.bookId, id: bookFiles.id, format: bookFiles.format, role: bookFiles.role })
.from(bookFiles)
.where(inArray(bookFiles.bookId, bookIds))
: [],
]);
return { rows, authorRows, total: Number(total) };
return { rows, authorRows, fileRows, total: Number(total) };
}
async findById(id: number) {
@@ -81,27 +89,27 @@ export class BookRepository {
return { book, authorRows, tagRows, fileRows };
}
async findPrimaryFile(bookId: number) {
async findFileById(fileId: number) {
const [file] = await this.db
.select({ absolutePath: bookFiles.absolutePath, format: bookFiles.format })
.select({ id: bookFiles.id, absolutePath: bookFiles.absolutePath, format: bookFiles.format, bookId: bookFiles.bookId })
.from(bookFiles)
.where(and(eq(bookFiles.bookId, bookId), eq(bookFiles.role, 'primary')))
.where(eq(bookFiles.id, fileId))
.limit(1);
return file ?? null;
}
async findProgress(bookId: number) {
const [row] = await this.db.select().from(readingProgress).where(eq(readingProgress.bookId, bookId)).limit(1);
async findProgress(fileId: number) {
const [row] = await this.db.select().from(readingProgress).where(eq(readingProgress.bookFileId, fileId)).limit(1);
return row ?? null;
}
async upsertProgress(bookId: number, cfi: string | null, percentage: number) {
async upsertProgress(fileId: number, cfi: string | null, pageNumber: number | null, percentage: number) {
await this.db
.insert(readingProgress)
.values({ bookId, cfi, percentage })
.values({ bookFileId: fileId, cfi, pageNumber, percentage })
.onConflictDoUpdate({
target: readingProgress.bookId,
set: { cfi, percentage, updatedAt: sql`now()` },
target: readingProgress.bookFileId,
set: { cfi, pageNumber, percentage, updatedAt: sql`now()` },
});
}
}
+16 -12
View File
@@ -22,7 +22,7 @@ export class BookService {
async getCards(dto: GetBooksDto): Promise<{ items: BookCardDto[]; total: number; page: number; size: number }> {
const { libraryId, page = 0, size = 50, search } = dto;
const { rows, authorRows, total } = await this.bookRepo.findCards(libraryId, { page, size, search });
const { rows, authorRows, fileRows, total } = await this.bookRepo.findCards(libraryId, { page, size, search });
const authorsByBook = new Map<number, string[]>();
for (const row of authorRows) {
@@ -31,6 +31,13 @@ export class BookService {
authorsByBook.set(row.bookId, list);
}
const filesByBook = new Map<number, { id: number; format: string | null; role: string }[]>();
for (const row of fileRows) {
const list = filesByBook.get(row.bookId) ?? [];
list.push({ id: row.id, format: row.format, role: row.role });
filesByBook.set(row.bookId, list);
}
const items: BookCardDto[] = rows.map((row) => ({
id: row.id,
status: row.status,
@@ -38,15 +45,12 @@ export class BookService {
seriesName: row.seriesName ?? null,
seriesIndex: row.seriesIndex ?? null,
authors: authorsByBook.get(row.id) ?? [],
files: filesByBook.get(row.id) ?? [],
}));
return { items, total, page, size };
}
/**
* Returns the absolute path of the stored cover file for a book,
* or null if no cover exists on disk.
*/
async getCoverPath(id: number): Promise<string | null> {
const dir = join(this.booksPath, 'covers', String(id));
try {
@@ -58,19 +62,19 @@ export class BookService {
}
}
async getFileStream(id: number): Promise<{ stream: ReturnType<typeof createReadStream>; size: number; format: string }> {
const file = await this.bookRepo.findPrimaryFile(id);
if (!file) throw new NotFoundException(`No file for book ${id}`);
async getFileStream(fileId: number): Promise<{ stream: ReturnType<typeof createReadStream>; size: number; format: string }> {
const file = await this.bookRepo.findFileById(fileId);
if (!file) throw new NotFoundException(`No file with id ${fileId}`);
const { size } = await stat(file.absolutePath);
return { stream: createReadStream(file.absolutePath), size, format: file.format ?? 'unknown' };
}
async getProgress(id: number) {
return this.bookRepo.findProgress(id);
async getProgress(fileId: number) {
return this.bookRepo.findProgress(fileId);
}
async saveProgress(id: number, cfi: string | null | undefined, percentage: number) {
await this.bookRepo.upsertProgress(id, cfi ?? null, percentage);
async saveProgress(fileId: number, cfi: string | null | undefined, pageNumber: number | null | undefined, percentage: number) {
await this.bookRepo.upsertProgress(fileId, cfi ?? null, pageNumber ?? null, percentage);
}
async getDetail(id: number): Promise<BookDetailDto> {
@@ -1,3 +1,9 @@
export class BookFileRefDto {
id: number;
format: string | null;
role: string;
}
export class BookCardDto {
id: number;
status: string;
@@ -5,4 +11,5 @@ export class BookCardDto {
authors: string[];
seriesName: string | null;
seriesIndex: number | null;
files: BookFileRefDto[];
}
@@ -1,9 +1,13 @@
import { IsNumber, IsOptional, IsString, Max, Min } from 'class-validator';
import { IsInt, IsNumber, IsOptional, IsString, Max, Min } from 'class-validator';
export class SaveProgressDto {
@IsOptional()
@IsString()
cfi?: string;
cfi?: string | null;
@IsOptional()
@IsInt()
pageNumber?: number | null;
@IsNumber()
@Min(0)