diff --git a/apps/readest-app/src/__tests__/pages/api/sync-original-filename.test.ts b/apps/readest-app/src/__tests__/pages/api/sync-original-filename.test.ts new file mode 100644 index 000000000..8ea74a3a3 --- /dev/null +++ b/apps/readest-app/src/__tests__/pages/api/sync-original-filename.test.ts @@ -0,0 +1,87 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { NextRequest } from 'next/server'; +import type { Book } from '@/types/book'; +import type { DBBook } from '@/types/records'; + +const db = vi.hoisted(() => ({ + book: null as DBBook | null, + writes: [] as DBBook[], +})); +vi.mock('@/utils/access', () => ({ + validateUserAndToken: async () => ({ user: { id: 'test-user' }, token: 'test-token' }), +})); +vi.mock('@/utils/supabase', () => ({ + createSupabaseClient: () => ({ + from: () => ({ + select: () => ({ or: async () => ({ data: db.book ? [db.book] : [], error: null }) }), + upsert: (rows: DBBook[]) => { + db.writes.push(...rows); + db.book = rows[0] ?? null; + return { select: async () => ({ data: rows, error: null }) }; + }, + }), + }), +})); + +import { POST } from '@/pages/api/sync'; + +const push = (book: Partial) => + POST( + new Request('https://example.com/api/sync', { + method: 'POST', + headers: { authorization: 'Bearer test-token', 'content-type': 'application/json' }, + body: JSON.stringify({ + books: [{ hash: 'h', format: 'EPUB', title: 'T', author: 'A', updatedAt: 1, ...book }], + }), + }) as unknown as NextRequest, + ); + +beforeEach(() => { + db.book = { + user_id: 'test-user', + book_hash: 'h', + format: 'EPUB', + title: 'T', + author: 'A', + original_filename: null, + updated_at: new Date(2).toISOString(), + }; + db.writes = []; +}); + +describe('original filename cloud merge', () => { + it.each([ + 1, 2, 3, + ])('fills a missing filename independently of the row clock (%s)', async (updatedAt) => { + const response = await push({ originalFilename: 'Original.epub', updatedAt }); + + expect(response.status).toBe(200); + expect(db.writes).toHaveLength(1); + expect(db.book?.original_filename).toBe('Original.epub'); + expect(db.book?.updated_at).toBe(new Date(Math.max(2, updatedAt)).toISOString()); + expect((await response.json()).books[0].original_filename).toBe('Original.epub'); + + await push({ originalFilename: 'Original.epub', updatedAt }); + expect(db.writes).toHaveLength(1); + }); + + it.each([ + undefined, + 'Peer copy.epub', + ])('preserves the known server filename when a newer client sends %s', async (originalFilename) => { + db.book!.original_filename = 'Original.epub'; + const response = await push({ originalFilename, updatedAt: 3 }); + + expect(response.status).toBe(200); + expect(db.writes).toHaveLength(1); + expect(db.book?.original_filename).toBe('Original.epub'); + expect(db.book?.updated_at).toBe(new Date(3).toISOString()); + }); + + it('does not rewrite a legacy row when neither peer knows the filename', async () => { + const response = await push({}); + + expect(response.status).toBe(200); + expect(db.writes).toHaveLength(0); + }); +}); diff --git a/apps/readest-app/src/__tests__/services/import-docx-conversion.test.ts b/apps/readest-app/src/__tests__/services/import-docx-conversion.test.ts index 4d1bed1c7..037a9721d 100644 --- a/apps/readest-app/src/__tests__/services/import-docx-conversion.test.ts +++ b/apps/readest-app/src/__tests__/services/import-docx-conversion.test.ts @@ -154,7 +154,7 @@ describe('importBook DOCX/RTF conversion', () => { const result = await service.importBook('/library/report.docx', books); - expect(result).not.toBeNull(); + expect(result).toMatchObject({ originalFilename: 'report.docx', format: 'EPUB' }); expect(mockConvertDocx).toHaveBeenCalledTimes(1); expect(mockConvertDocx).toHaveBeenCalledWith({ kind: 'docx', 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 a172dcc98..fdb568108 100644 --- a/apps/readest-app/src/__tests__/services/import-metahash.test.ts +++ b/apps/readest-app/src/__tests__/services/import-metahash.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Book } from '@/types/book'; import { getMetadataHash } from '@/utils/book'; +import { transformBookFromDB, transformBookToDB } from '@/utils/transform'; const mockOpen = vi.hoisted(() => vi.fn()); const mockPartialMD5 = vi.hoisted(() => vi.fn()); @@ -32,6 +33,7 @@ vi.mock('@/libs/storage', () => ({ })); import { BaseAppService } from '@/services/appService'; +import { WebAppService } from '@/services/webAppService'; import { buildBookLookupIndex, refreshBookMetadata } from '@/services/bookService'; // Concrete test subclass of BaseAppService with mocked fs @@ -1247,6 +1249,14 @@ describe('importBook PDF filename-aware dedup', () => { expect(book2).not.toBe(book1); expect(books.filter((b) => !b.deletedAt)).toHaveLength(2); + expect(book1).toMatchObject({ + title: 'lecture-01', + originalFilename: 'lecture-01.pdf', + sourceTitle: PDF_METADATA.title, + metadata: PDF_METADATA, + metaHash: getMetadataHash(PDF_METADATA, 'lecture-01'), + }); + expect(book2).toMatchObject({ title: 'lecture-02', originalFilename: 'lecture-02.pdf' }); }); it('still dedupes a PDF re-imported with the same filename and metadata', async () => { @@ -1302,7 +1312,11 @@ describe('importBook PDF filename-aware dedup', () => { const imported = await service.importBook(changedFile, [existingBook]); expect(imported).toBe(existingBook); - expect(existingBook.title).toBe(changedMetadata.title); + expect(existingBook).toMatchObject({ + title: originalMetadata.title, + metaHash: getMetadataHash(originalMetadata, 'canon-r7-custom-buttons'), + }); + expect(existingBook.originalFilename).toBeUndefined(); expect(existingBook.sourceTitle).toBe(originalMetadata.title); expect(existingBook.author).toBe(changedMetadata.author); expect(existingBook.metadata).toEqual(changedMetadata); @@ -1310,6 +1324,314 @@ describe('importBook PDF filename-aware dedup', () => { expect(service.getFs().openFile).not.toHaveBeenCalled(); }); + it('preserves an edited PDF title and both hashes on reimport', async () => { + const books: Book[] = []; + mockPartialMD5.mockResolvedValue('pdf-hash'); + setupMockPdfDoc(); + const book = (await service.importBook(new File(['pdf'], 'Original.pdf'), books))!; + const originalMetaHash = book.metaHash; + book.title = 'My edited title'; + + setupMockPdfDoc({ ...PDF_METADATA, author: 'Updated author' }); + const reimported = await service.importBook(new File(['pdf'], 'Renamed.pdf'), books); + + expect(reimported).toBe(book); + expect(reimported).toMatchObject({ + title: 'My edited title', + hash: 'pdf-hash', + metaHash: originalMetaHash, + originalFilename: 'Original.pdf', + }); + }); + + it('preserves an existing PDF with no original filename on external reimport', async () => { + const legacy = makeBook({ + hash: 'legacy-pdf', + format: 'PDF', + title: 'Existing title', + metaHash: 'existing-meta-hash', + sourceTitle: PDF_METADATA.title, + }); + mockPartialMD5.mockResolvedValue(legacy.hash); + setupMockPdfDoc(); + const reimported = await service.importBook(new File(['pdf'], 'New name.pdf'), [legacy]); + expect(reimported).toMatchObject({ + title: 'Existing title', + hash: 'legacy-pdf', + metaHash: 'existing-meta-hash', + }); + expect(reimported!.originalFilename).toBeUndefined(); + }); + + it('keeps the original filename and PDF title when re-importing the managed copy', async () => { + mockPartialMD5.mockResolvedValue('pdf-hash-1'); + setupMockPdfDoc(); + const books: Book[] = []; + const book = await service.importBook(new File(['pdf'], 'Device_Manual_V2.1.PDF'), books); + + service.getFs().openFile.mockResolvedValue(new File(['pdf'], 'PowerPoint Presentation.pdf')); + setupMockPdfDoc(); + const reimported = await service.importBook( + '/library/Books/pdf-hash-1/PowerPoint Presentation.pdf', + books, + ); + + expect(reimported).toBe(book); + expect(reimported).toMatchObject({ + originalFilename: 'Device_Manual_V2.1.PDF', + title: 'Device_Manual_V2.1', + sourceTitle: PDF_METADATA.title, + }); + }); + + it.each([ + 'windows', + 'macos', + 'ios', + 'linux', + ] as const)('preserves synced managed-copy identity using %s path comparison', async (osPlatform) => { + mockPartialMD5.mockResolvedValue('pdf-hash-1'); + setupMockPdfDoc(); + const imported = await service.importBook(new File(['pdf'], 'Device_Manual_V2.1.PDF'), []); + const dbBook = transformBookToDB(imported!, 'test-user'); + const synced = transformBookFromDB({ ...dbBook, original_filename: undefined }); + expect(synced.originalFilename).toBeUndefined(); + service.getFs().getPrefix.mockResolvedValue('/library/Books'); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], 'PowerPoint Presentation.pdf')); + setupMockPdfDoc(); + service.osPlatform = osPlatform; + + const reimported = await service.importBook( + osPlatform === 'linux' + ? '/library/Books/pdf-hash-1/PowerPoint Presentation.pdf' + : '/LIBRARY/BOOKS/pdf-hash-1/POWERPOINT PRESENTATION.PDF', + [synced], + ); + + expect(reimported).toBe(synced); + expect(reimported).toMatchObject({ + title: 'Device_Manual_V2.1', + metaHash: imported!.metaHash, + sourceTitle: PDF_METADATA.title, + }); + expect(reimported!.originalFilename).toBeUndefined(); + }); + + it.each([ + ['EPUB', 'novel.epub'], + ['MOBI', 'novel.mobi'], + ['CBZ', 'comic.cbz'], + ['FB2', 'novel.fb2'], + ['MD', 'notes.md'], + ['HTML', 'article.html'], + ] as const)('saves the original basename for %s without replacing its metadata title', async (format, name) => { + mockPartialMD5.mockResolvedValue('book-hash'); + mockOpen.mockResolvedValue({ + format, + book: { metadata: { ...TEST_METADATA }, getCover: vi.fn().mockResolvedValue(null) }, + }); + + const book = await service.importBook(new File(['book'], name), []); + + expect(book).toMatchObject({ originalFilename: name, title: TEST_METADATA.title }); + }); + + it.each([ + ['/home/reader/manuals/安全 Manual.v2.pdf', '安全 Manual.v2.pdf'], + ['C:\\Users\\reader\\manuals\\Device_Manual.pdf', 'Device_Manual.pdf'], + ])('saves only the basename when importing %s', async (path, name) => { + mockPartialMD5.mockResolvedValue('pdf-hash'); + setupMockPdfDoc(); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], name)); + + const book = await service.importBook(path, []); + + expect(book).toMatchObject({ originalFilename: name, title: name.replace(/\.pdf$/, '') }); + }); + + it.each([ + 'file', + 'path', + ] as const)('keeps PDFs with question marks distinct when importing a %s', async (source) => { + const books: Book[] = []; + for (const revision of [1, 2]) { + const name = `manual?rev${revision}.pdf`; + mockPartialMD5.mockResolvedValue(`pdf-revision-${revision}`); + setupMockPdfDoc(); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], name)); + const book = await service.importBook( + source === 'file' ? new File([`revision ${revision}`], name) : `/library/${name}`, + books, + ); + expect(book).toMatchObject({ + originalFilename: name, + title: `manual?rev${revision}`, + metaHash: getMetadataHash(PDF_METADATA, `manual?rev${revision}`), + }); + } + expect(books.filter((book) => !book.deletedAt)).toHaveLength(2); + }); + + it.each([ + 'file', + 'path', + ] as const)('preserves literal POSIX backslashes when importing a %s', async (source) => { + for (const edition of ['first', 'second']) { + const name = `${edition}\\chapter.pdf`; + mockPartialMD5.mockResolvedValue(`pdf-${edition}`); + setupMockPdfDoc(); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], name)); + const book = await service.importBook( + source === 'file' ? new File([edition], name) : `/library/${name}`, + [], + ); + expect(book).toMatchObject({ + originalFilename: name, + title: `${edition}\\chapter`, + metaHash: getMetadataHash(PDF_METADATA, 'chapter'), + }); + } + }); + + it.each([ + ['https://example.com/manual.pdf?token=abc.def', undefined, 'manual.pdf'], + ['https://example.com/manual.pdf#page=2', undefined, 'manual.pdf'], + ['https://example.com/manual.pdf?token=abc.def#page=2', undefined, 'manual.pdf'], + ['https://example.com/manual.pdf#page=2', 'resolved?edition#1.pdf', 'resolved?edition#1.pdf'], + ['https://example.com/C%2B%2B.pdf', undefined, 'C++.pdf'], + ['https://example.com/manual.pdf?type=application/pdf', undefined, 'manual.pdf'], + ['https://example.com/manual.pdf?token=%FF', undefined, 'manual.pdf'], + ['https://example.com/manual%FF.pdf', undefined, 'manual%FF.pdf'], + ['https://example.com/one%5Cpart.pdf', undefined, 'one\\part.pdf'], + ['https://example.com/two%5Cpart.pdf', undefined, 'two\\part.pdf'], + ])('uses a clean URL fallback for %s while preserving resolved filename %s', async (url, resolvedFilename, name) => { + mockPartialMD5.mockResolvedValue('pdf-hash'); + setupMockPdfDoc(); + const web = new WebAppService(); + const fetcher = vi.fn().mockResolvedValue( + new Response(null, { + headers: { 'content-length': '3', 'content-type': 'application/pdf' }, + }), + ); + const file = await web.fs.openFile(url, 'None', resolvedFilename, fetcher); + service.getFs().openFile.mockResolvedValue(file); + + const book = await service.importBook(url, []); + const title = name.slice(0, -4); + expect(book).toMatchObject({ + originalFilename: name, + title, + metaHash: getMetadataHash(PDF_METADATA, title.replace(/\\/g, '/').split('/').pop()), + }); + }); + + it('keeps decoded URL slashes in the displayed import filename', async () => { + const web = new WebAppService(); + const fetcher = vi.fn().mockResolvedValue( + new Response(null, { + headers: { 'content-length': '3', 'content-type': 'application/pdf' }, + }), + ); + for (const prefix of ['one', 'two']) { + const url = `https://example.com/${prefix}%2Fpart.pdf`; + const file = await web.fs.openFile(url, 'None', undefined, fetcher); + service.getFs().openFile.mockResolvedValue(file); + mockPartialMD5.mockResolvedValue(`pdf-${prefix}`); + setupMockPdfDoc(); + + const book = await service.importBook(url, []); + + expect(book).toMatchObject({ + originalFilename: `${prefix}/part.pdf`, + title: `${prefix}/part`, + metaHash: getMetadataHash(PDF_METADATA, 'part'), + }); + } + }); + + it('uses the existing metadata hash calculation for an extensionless PDF', async () => { + mockPartialMD5.mockResolvedValue('pdf-download'); + setupMockPdfDoc(); + const book = await service.importBook(new File(['pdf'], 'download'), []); + expect(book).toMatchObject({ + hash: 'pdf-download', + title: 'download', + originalFilename: 'download', + metaHash: getMetadataHash(PDF_METADATA, 'download'), + }); + }); + + it('keeps a legacy PDF metadata hash and its batch index unchanged', async () => { + const legacyHash = getMetadataHash(PDF_METADATA, 'download'); + const legacy: Book = { + hash: 'legacy-pdf', + format: 'PDF', + title: 'download', + sourceTitle: PDF_METADATA.title, + author: PDF_METADATA.author, + metadata: PDF_METADATA, + metaHash: legacyHash, + createdAt: 1, + updatedAt: 1, + }; + const books = [legacy]; + const lookupIndex = buildBookLookupIndex(books); + mockPartialMD5.mockResolvedValue('legacy-pdf'); + setupMockPdfDoc(); + await service.importBook(new File(['pdf'], 'download'), books, { lookupIndex }); + + expect(legacy.metaHash).toBe(legacyHash); + expect(lookupIndex.byMetaKey.get(`${legacyHash}:PDF`)).toEqual([legacy]); + expect(books.filter((book) => !book.deletedAt)).toHaveLength(1); + expect(legacy.hash).toBe('legacy-pdf'); + expect(service.getFs().removeDir).not.toHaveBeenCalled(); + }); + + it('keeps PDF title and hashes when its managed filename is sanitized', async () => { + const books: Book[] = []; + mockPartialMD5.mockResolvedValue('untitled-download'); + setupMockPdfDoc({ ...PDF_METADATA, title: '' }); + const book = await service.importBook(new File(['pdf'], 'download?rev1'), books); + const originalMetaHash = book!.metaHash; + const originalTitle = book!.title; + + setupMockPdfDoc({ ...PDF_METADATA, title: '' }); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], 'download_rev1.pdf')); + const reimported = await service.importBook( + '/library/Books/untitled-download/download_rev1.pdf', + books, + ); + expect(reimported!.title).toEqual(originalTitle); + expect(reimported!.metaHash).toBe(originalMetaHash); + expect(reimported!.originalFilename).toBe('download?rev1'); + }); + + it('saves the resolved Android provider name instead of the opaque content URI', async () => { + mockPartialMD5.mockResolvedValue('pdf-hash'); + setupMockPdfDoc(); + service.getFs().openFile.mockResolvedValue(new File(['pdf'], 'Original Manual.pdf')); + + const book = await service.importBook( + 'content://com.android.providers.downloads.documents/document/7421', + [], + ); + + expect(book).toMatchObject({ + originalFilename: 'Original Manual.pdf', + title: 'Original Manual', + metaHash: getMetadataHash(PDF_METADATA, 'Original Manual'), + }); + }); + + it('preserves the unmodified basename before removing a download duplicate marker', async () => { + mockPartialMD5.mockResolvedValue('pdf-hash'); + setupMockPdfDoc(); + + const book = await service.importBook(new File(['pdf'], 'manual.pdf (1)'), []); + + expect(book).toMatchObject({ originalFilename: 'manual.pdf (1)', title: 'manual' }); + }); + 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/__tests__/services/native-app-service-share.test.ts b/apps/readest-app/src/__tests__/services/native-app-service-share.test.ts index c53cc3576..273d6b642 100644 --- a/apps/readest-app/src/__tests__/services/native-app-service-share.test.ts +++ b/apps/readest-app/src/__tests__/services/native-app-service-share.test.ts @@ -8,6 +8,7 @@ const saveDialogMock = vi.fn().mockResolvedValue('/tmp/exported.md'); const shareFileMock = vi.fn().mockResolvedValue(undefined); const copyURIToPathMock = vi.fn().mockResolvedValue({ success: true }); const removeMock = vi.fn().mockResolvedValue(undefined); +const basenameMock = vi.fn((p: string) => Promise.resolve(p.split('/').pop() ?? p)); vi.mock('@tauri-apps/plugin-os', () => ({ type: () => osTypeMock(), @@ -40,7 +41,7 @@ vi.mock('@tauri-apps/plugin-dialog', () => ({ vi.mock('@tauri-apps/api/path', () => ({ join: (...parts: string[]) => Promise.resolve(parts.join('/')), - basename: (p: string) => Promise.resolve(p.split('/').pop() ?? p), + basename: (p: string) => basenameMock(p), appDataDir: () => Promise.resolve('/tmp/app-data'), appConfigDir: () => Promise.resolve('/tmp/app-config'), appCacheDir: () => Promise.resolve('/tmp/app-cache'), @@ -60,11 +61,25 @@ vi.mock('@/utils/bridge', () => ({ vi.mock('@/utils/file', () => ({ NativeFile: class { + constructor( + public path: string, + public name: string, + ) {} + + async open() { + return this; + } + }, + RemoteFile: class { + constructor( + public url: string, + public name: string, + ) {} + async open() { return this; } }, - RemoteFile: class {}, })); vi.mock('@/utils/files', () => ({ @@ -95,6 +110,49 @@ describe('NativeAppService.saveFile share gating', () => { removeMock.mockClear(); }); + test.each([ + 'content://com.android.externalstorage.documents/document/primary%3Aopaque-id', + 'content://com.android.providers.downloads.documents/document/7421', + ])('resolves the provider display name with basename for %s', async (uri) => { + const service = await loadServiceWithOS('android'); + basenameMock.mockResolvedValueOnce('Original Manual.pdf'); + + const file = await service.openFile(uri, 'None'); + + expect(basenameMock).toHaveBeenCalledWith(uri); + expect(file.name).toBe('Original Manual.pdf'); + }); + + test.each([ + ['https://example.com/manual.pdf#zoom=1.25', undefined, 'manual.pdf'], + ['https://example.com/C%2B%2B.pdf?type=application/pdf', undefined, 'C++.pdf'], + ['https://example.com/one%5Cpart.pdf', undefined, 'one\\part.pdf'], + ['https://example.com/manual%FF.pdf', undefined, 'manual%FF.pdf'], + ['https://example.com/manual.pdf#page=2', 'Original%20Name.pdf', 'Original%20Name.pdf'], + ])('resolves native URL fallback names for %s with override %s', async (url, name, expected) => { + const service = await loadServiceWithOS('android'); + + const file = await service['fs'].openFile(url, 'None', name); + + expect(file.name).toBe(expected); + }); + + test.each([ + ['linux', '/books/first\\chapter.pdf', undefined, 'first\\chapter.pdf'], + ['linux', '/books/manual?rev1.pdf', undefined, 'manual?rev1.pdf'], + ['linux', '/books/Report%20Final.pdf', undefined, 'Report%20Final.pdf'], + ['windows', 'C:\\books\\Device_Manual.pdf', undefined, 'Device_Manual.pdf'], + ['windows', 'chapters\\manual.pdf', undefined, 'manual.pdf'], + ['windows', '\\chapters\\manual.pdf', undefined, 'manual.pdf'], + ['linux', 'chapters\\manual.pdf', undefined, 'chapters\\manual.pdf'], + ['windows', '\\\\server\\books\\Device_Manual.pdf', undefined, 'Device_Manual.pdf'], + ['macos', '/books/book.pdf', 'Original%20Name.pdf', 'Original%20Name.pdf'], + ] as const)('resolves local %s names for %s', async (os, path, name, expected) => { + const service = await loadServiceWithOS(os); + const file = await service['fs'].openFile(path, 'None', name); + expect(file.name).toBe(expected); + }); + test('uses a unique cache path for same-named content-provider files', async () => { const service = await loadServiceWithOS('android'); diff --git a/apps/readest-app/src/__tests__/services/sync/file/merge.test.ts b/apps/readest-app/src/__tests__/services/sync/file/merge.test.ts index 8110481b7..7293b0951 100644 --- a/apps/readest-app/src/__tests__/services/sync/file/merge.test.ts +++ b/apps/readest-app/src/__tests__/services/sync/file/merge.test.ts @@ -5,6 +5,8 @@ import { mergeBookMetadata, isRemoteBookMetadataNewer, shouldApplyRemoteBookMetadata, + isRemoteBookMissingLocally, + resolvePublishedBook, } from '@/services/sync/file/merge'; import type { Book, BookConfig, BookNote } from '@/types/book'; import type { RemoteBookConfig } from '@/services/sync/file/wire'; @@ -577,6 +579,54 @@ describe('mergeBookMetadata metadataUpdatedAt clock (issue #5438)', () => { }); }); +describe('original filename reconciliation', () => { + const local: Book = { + hash: 'pdf-hash', + format: 'PDF', + title: 'PowerPoint Presentation', + sourceTitle: 'Local managed title', + author: 'Author', + createdAt: 1, + updatedAt: 200, + metadataUpdatedAt: 100, + }; + const remote: Book = { + ...local, + title: 'Device Manual', + sourceTitle: 'Remote managed title', + originalFilename: 'Device Manual.PDF', + }; + + test.each([ + ['mergeBookMetadata', mergeBookMetadata], + ['resolvePublishedBook', resolvePublishedBook], + ] as const)('%s fills missing provenance without changing title, managed path, or clocks', (_name, merge) => { + expect(merge(local, remote)).toEqual({ ...local, originalFilename: 'Device Manual.PDF' }); + expect(local.originalFilename).toBeUndefined(); + }); + + test.each([ + ['mergeBookMetadata', mergeBookMetadata], + ['resolvePublishedBook', resolvePublishedBook], + ] as const)('%s preserves an existing filename and does not invent absent provenance', (_name, merge) => { + const named = { ...local, originalFilename: 'Original.pdf' }; + expect(merge(named, remote)).toEqual(named); + expect(merge(local, { ...remote, originalFilename: undefined })).toEqual(local); + }); + + test('Full Sync repairs missing provenance once, without requiring newer clocks', () => { + expect(isRemoteBookMissingLocally(local, remote)).toBe(true); + const repaired = mergeBookMetadata(local, remote); + expect(isRemoteBookMissingLocally(repaired, remote)).toBe(false); + expect(shouldApplyRemoteBookMetadata(local, remote)).toBe(false); + expect(isRemoteBookMissingLocally(local, { ...remote, originalFilename: undefined })).toBe( + false, + ); + expect(isRemoteBookMissingLocally({ ...local, deletedAt: 300 }, remote)).toBe(false); + expect(isRemoteBookMissingLocally(local, { ...remote, deletedAt: 300 })).toBe(false); + }); +}); + describe('shouldApplyRemoteBookMetadata metadataUpdatedAt clause (issue #5438)', () => { test('triggers when only the remote metadata stamp is newer', () => { const local = { hash: 'h', title: 'L', author: 'A', updatedAt: 90 } as Book; diff --git a/apps/readest-app/src/__tests__/services/web-app-service.test.ts b/apps/readest-app/src/__tests__/services/web-app-service.test.ts index a8b453e7d..ef022366f 100644 --- a/apps/readest-app/src/__tests__/services/web-app-service.test.ts +++ b/apps/readest-app/src/__tests__/services/web-app-service.test.ts @@ -97,6 +97,18 @@ describe('WebAppService', () => { vi.restoreAllMocks(); }); + test.each([ + ['folder/安全 Manual.v2.pdf', undefined, '安全 Manual.v2.pdf'], + ['folder/first\\chapter.pdf', undefined, 'first\\chapter.pdf'], + ['folder/manual?rev1.pdf', undefined, 'manual?rev1.pdf'], + ['folder/Report%20Final.pdf', undefined, 'Report%20Final.pdf'], + ['folder/book.pdf', 'Original%20Name.pdf', 'Original%20Name.pdf'], + ])('openFile returns the resolved basename for %s', async (path, name, expected) => { + vi.spyOn(service.fs, 'readFile').mockResolvedValue(new ArrayBuffer(0)); + const file = await service.fs.openFile(path!, 'None', name); + expect(file.name).toBe(expected); + }); + describe('class properties', () => { test('appPlatform is web', () => { expect(service.appPlatform).toBe('web'); diff --git a/apps/readest-app/src/__tests__/utils/transform.test.ts b/apps/readest-app/src/__tests__/utils/transform.test.ts index 5b2a5629b..44359aae7 100644 --- a/apps/readest-app/src/__tests__/utils/transform.test.ts +++ b/apps/readest-app/src/__tests__/utils/transform.test.ts @@ -497,6 +497,36 @@ describe('transformBook metadataUpdatedAt (issue #5438)', () => { }); }); +describe('book original filename', () => { + const book: Book = { + hash: 'h', + format: 'EPUB', + title: 'T', + author: 'A', + originalFilename: '原書 (original edition).epub', + createdAt: 1, + updatedAt: 2, + }; + + it('round-trips the original import filename through the DB record', () => { + const db = transformBookToDB(book, 'u'); + expect(db).toMatchObject({ original_filename: book.originalFilename }); + expect(transformBookFromDB(db).originalFilename).toBe(book.originalFilename); + }); + + it('omits the outgoing column when no original filename is known', () => { + const db = transformBookToDB({ ...book, originalFilename: undefined }, 'u'); + expect(JSON.parse(JSON.stringify(db))).not.toHaveProperty('original_filename'); + }); + + it.each([undefined, null])('keeps the local filename when the DB value is %s', (value) => { + const row = transformBookToDB(book, 'u'); + const pulled = transformBookFromDB({ ...row, original_filename: value }); + expect(pulled).not.toHaveProperty('originalFilename'); + expect({ ...book, ...pulled }.originalFilename).toBe(book.originalFilename); + }); +}); + describe('book page count', () => { const book: Book = { hash: 'h', diff --git a/apps/readest-app/src/pages/api/sync.ts b/apps/readest-app/src/pages/api/sync.ts index e565ad700..79e37cbb7 100644 --- a/apps/readest-app/src/pages/api/sync.ts +++ b/apps/readest-app/src/pages/api/sync.ts @@ -803,6 +803,7 @@ export async function POST(req: NextRequest) { | 'group_name' | 'group_updated_at' | 'page_count' + | 'original_filename' > > & Pick; @@ -815,6 +816,9 @@ export async function POST(req: NextRequest) { // Group membership likewise merges on its own clock (issue #5911). const group = resolveGroupMerge(clientBook, serverBook, clientIsNewer); const pageCount = resolvePageCountMerge(clientBook, serverBook, clientIsNewer); + // Import provenance only fills a blank; page-turn clocks and peers + // without the filename must not replace one already recorded. + const originalFilename = serverBook.original_filename || clientBook.original_filename; if (clientIsNewer) { // Client wins the row; graft the fresher status + cover + // metadata onto it (server's may be the newer one even though @@ -832,6 +836,7 @@ export async function POST(req: NextRequest) { clientBook.group_name = group.group_name; clientBook.group_updated_at = group.group_updated_at; clientBook.page_count = pageCount; + clientBook.original_filename = originalFilename; toUpdate.push(clientBook); } else { // Only rewrite when a resolved field VALUE differs from the @@ -845,12 +850,15 @@ export async function POST(req: NextRequest) { const metadataChanged = bookMetadataChanged(meta, serverBook); const groupChanged = bookGroupChanged(group, serverBook); const pageCountChanged = pageCount !== (serverBook.page_count ?? null); + const originalFilenameChanged = + (originalFilename ?? null) !== (serverBook.original_filename ?? null); if ( statusChanged || coverChanged || metadataChanged || groupChanged || - pageCountChanged + pageCountChanged || + originalFilenameChanged ) { // Server wins the row, but the client's status, cover and/or // metadata is the fresher one. Graft the fresher fields onto @@ -876,6 +884,7 @@ export async function POST(req: NextRequest) { propagated.group_name = group.group_name; propagated.group_updated_at = group.group_updated_at; propagated.page_count = pageCount; + propagated.original_filename = originalFilename; toUpdate.push(propagated); } else { batchAuthoritativeRecords.push(serverData); diff --git a/apps/readest-app/src/services/bookService.ts b/apps/readest-app/src/services/bookService.ts index d5027cf14..5075ce8fb 100644 --- a/apps/readest-app/src/services/bookService.ts +++ b/apps/readest-app/src/services/bookService.ts @@ -576,6 +576,7 @@ export async function importBook( try { let format: BookFormat; let filename: string; + let originalFilename: string | undefined; // When the Rust EPUB parser succeeds it gives us the partialMD5 for free, // so we can short-circuit the JS hashing pass below. let nativeHash: string | undefined; @@ -590,13 +591,9 @@ export async function importBook( ({ book: loadedBook, format } = await openPseStreamBook(data)); filename = file as string; } else { - if (typeof file === 'string') { - fileobj = await fs.openFile(file, 'None'); - filename = fileobj.name || getFilename(file); - } else { - fileobj = file; - filename = file.name; - } + fileobj = typeof file === 'string' ? await fs.openFile(file, 'None') : file; + filename = fileobj.name; + originalFilename = filename; // A download saved as "novel.txt (1)" is still a TXT, and its title // should not read "novel.txt" either. Drop the duplicate marker before // anything downstream classifies or names the book (issue #5959). @@ -731,21 +728,19 @@ export async function importBook( } const hash = isPseStream ? md5(file as string) : (nativeHash ?? (await partialMD5(fileobj!))); - - // PDF metadata is often generic boilerplate (e.g. every PowerPoint export - // is titled "PowerPoint Presentation" by the same author), so metadata - // alone wrongly collapses distinct files into one book (issue #5411). - // Salt the hash with the original filename so only same-named PDFs dedupe. - const metaHash = getMetadataHash( - loadedBook.metadata, - format === 'PDF' ? getBaseFilename(filename) : undefined, - ); - const stableHash = hasVolatileIdentifiers(format) - ? getStableMetadataHash(loadedBook.metadata) - : undefined; let existingBook = lookupIndex ? lookupIndex.byHash.get(hash) : books.find((b) => b.hash === hash); + const metaHash = + format === 'PDF' && existingBook + ? existingBook.metaHash + : getMetadataHash( + loadedBook.metadata, + format === 'PDF' ? getBaseFilename(filename) : undefined, + ); + const stableHash = hasVolatileIdentifiers(format) + ? getStableMetadataHash(loadedBook.metadata) + : undefined; let metaHashMatch = false; let oldBookDir: string | undefined; if (existingBook) { @@ -806,7 +801,11 @@ export async function importBook( hash, format, metaHash, - title: formatTitle(loadedBook.metadata.title), + title: + format === 'PDF' + ? (existingBook?.title ?? filename.replace(/\.[^.]*$/, '')) + : formatTitle(loadedBook.metadata.title), + originalFilename: existingBook ? existingBook.originalFilename : originalFilename, sourceTitle: formatTitle(loadedBook.metadata.title), primaryLanguage, author: formatAuthors(loadedBook.metadata.author, primaryLanguage), @@ -865,6 +864,7 @@ export async function importBook( existingBook.format = book.format; existingBook.metaHash = metaHash; existingBook.title = book.title; + existingBook.originalFilename = book.originalFilename; existingBook.sourceTitle = book.sourceTitle; existingBook.author = book.author; existingBook.primaryLanguage = book.primaryLanguage; @@ -879,6 +879,7 @@ export async function importBook( existingBook.format = book.format; existingBook.metaHash = metaHash; existingBook.title = book.title; + existingBook.originalFilename = book.originalFilename; existingBook.sourceTitle = book.sourceTitle; existingBook.author = book.author; existingBook.primaryLanguage = book.primaryLanguage; diff --git a/apps/readest-app/src/services/nativeAppService.ts b/apps/readest-app/src/services/nativeAppService.ts index 6b048ba84..afd78f6d3 100644 --- a/apps/readest-app/src/services/nativeAppService.ts +++ b/apps/readest-app/src/services/nativeAppService.ts @@ -40,7 +40,7 @@ import { import type { Book } from '@/types/book'; import { needsQueryRangeReads } from '@/utils/ua'; import { getOSPlatform, isContentURI, isFileURI, isValidURL } from '@/utils/misc'; -import { getDirPath, getFilename } from '@/utils/path'; +import { getDirPath, getFilename, getPathFilename, getURLFilename } from '@/utils/path'; import { NativeFile, RemoteFile } from '@/utils/file'; import { copyURIToPath, @@ -313,11 +313,12 @@ export const nativeFileSystem: FileSystem = { async openFile(path: string, base: BaseDir, name?: string, fetcher?: typeof fetch) { const normalizedPath = OS_TYPE === 'ios' ? safeDecodePath(path) : path; const { fp, baseDir } = this.resolvePath(normalizedPath, base); - let fname = safeDecodePath(name || getFilename(fp)); if (isValidURL(path)) { + const fname = name || getURLFilename(path); return await new RemoteFile(path, fname, '', Date.now(), fetcher ?? tauriFetch).open(); - } else if (isContentURI(path) || (isFileURI(path) && OS_TYPE === 'ios')) { - fname = safeDecodePath(await basename(path)); + } + if (isContentURI(path) || (isFileURI(path) && OS_TYPE === 'ios')) { + const fname = safeDecodePath(await basename(path)); if (path.includes('com.android.externalstorage')) { // If the URI is from shared internal storage (like /storage/emulated/0), // we can access it directly using the path — no need to copy. @@ -335,7 +336,10 @@ export const nativeFileSystem: FileSystem = { } return await new NativeFile(dst, fname, baseDir ? baseDir : null).open(); } - } else if (isFileURI(path)) { + } + const localPath = OS_TYPE === 'windows' ? fp.replace(/\\/g, '/') : fp; + const fname = name || (isFileURI(path) ? getURLFilename(path) : getPathFilename(localPath)); + if (isFileURI(path)) { return await new NativeFile(fp, fname, baseDir ? baseDir : null).open(); } else if (needsQueryRangeReads(OS_TYPE)) { // Android and Linux can't use the asset protocol for ranged reads — diff --git a/apps/readest-app/src/services/sync/file/merge.ts b/apps/readest-app/src/services/sync/file/merge.ts index be472036b..18818fba1 100644 --- a/apps/readest-app/src/services/sync/file/merge.ts +++ b/apps/readest-app/src/services/sync/file/merge.ts @@ -196,6 +196,10 @@ export const mergeBookMetadata = (local: Book, remote: Book): Book => { // this a metadata-less peer erased every book's description across the fleet // (#5912). merged.metadata = merged.metadata ?? remote.metadata ?? local.metadata; + // Directory discovery cannot recover the original import name from the managed file. + if (!merged.originalFilename && remote.originalFilename) { + merged.originalFilename = remote.originalFilename; + } return merged; }; @@ -243,7 +247,7 @@ export const shouldApplyRemoteBookMetadata = (local: Book, remote: Book): boolea * trigger, and the pass that gets a device's own shelf back after #5911 / #5912 * emptied it. * - * Both cases are "an absent value must never win", and neither can loop: + * These cases are "an absent value must never win", and none can loop: * applying the merge makes the local row equal the resolution, after which this * is false again. * @@ -253,6 +257,7 @@ export const shouldApplyRemoteBookMetadata = (local: Book, remote: Book): boolea * has already returned true, so the only question left here is the tie — and * on a tie the merge itself resolves the same way. * - A description this device does not have and the peer does. + * - An original import filename missing from a directory-discovered row. * * Never on the incremental path. It is true for an entire library at once on * the first run after the fix, and every hit costs a local library write @@ -267,7 +272,8 @@ export const isRemoteBookMissingLocally = (local: Book, remote: Book): boolean = !remote.deletedAt && !local.deletedAt && (bookGroupDiffers(local, pickFresherGroup(local, remote, false)) || - (!local.metadata && !!remote.metadata)); + (!local.metadata && !!remote.metadata) || + (!local.originalFilename && !!remote.originalFilename)); /** * The row to PUBLISH into library.json for a book this device also holds, @@ -303,12 +309,14 @@ export const resolvePublishedBook = (local: Book, remote: Book | undefined): Boo const meta = remoteMetaNewer ? remote : local; // Never delete a blob the remote has, whichever side won the clock. const metadata = meta.metadata ?? local.metadata ?? remote.metadata; + const originalFilename = local.originalFilename || remote.originalFilename; if ( group.groupId === local.groupId && group.groupName === local.groupName && group.groupUpdatedAt === local.groupUpdatedAt && !remoteMetaNewer && - metadata === local.metadata + metadata === local.metadata && + originalFilename === local.originalFilename ) { return local; } @@ -325,5 +333,6 @@ export const resolvePublishedBook = (local: Book, remote: Book | undefined): Boo } : {}), metadata, + ...(originalFilename ? { originalFilename } : {}), }; }; diff --git a/apps/readest-app/src/services/webAppService.ts b/apps/readest-app/src/services/webAppService.ts index 93e529b7d..5707dc944 100644 --- a/apps/readest-app/src/services/webAppService.ts +++ b/apps/readest-app/src/services/webAppService.ts @@ -3,6 +3,7 @@ import { DatabaseOpts, DatabaseService } from '@/types/database'; import { SchemaType } from '@/services/database/migrate'; import { getOSPlatform, isValidURL } from '@/utils/misc'; import { isSafariBrowser } from '@/utils/ua'; +import { getPathFilename, getURLFilename } from '@/utils/path'; import { RemoteFile } from '@/utils/file'; import { detectViewTransitionGroup, detectViewTransitionsAPI } from '@/utils/viewTransition'; import { isPWA } from './environment'; @@ -83,10 +84,16 @@ const indexedDBFileSystem: FileSystem = { }, async openFile(path: string, base: BaseDir, filename?: string, fetcher?: typeof fetch) { if (isValidURL(path)) { - return await new RemoteFile(path, filename, '', Date.now(), fetcher).open(); + return await new RemoteFile( + path, + filename || getURLFilename(path), + '', + Date.now(), + fetcher, + ).open(); } else { const content = await this.readFile(path, base, 'binary'); - return new File([content], filename || path); + return new File([content], filename || getPathFilename(path)); } }, async copyFile(srcPath: string, srcBase: BaseDir, dstPath: string, dstBase: BaseDir) { diff --git a/apps/readest-app/src/types/book.ts b/apps/readest-app/src/types/book.ts index 43a3f6fca..890862fd5 100644 --- a/apps/readest-app/src/types/book.ts +++ b/apps/readest-app/src/types/book.ts @@ -115,7 +115,8 @@ export interface Book { // Metadata md5 hash, used to aggregate different versions of the same book metaHash?: string; format: BookFormat; - title: string; // editable title from metadata + title: string; // editable title, defaulting to the filename stem for PDFs + originalFilename?: string; // original import basename, including the extension sourceTitle?: string; // parsed when the book is imported and used to locate the file author: string; group?: string; // deprecated in favor of groupId and groupName diff --git a/apps/readest-app/src/types/records.ts b/apps/readest-app/src/types/records.ts index 084f17ad5..19b968f81 100644 --- a/apps/readest-app/src/types/records.ts +++ b/apps/readest-app/src/types/records.ts @@ -6,6 +6,7 @@ export interface DBBook { format: string; title: string; source_title?: string; + original_filename?: string | null; author: string; group_id?: string; group_name?: string; diff --git a/apps/readest-app/src/types/system.ts b/apps/readest-app/src/types/system.ts index 76a35bd41..695069fea 100644 --- a/apps/readest-app/src/types/system.ts +++ b/apps/readest-app/src/types/system.ts @@ -64,6 +64,7 @@ export interface FileSystem { getURL(path: string): string; getBlobURL(path: string, base: BaseDir): Promise; getImageURL(path: string): Promise; + /** Returns a File whose name is the resolved basename, not the input path or URI. */ openFile(path: string, base: BaseDir, filename?: string, fetcher?: typeof fetch): Promise; copyFile(srcPath: string, srcBase: BaseDir, dstPath: string, dstBase: BaseDir): Promise; readFile(path: string, base: BaseDir, mode: 'text' | 'binary'): Promise; diff --git a/apps/readest-app/src/utils/path.ts b/apps/readest-app/src/utils/path.ts index f267712de..819377943 100644 --- a/apps/readest-app/src/utils/path.ts +++ b/apps/readest-app/src/utils/path.ts @@ -11,6 +11,22 @@ export const getFilename = (fileOrUri: string) => { return lastPart.split('?')[0]!; }; +export const getPathFilename = (path: string) => { + // Backslashes are separators in drive-rooted and UNC Windows paths only. + const normalized = /^(?:[a-z]:[\\/]|\\\\)/i.test(path) ? path.replace(/\\/g, '/') : path; + return normalized.split('/').pop()!; +}; + +export const getURLFilename = (url: string) => { + const name = new URL(url).pathname.split('/').pop() || 'remote-file'; + try { + return decodeURIComponent(name); + } catch { + // Keep the encoded basename when the server uses non-UTF-8 path bytes. + return name; + } +}; + /** * Duplicate marker a browser or download manager appends when a download would * overwrite an existing file. Several of them put it after the extension diff --git a/apps/readest-app/src/utils/transform.ts b/apps/readest-app/src/utils/transform.ts index fda74ee09..24e25fd6c 100644 --- a/apps/readest-app/src/utils/transform.ts +++ b/apps/readest-app/src/utils/transform.ts @@ -77,6 +77,7 @@ export const transformBookToDB = (book: unknown, userId: string): DBBook => { format, title, sourceTitle, + originalFilename, author, groupId, groupName, @@ -116,6 +117,7 @@ export const transformBookToDB = (book: unknown, userId: string): DBBook => { cover_updated_at: coverUpdatedAt ? new Date(coverUpdatedAt).toISOString() : null, page_count: pageCount ?? null, source_title: sanitizeString(sourceTitle), + original_filename: sanitizeString(originalFilename), metadata: metadata ? sanitizeString(JSON.stringify(metadata)) : null, metadata_updated_at: metadataUpdatedAt ? new Date(metadataUpdatedAt).toISOString() : null, created_at: new Date(createdAt ?? Date.now()).toISOString(), @@ -143,6 +145,7 @@ export const transformBookFromDB = (dbBook: DBBook): Book => { cover_updated_at, page_count, source_title, + original_filename, metadata, metadata_updated_at, created_at, @@ -179,6 +182,7 @@ export const transformBookFromDB = (dbBook: DBBook): Book => { // Only when set: an undefined key would wipe the local count in the pull // merge's `{ ...local, ...remote }` spread. if (page_count != null) book.pageCount = page_count; + if (original_filename != null) book.originalFilename = original_filename; // Native cloud DBBook has no `url` column; a feed book carries its feed URL in // metadata so the reader can rebuild the feed:// descriptor here. if (!book.url && book.metadata?.feedUrl) { diff --git a/docker/volumes/db/init/schema.sql b/docker/volumes/db/init/schema.sql index 9131f1a60..d0071daa9 100644 --- a/docker/volumes/db/init/schema.sql +++ b/docker/volumes/db/init/schema.sql @@ -8,6 +8,7 @@ CREATE TABLE public.books ( format text NULL, title text NULL, source_title text NULL, + original_filename text NULL, author text NULL, "group" text NULL, tags text[] NULL, diff --git a/docker/volumes/db/migrations/031_add_book_original_filename.sql b/docker/volumes/db/migrations/031_add_book_original_filename.sql new file mode 100644 index 000000000..36697e462 --- /dev/null +++ b/docker/volumes/db/migrations/031_add_book_original_filename.sql @@ -0,0 +1,8 @@ +-- Migration 031: Add `original_filename` to books +-- +-- Preserve the original import basename, including its extension, across +-- cloud sync. Nullable for books imported before the filename was recorded. +-- Apply BEFORE deploying clients or servers that write the new column. + +ALTER TABLE public.books + ADD COLUMN IF NOT EXISTS original_filename text NULL;