From 2d75e0937b81f348cf4807c19ebc9bdf57e43e65 Mon Sep 17 00:00:00 2001 From: Huang Xin Date: Wed, 4 Nov 2026 20:25:49 +0800 Subject: [PATCH] fix(sync): give HTML chapter files their own sync identity (#7321) * fix(sync): give HTML chapter files their own sync identity Web-novel downloaders such as the legado and moon KOReader plugins save each chapter as its own HTML file under the book's title and author. The metadata hash, which syncs reading progress across devices, then matched every chapter of the book, so opening a new chapter could pull the previous chapter's position. #7231 does not cover this: a chapter opened for the first time has no save of its own, so a sibling's newer position still wins. HTML files (.html, .htm, .xhtml, .xhtm, .mhtml, .mht) now salt the meta hash with the base filename, as PDFs already do (#5411), in both the KOReader plugin and the app. The app keeps the salted hash from import and never recomputes it on a metadata refresh. Files already opened keep their cached hash; chapters opened after the update get their own. Verified: - Tests that fail without the fix: - spec/syncconfig_spec.lua "gives per-chapter HTML files of one book distinct hashes": expected 'Sword Coming|Fenghuo Xizhuhou||0001', got the hash source without the filename. - import-metahash.test.ts "imports HTML chapters with identical metadata as separate books" (expected the salted hash, got the shared one) and "refreshBookMetadata preserves the salted metaHash for HTML" (expected 'salted-import-hash', got the recomputed hash). - All koplugin busted specs pass (513), luajit syntax check clean; the related app suites pass (34 files); pnpm lint and format:check clean. - On a Kindle with KOReader, two HTML files sharing a title got the same meta_hash_v1 under the old plugin and distinct ones under the fix, each equal to md5 of "|||<basename>". - Not run: the cross-device sync round trip, because sync from that Kindle currently fails for an unrelated reason. Closes #7313 Reported by zzzh3ng on GitHub Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(sync): salt the HTML metaHash when an existing row has none An existing HTML row with no metaHash (imported before metaHashes existed) kept undefined on re-import instead of getting a salted hash. Keep the stored hash only when there is one. Verified: the new import-metahash test "salts the metaHash when re-importing an HTML book that has none" fails without this change (expected undefined to be the salted hash) and passes with it; related suites pass (35 files, 543 tests); pnpm lint and format:check clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .../services/import-metahash.test.ts | 44 +++++++++++++++++++ apps/readest-app/src/services/bookService.ts | 28 ++++++++---- apps/readest.koplugin/readest_syncconfig.lua | 11 +++-- .../readest.koplugin/spec/syncconfig_spec.lua | 17 ++++++- 4 files changed, 88 insertions(+), 12 deletions(-) diff --git a/apps/readest-app/src/__tests__/services/import-metahash.test.ts b/apps/readest-app/src/__tests__/services/import-metahash.test.ts index fdb568108..4537f9a09 100644 --- a/apps/readest-app/src/__tests__/services/import-metahash.test.ts +++ b/apps/readest-app/src/__tests__/services/import-metahash.test.ts @@ -1632,6 +1632,50 @@ describe('importBook PDF filename-aware dedup', () => { expect(book).toMatchObject({ originalFilename: 'manual.pdf (1)', title: 'manual' }); }); + // Issue #7313: web-novel downloaders save each chapter as its own HTML file + // carrying the book's title and author, so metadata alone merges chapters. + it('imports HTML chapters with identical metadata as separate books', async () => { + const books: Book[] = []; + for (const name of ['0001.html', '0002.htm']) { + mockPartialMD5.mockResolvedValue(`html-${name}`); + mockOpen.mockResolvedValue({ + book: { metadata: { ...PDF_METADATA }, getCover: vi.fn().mockResolvedValue(null) }, + format: 'HTML', + }); + const book = await service.importBook(new File(['chapter'], name), books); + expect(book!.metaHash).toBe(getMetadataHash(PDF_METADATA, name.replace(/\..*$/, ''))); + } + expect(books.filter((b) => !b.deletedAt)).toHaveLength(2); + }); + + it('salts the metaHash when re-importing an HTML book that has none', async () => { + const books: Book[] = [makeBook({ hash: 'html-old', format: 'HTML' })]; + mockPartialMD5.mockResolvedValue('html-old'); + mockOpen.mockResolvedValue({ + book: { metadata: { ...PDF_METADATA }, getCover: vi.fn().mockResolvedValue(null) }, + format: 'HTML', + }); + + const book = await service.importBook(new File(['chapter'], '0003.html'), books); + + expect(book!.metaHash).toBe(getMetadataHash(PDF_METADATA, '0003')); + }); + + it('refreshBookMetadata preserves the salted metaHash for HTML', async () => { + const book = makeBook({ hash: 'html-hash', format: 'HTML', metaHash: 'salted-import-hash' }); + const fs = service.getFs(); + fs.exists.mockResolvedValue(true); + fs.openFile.mockResolvedValue(new File(['html'], 'Test Book.html')); + mockOpen.mockResolvedValue({ + book: { metadata: { ...PDF_METADATA }, getCover: vi.fn().mockResolvedValue(null) }, + format: 'HTML', + }); + + await refreshBookMetadata(fs as unknown as Parameters<typeof refreshBookMetadata>[0], book); + + expect(book.metaHash).toBe('salted-import-hash'); + }); + it('refreshBookMetadata preserves the salted metaHash for PDFs', async () => { // The original filename is lost after import (files are stored under the // metadata title), so re-parsing the file cannot reproduce the salt and diff --git a/apps/readest-app/src/services/bookService.ts b/apps/readest-app/src/services/bookService.ts index 5075ce8fb..c63d6961e 100644 --- a/apps/readest-app/src/services/bookService.ts +++ b/apps/readest-app/src/services/bookService.ts @@ -52,18 +52,30 @@ import { type BookFileContentSource, } from './bookContent'; +/** + * Formats whose metaHash is salted with the import filename, because their + * metadata often doesn't tell files apart: PDF boilerplate like "PowerPoint + * Presentation" (issue #5411), and HTML chapters a web-novel downloader saves + * one per file under the book's title and author (issue #7313). A library row + * no longer knows its import filename, so the salted hash is never recomputed. + * Keep in sync with FILENAME_SALTED in readest.koplugin/readest_syncconfig.lua. + */ +function isFilenameSalted(format: Book['format']) { + return format === 'PDF' || format === 'HTML'; +} + /** * Whether a bare UUID identifier of this format can be dropped from the * import-time dedup key (issue #5959). * - * PDFs are left out: #5411 deliberately scopes their identity to the filename, - * and a library row no longer knows the filename it was imported from. + * Filename-salted formats are left out: their identity is deliberately scoped + * to the filename. * FB2/FBZ are left out: their document-info id is a GUID minted once for the * document and kept across revisions, so it is what tells two FB2s of the * same title apart (issue #7150). */ function hasVolatileIdentifiers(format: Book['format']) { - return format !== 'PDF' && format !== 'FB2' && format !== 'FBZ'; + return !isFilenameSalted(format) && format !== 'FB2' && format !== 'FBZ'; } /** @@ -732,11 +744,11 @@ export async function importBook( ? lookupIndex.byHash.get(hash) : books.find((b) => b.hash === hash); const metaHash = - format === 'PDF' && existingBook + isFilenameSalted(format) && existingBook?.metaHash ? existingBook.metaHash : getMetadataHash( loadedBook.metadata, - format === 'PDF' ? getBaseFilename(filename) : undefined, + isFilenameSalted(format) ? getBaseFilename(filename) : undefined, ); const stableHash = hasVolatileIdentifiers(format) ? getStableMetadataHash(loadedBook.metadata) @@ -1324,9 +1336,9 @@ export async function refreshBookMetadata(fs: FileSystem, book: Book): Promise<b if (!bookDoc) return false; book.metadata = bookDoc.metadata; - // PDF metaHash is salted with the original import filename (issue #5411), - // which is lost after import — keep the value stamped at import time. - if (book.format !== 'PDF' || !book.metaHash) { + // A filename-salted metaHash can't be reproduced after import (the + // original filename is lost), so keep the value stamped at import time. + if (!isFilenameSalted(book.format) || !book.metaHash) { book.metaHash = getMetadataHash(bookDoc.metadata); } const primaryLanguage = getPrimaryLanguage(bookDoc.metadata.language); diff --git a/apps/readest.koplugin/readest_syncconfig.lua b/apps/readest.koplugin/readest_syncconfig.lua index 36c610637..beb691d2b 100644 --- a/apps/readest.koplugin/readest_syncconfig.lua +++ b/apps/readest.koplugin/readest_syncconfig.lua @@ -27,6 +27,10 @@ local function normalizeIdentifier(identifier) return identifier end +-- Formats whose metadata often doesn't tell files apart, so the hash is +-- salted with the base filename: PDF (#5411) and HTML (#7313). +local FILENAME_SALTED = { pdf = true, html = true, htm = true, xhtml = true, xhtm = true, mhtml = true, mht = true } + local function normalizeAuthor(author) author = author:gsub("^%s*(.-)%s*$", "%1") return author @@ -88,9 +92,10 @@ function SyncConfig:computeMetadataHashInfo(doc_props, doc_path) local hash_source = title .. "|" .. table.concat(authors_list, ",") .. "|" .. table.concat(identifiers_list, ",") -- PDF metadata is often generic boilerplate (every PowerPoint export is - -- titled "PowerPoint Presentation"), so Readest salts PDF hashes with the - -- import filename (issue #5411). Salt with ours the same way. - if suffix and suffix:lower() == "pdf" then + -- titled "PowerPoint Presentation", issue #5411), and web-novel plugins + -- save each chapter as an HTML file with the book's title and author + -- (issue #7313). Readest salts these with the import filename; so do we. + if suffix and FILENAME_SALTED[suffix:lower()] then hash_source = hash_source .. "|" .. basename end return { diff --git a/apps/readest.koplugin/spec/syncconfig_spec.lua b/apps/readest.koplugin/spec/syncconfig_spec.lua index d0d940003..5a83af137 100644 --- a/apps/readest.koplugin/spec/syncconfig_spec.lua +++ b/apps/readest.koplugin/spec/syncconfig_spec.lua @@ -3,7 +3,7 @@ -- that must stay CONSISTENT with Readest's getMetadataHashInfo in -- apps/readest-app/src/utils/book.ts. The hash-source fixtures here mirror -- src/__tests__/utils/metadata-hash-info.test.ts: same inputs must produce --- the same "title|authors|identifiers[|pdf-filename]" string on both sides, +-- the same "title|authors|identifiers[|pdf-or-html-filename]" string on both sides, -- because md5 of that string is the fleet-wide book identity. -- -- Expected hashes are computed through the same (stubbed) ffi/sha2 module the @@ -84,6 +84,21 @@ describe("SyncConfig:getMetadataHashInfo", function() assert.are_not.equal(a.meta_hash, b.meta_hash) end) + it("gives per-chapter HTML files of one book distinct hashes (issue #7313)", function() + -- legado.koplugin caches each chapter as its own .html file and + -- reports the book's title and author for every one of them. + local props = { title = "Sword Coming", authors = "Fenghuo Xizhuhou" } + local hashes = {} + for _, name in ipairs({ "0001.html", "0002.htm", "0003.xhtml", "0004.xhtm", "0005.mhtml", "0006.mht" }) do + local info = SyncConfig:getMetadataHashInfo(fakeUI({ + doc_props = props, doc_path = "/legado/cache/" .. name, + })) + assert.are.equal("Sword Coming|Fenghuo Xizhuhou||" .. name:match("^(.*)%."), info.hash_source) + assert.is_nil(hashes[info.meta_hash]) + hashes[info.meta_hash] = true + end + end) + it("keeps the salt when the title already fell back to the filename", function() -- Readest hashes "report||" + "|report" for a metadata-less PDF: the -- title fallback happens before hashing, then the salt is appended