fix(library): preserve original filenames and use PDF filename titles (#7237)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_web_browser (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run

* fix(library): preserve import filenames and use PDF filename titles

Save each imported file's original basename, including its extension, on
the local Book record. Use the filename stem as the PDF display title while
preserving embedded metadata and the sourceTitle used to locate managed
files. Retain the original filename when re-importing a managed copy.

Regression evidence: before the fix, import-metahash and
import-docx-conversion had 13 assertion failures for missing
originalFilename fields and PDF titles still reading PowerPoint
Presentation. Both suites pass with the change.

Verified:
- Full unit suite: 1220 files passed, 4 skipped; 14648 tests passed,
  16 skipped (before updating to origin/main a2dd013a4).
- On origin/main a2dd013a4: six import suites plus useProgressSync,
  7 files / 124 tests passed.
- pnpm lint passed; formatting and git diff --check passed.
- Real web app: imported Device_Manual_V2.1.pdf with embedded title
  PowerPoint Presentation; filename title and originalFilename persisted
  after reload.
- Windows desktop not tested. Linux CEF verification was incomplete:
  the reused binary rendered a blank frontend in the isolated harness.

Reported by xiongshaowei on GitHub.
Refs #7230.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve question marks in import basenames

Derive local basenames without the URL helper's query stripping. For local
path imports use the supplied path, since NativeFile.name may already have
been shortened by that helper. Remote and provider imports retain their
resolved file names and URL fallback behavior.

The new File and path regression cases fail before this change with
originalFilename/title 'manual' instead of 'manual?rev1.pdf'/'manual?rev1'.
They now pass and verify two revisions remain separate library records.
A URL query fallback test also passes. Six import suites: 82 tests passed.
pnpm lint and formatting passed. The pre-push hook reruns the full suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain filename provenance across import and sync

Keep literal POSIX backslashes in import basenames and PDF identity, while
recognizing explicit Windows paths. Strip queries only from web URL fallback
names and preserve explicitly resolved filenames.

When a cloud-restored PDF lacks its original filename, reimporting its exact
managed path preserves the stored title and metadata hash. File sync fills
missing original filenames without changing titles, storage paths, or clocks.

Verification: four importer regressions failed first (URL fallback, two
backslash input forms, and cloud-restored managed copy). Three sync assertions
failed first for missing provenance and repair detection. All 232 tests across
11 affected suites pass with the fixes. pnpm lint, Biome formatting, and git
diff --check pass. Real web imports and reload retain three distinct filename
titles, original basenames, and embedded metadata. Windows desktop was not
tested; the earlier isolated Linux CEF harness remained blank. The full suite
runs again in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): exclude URL fragments from import fallback names

Remove the fragment before deriving the fallback name for a remote file,
while keeping explicitly resolved filenames unchanged.

Verification: the new fragment regression failed first because originalFilename
was manual.pdf#page=2 instead of manual.pdf. All 94 tests across the importer
metadata and web service suites pass, including query-plus-fragment and explicit
question-mark/hash filename cases. pnpm lint, formatting, and git diff --check
pass. Full unit tests run in the pre-push hook. Native device verification was
not repeated for this web URL fallback change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): decode remote basenames after parsing the URL path

Derive a web remote file's fallback name from its final pathname segment before
decoding. This excludes queries and fragments, decodes reserved characters, and
preserves encoded backslashes as filename characters. Keep the encoded spelling
when pathname bytes cannot be decoded as UTF-8. Explicit filenames bypass this.

Verification: six new URL cases failed before the fix, covering C++, a slash
inside the query, malformed query/path bytes, and two encoded backslash names.
All 100 tests in the importer metadata and web service suites now pass. pnpm
lint, Biome formatting, and git diff --check pass. The full suite runs in the
pre-push hook. Native device verification was not repeated for this web fallback.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* test(library): cover Android provider display names on import

Verify opaque Android content URIs resolve the provider display name through
Tauri basename, for both external-storage and staged-provider file paths.
Verify importBook uses that resolved File.name for originalFilename, PDF title,
and salted identity instead of parsing the document identifier.

Verification: all 114 tests across the import metadata, web service, and native
service suites pass, as do pnpm lint, formatting, and git diff --check. This is
coverage of the existing basename flow, so no production behavior changed.
Android native basename was inspected and queries OpenableColumns.DISPLAY_NAME.
UI verification could not run against the available emulator because its
existing development WebView shows an unavailable URL. The full unit suite runs
in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve resolved filenames as atomic basenames

Do not split a resolved File.name again during original filename capture.
Local path basenames were already extracted, while a decoded URL segment may
contain a slash that belongs to its filename identity.

Verification: the two-file URL regression failed first with one/part.pdf reduced
to part.pdf and a different salted hash. It now passes and verifies two live
records with distinct filename titles and metadata hashes. All 138 tests across
eight import/native suites pass. pnpm lint, formatting, and git diff --check
pass. The full suite runs in the pre-push hook. Device UI checks were not
repeated for this filename capture change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): simplify import filename handling (owner: refactor and simplify it)

Replace nested filename selection with explicit URI and local-path branches.
Resolve the managed-copy title/hash exception in one block instead of spreading
it across a boolean and three ternaries. Use the resolved title directly and
avoid PDF stem processing for non-PDF imports.

Verification: this is a control-flow refactor with no intended behavior change.
All 138 tests across eight import/native suites pass both before and after.
pnpm lint, Biome formatting, and git diff --check pass. Existing regressions
cover provider names, local special characters, Windows paths, decoded URLs,
conversion, and managed-copy identity. Full tests run again in the pre-push
hook. Device UI checks were not repeated for this refactor.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): share URL filename parsing across native and web imports

Reuse the URL pathname basename decoder in native and web filesystems. Native
URL fallbacks now exclude fragments and query separators and preserve decoded
filename characters, while explicit names remain unchanged. Use the existing
platform-aware path normalizer for managed-copy comparisons.

Verification: the new native URL and case-variant managed-copy regressions
failed before the fixes. All 146 tests across eight affected import/native
suites pass. pnpm lint, formatting, and git diff --check pass. Full tests run
in the pre-push hook. Device UI checks were not repeated; prior platform
verification limitations remain recorded on the PR.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): keep extensionless PDF downloads distinct

Use the existing file hash as the PDF identity salt when a remote URL does
not provide a .pdf filename. Keep the query-free title and original filename.
This prevents distinct query-selected downloads with identical metadata from
replacing one another's managed files.

Verified: the new extensionless-download regression failed before the fix
(expected two live books, received one), then all 147 affected tests passed.
pnpm lint passed with one unrelated informational notice; diff check passed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain extensionless PDF identity on reimport

Select the PDF identity salt from the preserved original filename rather than
the current input URL. Extensionless imports keep content-based identity when
the same files are reopened from local managed paths.

Verified: the extended two-download regression first failed because both
metadata hashes changed to the shared download stem. The correction preserves
both hashes, original names and live records without removing managed files.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): persist import provenance through cloud sync (owner: Can we simplify it?)

Add nullable books.original_filename, database mappings and blank-fill sync
merging so imported provenance survives cloud restoration and old clients.
Migration 031 must be applied before deploying the updated server.

Simplify PDF title/identity selection into three direct cases and normalize
the name once. Keep fallback metadata stable on managed-copy reimport and
refresh stale batch metadata keys after successful imports.

Verified: new regressions failed first for stale index keys, sanitized PDF
fallback titles, transform round trips and cloud filename merging. All 242
related tests pass, as do TypeScript, Biome lint and formatting checks. Actual
web imports, local reimports and reload preserve names and separate identities.
Migration applied twice successfully in isolated PostgreSQL, preserving null
legacy rows and round-tripping a Unicode filename. No live database changed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): resolve import filenames in openFile (owner: hide the filename parsing in openFile)

Have native and web filesystem openFile return a File whose name is the resolved
basename. Keep URL and Android provider resolution at that boundary and share
literal local-path basename parsing between the filesystem implementations.
The importer now reads fileobj.name without parsing the source path again.

Verified: eight new filesystem assertions failed before the changes for full
web paths, literal POSIX backslashes, question marks and percent-encoded-looking
local or supplied names. All 252 affected tests pass, as do TypeScript and Biome
lint. Existing importer mocks now provide resolved basenames; the obsolete
empty-name filesystem fallback test was removed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): resolve relative Windows import basenames

Normalize native Windows separators before extracting a local basename, so
relative and drive-relative paths satisfy the openFile name contract while
POSIX backslashes remain literal.

Verified: relative and root-relative Windows regression cases failed first
with directory components in File.name. The same POSIX relative name remains
literal. All 139 filesystem/importer tests and TypeScript/Biome lint pass.
Windows UI was not exercised on this Linux host.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve PDF identity and edited titles (owner: just use the origin filename as the default title)

Use the filename stem only as the initial PDF display title. Preserve stored
PDF titles and metadata hashes on exact-file reimport, and leave existing
books without filename provenance as they are. Keep the original content
hash and new-import metadata-hash calculations, removing content-salt and
managed-copy identity migration branches and their index maintenance.

Verified: two new regressions failed first because reimport replaced edited
or legacy titles and metadata hashes. All 81 importer tests now pass; lint
and whitespace checks pass. In the real web app, importing a PDF, editing
its title through Book Details, reloading, reimporting, and reloading again
preserved the edited bookshelf title, original filename, and both hashes.
Native UI was not repeated for this title-only simplification.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): clarify native filename branches (owner: Why the change is so ugly?)

Resolve URL and provider names within their early-return branches, then
select the local filename. Remove the overwritten mutable filename and
nested platform/path ternary while preserving existing naming behavior.

Verified with 141 passing native/web filesystem and importer tests, plus
TypeScript, Biome lint, and git diff --check. This is a control-flow cleanup;
no behavior change or new regression test is introduced. Native UI was not
repeated for this refactor.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-02 18:52:20 +08:00 • committed by GitHub
parent 4f9395859c
commit d5e10369b4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 657 additions and 36 deletions

View file

@ -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<Book>) =>
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);
});
});

View file

@ -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',

View file

@ -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

View file

@ -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');

View file

@ -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;

View file

@ -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');

View file

@ -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',

View file

@ -803,6 +803,7 @@ export async function POST(req: NextRequest) {
| 'group_name'
| 'group_updated_at'
| 'page_count'
| 'original_filename'
>
> &
Pick<DBBook, 'title' | 'author' | 'tags'>;
@ -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);

View file

@ -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;

View file

@ -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 —

View file

@ -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 } : {}),
};
};

View file

@ -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) {

View file

@ -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

View file

@ -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;

View file

@ -64,6 +64,7 @@ export interface FileSystem {
getURL(path: string): string;
getBlobURL(path: string, base: BaseDir): Promise<string>;
getImageURL(path: string): Promise<string>;
/** 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<File>;
copyFile(srcPath: string, srcBase: BaseDir, dstPath: string, dstBase: BaseDir): Promise<void>;
readFile(path: string, base: BaseDir, mode: 'text' | 'binary'): Promise<string | ArrayBuffer>;

View file

@ -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

View file

@ -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) {

View file

@ -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,

View file

@ -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;