feat(library): accept docx and rtf imports via silent EPUB conversion (#7050)

* feat(library): import docx and rtf via silent conversion to EPUB

DOCX and RTF have no native reader; today they are rejected at the
library door even though the app already ships a docx-to-EPUB
conversion pipeline: the Send inbox and /send page run
convertFileIfNeeded over incoming documents and land them in the same
library as ordinary EPUBs (novel import and RSS ingest already reuse
the same module). This routes local imports through the exact same
channel, closing the asymmetry between documents that arrive through
the cloud inbox and documents sitting on local disk.

Per the unified-reading-experience direction, the conversion is
silent: no UI changes, no new strings, no format naming. The
conversion branch sits next to the TXT-to-EPUB hook in importBook and
follows the same consume-the-source contract - the converted EPUB is
what gets hashed, stored, and synced; the source document is never
copied into Books/. The conversion stack stays code-split behind a
dynamic import.

Whitelisting docx/rtf lets every entry point (file picker, drag-drop,
folder walk, auto-import) reach the conversion; the two test files
that used resume.docx as their unsupported-extension counterexample
switch to .doc, which remains unsupported.

* fix(library): never bind converted docx/rtf imports to the source path

CodeRabbit major on #7050: for in-place or transient imports the
conversion produced an in-memory EPUB, but nothing was persisted and
the returned book kept filePath pointing at the original document - so
the reader would later open the raw docx (unsupported) and the
in-place sync path (uploadBook reads book.filePath) would upload the
raw document instead of the converted book.

- In-place docx/rtf imports now fall back to a managed copy: the
  converted EPUB is persisted into Books/<hash>/ and the book carries
  no source-path binding. In-place is only meaningful for formats the
  reader parses natively.
- Transient docx/rtf open-with fails fast: transient mode never
  persists anything, so the converted EPUB would have nowhere readable
  to live - the same net behavior as before the conversion existed,
  with a clearer error.

Both regressions are locked down by new test cases.

* test: update docx/rtf counterexamples after the whitelist change

The drag-drop mixed-drop fixture still used c.docx as its unsupported
counterexample, and the OPDS acquisition classifier test asserted docx/
rtf links as unsupported - both predate the whitelist change that makes
them importable. The drag-drop fixture now uses .doc (still
unsupported), and the OPDS rejects-list drops rtf/docx: the shared
SUPPORTED_BOOK_EXTS classifies their links as downloadable, and the
import pipeline converts them to EPUB on arrival.

* fix(send): keep the conversion worker out of its own import graph

bookService now starts the send-conversion worker, and the worker's own
graph reached bookService through assetBundler/faviconFetcher ->
services/environment -> appService. Turbopack then bundles the worker
inside itself: a cold `next build` hangs (build_web_app hit the 6 h CI
limit on this PR) and a warm one aborts with a turbo-tasks panic
(`get_disjoint_mut was called with equal keys`). Read the platform env
directly in those two modules, as AudiobookClock and constants do.

Verified: `pnpm build-web` on the PR rebased onto origin/main hung at
"Creating an optimized production build" for 12 min; with this change it
compiles in 15 s. Reverting only these two files brings the panic back.
No unit test: the failure is in the bundler, and build_web_app covers it.

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

* fix(library): remember a watched docx/rtf so auto-import skips it

A converted docx/rtf from a watched folder lives in Books/ with no
filePath, so collectKnownSourcePaths never saw its source and every
library open or window focus converted it again and toasted
"Successfully imported 1 book". Record the source in altFilePaths.

Verified: the new import-docx-conversion test fails without the change
(expected false to be true) and passes with it. In the Linux CEF app
with a watched folder holding a .docx, three window-focus events gave
3 conversions and 3 import toasts without the change, and none with it.

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

---------

Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
k6G52m4Dz75W 2026-10-25 17:44:49 +08:00 • committed by GitHub
parent 1d00df6ed4
commit 664b7dc342
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 346 additions and 17 deletions

View file

@ -101,7 +101,8 @@ describe('useDragDropImport skipped-file toast', () => {
it('names the skipped files of a mixed drop and imports the rest', async () => {
const spy = vi.spyOn(eventDispatcher, 'dispatch');
renderHook(() => useDragDropImport());
await dropTauriPaths(['C:\\Library\\a.epub', 'C:\\Library\\b.exe', 'C:\\Library\\c.docx']);
// .doc stays unsupported; .docx converts to EPUB on import and is accepted.
await dropTauriPaths(['C:\\Library\\a.epub', 'C:\\Library\\b.exe', 'C:\\Library\\c.doc']);
await waitFor(() =>
expect(spy).toHaveBeenCalledWith(
@ -113,7 +114,7 @@ describe('useDragDropImport skipped-file toast', () => {
const toasts = toastPayloads(spy);
expect(toasts).toHaveLength(1);
expect(toasts[0]!.type).toBe('error');
expect(toasts[0]!.message).toBe('Failed to import book(s): b.exe, c.docx');
expect(toasts[0]!.message).toBe('Failed to import book(s): b.exe, c.doc');
const importPayload = spy.mock.calls.find((call) => call[0] === 'import-book-files')?.[1] as {
files: { file?: File; path?: string }[];

View file

@ -140,8 +140,9 @@ describe('useAndroidPickedBooks with a mixed selection', () => {
test('imports the books and still names the file it dropped', async () => {
const onPickedBooks = vi.fn();
const dispatchSpy = vi.spyOn(eventDispatcher, 'dispatch').mockResolvedValue();
// .doc stays unsupported; .docx converts to EPUB on import and is accepted.
basenameMock.mockImplementation(async (path: string) =>
path.endsWith('/1') ? 'novel.epub' : 'resume.docx',
path.endsWith('/1') ? 'novel.epub' : 'resume.doc',
);
renderHook(() => useAndroidPickedBooks(makeAppService(true), onPickedBooks));
@ -154,7 +155,7 @@ describe('useAndroidPickedBooks with a mixed selection', () => {
]);
expect(dispatchSpy).toHaveBeenCalledWith(
'toast',
expect.objectContaining({ message: expect.stringContaining('resume.docx') }),
expect.objectContaining({ message: expect.stringContaining('resume.doc') }),
);
dispatchSpy.mockRestore();
});

View file

@ -187,7 +187,9 @@ describe('useFileSelector book selection with a duplicate-download marker', () =
test('reports the files it dropped instead of returning an empty selection silently', async () => {
const dispatchSpy = vi.spyOn(eventDispatcher, 'dispatch').mockResolvedValue();
basenameMock.mockResolvedValueOnce('resume.docx');
// .doc (legacy binary Word) stays unsupported; .docx converts to EPUB on
// import and is therefore an accepted book extension now.
basenameMock.mockResolvedValueOnce('resume.doc');
const { appService } = makeAppService('android', [
'content://com.android.providers.downloads/document/7',
]);
@ -200,7 +202,7 @@ describe('useFileSelector book selection with a duplicate-download marker', () =
'toast',
expect.objectContaining({
type: 'error',
message: expect.stringContaining('resume.docx'),
message: expect.stringContaining('resume.doc'),
}),
);
dispatchSpy.mockRestore();
@ -222,7 +224,7 @@ describe('useFileSelector book selection with a duplicate-download marker', () =
describe('useFileSelector reports every file it skips', () => {
test('keeps the supported file and still names the one it dropped', async () => {
const dispatchSpy = vi.spyOn(eventDispatcher, 'dispatch').mockResolvedValue();
basenameMock.mockResolvedValueOnce('novel.epub').mockResolvedValueOnce('resume.docx');
basenameMock.mockResolvedValueOnce('novel.epub').mockResolvedValueOnce('resume.doc');
const { appService } = makeAppService('android', [
'content://com.android.providers.downloads/document/1',
'content://com.android.providers.downloads/document/2',
@ -234,7 +236,7 @@ describe('useFileSelector reports every file it skips', () => {
expect(result.files).toEqual([expect.objectContaining({ name: 'novel.epub' })]);
expect(dispatchSpy).toHaveBeenCalledWith(
'toast',
expect.objectContaining({ message: expect.stringContaining('resume.docx') }),
expect.objectContaining({ message: expect.stringContaining('resume.doc') }),
);
// Only the rejected file is named.
const [, toast] = dispatchSpy.mock.calls[0]!;

View file

@ -0,0 +1,246 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Book } from '@/types/book';
import type { ClosableFile } from '@/utils/file';
const mockOpen = vi.hoisted(() => vi.fn());
const mockPartialMD5 = vi.hoisted(() => vi.fn());
const mockConvertDocx = vi.hoisted(() => vi.fn());
vi.mock('@/utils/md5', async () => {
const actual = await vi.importActual<typeof import('@/utils/md5')>('@/utils/md5');
return { ...actual, partialMD5: mockPartialMD5 };
});
vi.mock('@/libs/document', async () => {
const actual = await vi.importActual<typeof import('@/libs/document')>('@/libs/document');
class MockDocumentLoader {
open() {
return mockOpen();
}
}
return { ...actual, DocumentLoader: MockDocumentLoader };
});
vi.mock('@/services/send/conversion/conversionWorker', () => ({
convertToEpubWithWorker: mockConvertDocx,
}));
vi.mock('@/utils/svg', () => ({ svg2png: vi.fn() }));
vi.mock('@tauri-apps/plugin-http', () => ({ fetch: vi.fn() }));
vi.mock('@/libs/storage', () => ({
downloadFile: vi.fn(),
uploadFile: vi.fn(),
deleteFile: vi.fn(),
createProgressHandler: vi.fn(),
batchGetDownloadUrls: vi.fn(),
}));
import { BaseAppService } from '@/services/appService';
import { collectKnownSourcePaths } from '@/services/bookService';
class TestAppService extends BaseAppService {
protected fs = {
openFile: vi.fn(),
readFile: vi.fn(),
writeFile: vi.fn(),
copyFile: vi.fn(),
removeFile: vi.fn(),
readDir: vi.fn(),
createDir: vi.fn(),
removeDir: vi.fn(),
exists: vi.fn(),
stats: vi.fn(),
resolvePath: vi.fn(),
getURL: vi.fn(),
getBlobURL: vi.fn().mockResolvedValue(''),
getImageURL: vi.fn(),
getPrefix: vi.fn(),
};
protected resolvePath() {
return { baseDir: 0, basePrefix: async () => '', fp: '', base: 'Books' as const };
}
async init() {}
async setCustomRootDir() {}
async selectDirectory() {
return '';
}
async selectFiles() {
return [];
}
async saveFile() {
return false;
}
async saveImageToGallery() {
return false;
}
async ask() {
return false;
}
async openDatabase() {
return {} as ReturnType<BaseAppService['openDatabase']>;
}
async createWindow() {}
async getCacheDir() {
return '';
}
async clearWebviewCache() {}
async showNotification() {}
getFs() {
return this.fs;
}
}
const TEST_METADATA = {
title: 'Test Book',
author: 'Test Author',
language: 'en',
identifier: 'docx-id-1',
};
/**
* DOCX/RTF import converts the source to EPUB via the send-conversion worker
* before the pipeline opens it. The converted EPUB — not the source document —
* must be what DocumentLoader sees and what lands in Books/<hash>/, and the
* source ClosableFile must be closed either way (same lifecycle contract as
* the TXT conversion).
*/
describe('importBook DOCX/RTF conversion', () => {
let service: TestAppService;
let mockClose: ReturnType<typeof vi.fn>;
const makeSourceDoc = (name = 'report.docx'): ClosableFile => {
mockClose = vi.fn(async () => undefined);
const file = new File(['docx-bytes'], name, {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
}) as ClosableFile;
file.close = mockClose as ClosableFile['close'];
file.open = (async () => file) as ClosableFile['open'];
return file;
};
beforeEach(() => {
vi.clearAllMocks();
service = new TestAppService();
const fs = service.getFs();
fs.exists.mockResolvedValue(false);
fs.createDir.mockResolvedValue(undefined);
fs.writeFile.mockResolvedValue(undefined);
fs.removeDir.mockResolvedValue(undefined);
fs.readFile.mockResolvedValue('{}');
mockPartialMD5.mockResolvedValue('hash-docx-abc');
mockOpen.mockResolvedValue({
book: {
metadata: TEST_METADATA,
getCover: vi.fn().mockResolvedValue(null),
destroy: vi.fn(),
},
format: 'EPUB',
});
mockConvertDocx.mockResolvedValue({
file: new File(['epub-bytes'], 'report.epub', { type: 'application/epub+zip' }),
title: 'Test Book',
author: 'Test Author',
});
});
it('converts a DOCX via the worker and imports the resulting EPUB', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
const books: Book[] = [];
const result = await service.importBook('/library/report.docx', books);
expect(result).not.toBeNull();
expect(mockConvertDocx).toHaveBeenCalledTimes(1);
expect(mockConvertDocx).toHaveBeenCalledWith({
kind: 'docx',
bytes: expect.any(ArrayBuffer),
fileName: 'report.docx',
});
expect(mockClose).toHaveBeenCalledTimes(1);
});
it('stores the converted EPUB, never a copy of the source document', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
await service.importBook('/library/report.docx', []);
const fs = service.getFs();
expect(fs.copyFile).not.toHaveBeenCalled();
// The flow writes several files (book file, config, ...); the book file
// itself must be the converted EPUB, written from memory.
const bookWrite = fs.writeFile.mock.calls.find(([name]) => /\.epub$/.test(name));
expect(bookWrite).toBeDefined();
const [, baseDir] = bookWrite!;
expect(baseDir).toBe('Books');
});
it('converts an RTF through the same worker path', async () => {
const source = makeSourceDoc('notes.rtf');
service.getFs().openFile.mockResolvedValue(source);
const result = await service.importBook('/library/notes.rtf', []);
expect(result).not.toBeNull();
expect(mockConvertDocx).toHaveBeenCalledWith({
kind: 'rtf',
bytes: expect.any(ArrayBuffer),
fileName: 'notes.rtf',
});
});
it('rejects and still closes the source when conversion fails', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
mockConvertDocx.mockRejectedValue(new Error('Could not parse document'));
await expect(service.importBook('/library/report.docx', [])).rejects.toThrow();
expect(mockClose).toHaveBeenCalledTimes(1);
});
it('falls back to a managed copy for in-place DOCX imports', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
// In-place binds the book to the source path, but the reader can only
// open the converted EPUB — so an in-place docx import must be persisted
// into Books/ instead, and the book must not carry the source path.
const result = await service.importBook('/watched/report.docx', [], {
inPlace: true,
});
expect(result).not.toBeNull();
expect(result!.filePath).toBeUndefined();
const fs = service.getFs();
const bookWrite = fs.writeFile.mock.calls.find(([name]) => /\.epub$/.test(name));
expect(bookWrite).toBeDefined();
expect(fs.copyFile).not.toHaveBeenCalled();
});
it('remembers the watched source so the auto-import scan skips it next time', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
const result = await service.importBook('/watched/report.docx', [], { inPlace: true });
expect(collectKnownSourcePaths([result!], 'linux').has('/watched/report.docx')).toBe(true);
});
it('fails fast when a DOCX is opened transiently', async () => {
const source = makeSourceDoc();
service.getFs().openFile.mockResolvedValue(source);
// Transient mode never persists anything, so the converted EPUB would
// have nowhere readable to live — reject instead of returning a book
// bound to the raw document.
await expect(
service.importBook('/library/report.docx', [], { transient: true }),
).rejects.toThrow();
expect(mockConvertDocx).not.toHaveBeenCalled();
});
});

View file

@ -112,7 +112,10 @@ describe('classifyAcquisitionLink', () => {
});
it('rejects incompatible formats by href extension', () => {
for (const href of ['/dl/book.rtf', '/dl/book.docx', '/dl/book.lrf', '/dl/book.prc']) {
// rtf/docx left this list when they became importable: the shared
// whitelist classifies their links as downloadable, and the import
// pipeline converts them to EPUB on arrival.
for (const href of ['/dl/book.lrf', '/dl/book.prc']) {
expect(classifyAcquisitionLink(link({ href }))).toBe('unsupported');
}
});

View file

@ -537,6 +537,11 @@ export async function importBook(
lookupIndex,
osPlatform,
} = options;
// In-place is only meaningful for formats the reader can parse natively.
// DOCX/RTF are converted to EPUB and must be persisted into Books/ — the
// converted artifact is the only readable form, so binding the book to the
// original document path would break reader opens and sync uploads.
let effectiveInPlace = inPlace;
const isPseStream = typeof file === 'string' && isPseStreamFileName(file);
let loadedBook: BookDoc | undefined;
@ -605,6 +610,49 @@ export async function importBook(
openedSource = undefined;
}
}
// DOCX/RTF have no native reader either: convert to EPUB up front so
// everything downstream (native parse, hash, metadata, storage, sync)
// sees an ordinary EPUB import. Same consume-the-source contract as
// the TXT conversion above; the conversion stays silent — no UI, no
// new strings — consistent with how the Send inbox already converts
// documents through the same worker.
if (/\.(docx|rtf)$/i.test(filename)) {
// Fall back to a managed copy: the reader can only open the
// converted EPUB, so an in-place binding to the source document
// would be unreadable.
if (effectiveInPlace) {
effectiveInPlace = false;
}
// Transient open-with cannot work either: nothing is persisted in
// transient mode, so there is nowhere readable to put the EPUB.
// Fail fast instead of returning a book bound to the raw document.
if (transient) {
throw new Error(
'DOCX/RTF files must be imported (converted to EPUB) before they can be read; transient open is not supported.',
);
}
// Dynamic import: the conversion stack (mammoth, Readability, EPUB
// assembly) stays out of the main bundle via code splitting.
const { convertToEpubWithWorker } = await import(
'@/services/send/conversion/conversionWorker'
);
try {
const bytes = await fileobj.arrayBuffer();
const { file: convertedFile } = await convertToEpubWithWorker({
kind: /\.docx$/i.test(filename) ? 'docx' : 'rtf',
bytes,
fileName: filename,
});
fileobj = convertedFile;
} finally {
if (openedSource?.close) {
try {
await openedSource.close();
} catch {}
}
openedSource = undefined;
}
}
if (!fileobj || fileobj.size === 0) {
throw new Error('Invalid or empty book file');
}
@ -627,7 +675,10 @@ export async function importBook(
// tests.
let nativeBookDoc: BookDoc | undefined;
let nativeFormat: BookFormat | undefined;
if (typeof file === 'string' && !/\.txt$/i.test(filename)) {
// TXT/DOCX/RTF fileobj was converted in memory above, so the bytes at
// `path` are still the original document — don't hand those to the
// path-based native parsers.
if (typeof file === 'string' && !/(\.txt|\.docx|\.rtf)$/i.test(filename)) {
const nativePdf = await tryNativeParsePdf(file, fileobj, osPlatform);
if (nativePdf) {
nativeBookDoc = nativePdf.bookDoc;
@ -834,12 +885,15 @@ export async function importBook(
const willWriteBookFile =
saveBook &&
!transient &&
!inPlace &&
!effectiveInPlace &&
!!fileobj &&
(!(await fs.exists(bookFilename, 'Books')) ||
(overwrite && file !== `${await fs.getPrefix('Books')}/${bookFilename}`));
if (willWriteBookFile && fileobj) {
if (/\.txt$/i.test(filename)) {
if (/(\.txt|\.docx|\.rtf)$/i.test(filename)) {
// The import converted fileobj in memory; the file at `path` still
// holds the original document, so write the EPUB bytes — never copy
// the source path into Books.
await fs.writeFile(bookFilename, 'Books', fileobj);
} else if (typeof file === 'string' && isContentURI(file)) {
// openFile has already materialized opaque providers into a seekable
@ -1024,7 +1078,7 @@ export async function importBook(
if (isValidURL(file)) {
book.url = file;
if (existingBook) existingBook.url = file;
} else if (transient || inPlace) {
} else if (transient || effectiveInPlace) {
// transient: source file is loaded directly, never persisted in Books/.
// inPlace: source file is inside the user's library root and we read it
// there directly instead of duplicating it under Books/<hash>/.
@ -1034,11 +1088,20 @@ export async function importBook(
// Keep the path it is losing so the auto-import scan knows both
// files are accounted for (transient previews are never persisted,
// so there is nothing to remember for them).
if (inPlace && !transient) {
if (effectiveInPlace && !transient) {
displaceSourcePath(existingBook, file, osPlatform);
}
existingBook.filePath = file;
}
} else if (inPlace) {
// A converted DOCX/RTF lives in Books/; remember its watched source so
// the auto-import scan doesn't convert it again on every pass.
const target = existingBook || book;
const key = normalizeFilePathForIndex(file, osPlatform);
const known = (target.altFilePaths ?? []).map((p) =>
normalizeFilePathForIndex(p, osPlatform),
);
if (!known.includes(key)) target.altFilePaths = [...(target.altFilePaths ?? []), file];
}
}
// Now that `filePath` is set, keep the path index in sync so later files
@ -1046,7 +1109,7 @@ export async function importBook(
// in-place fast path. Only persistent in-place imports go into the
// index — transient previews are short-lived and never persisted to
// the library so indexing them would just leak references.
if (lookupIndex && inPlace && !transient && typeof file === 'string') {
if (lookupIndex && effectiveInPlace && !transient && typeof file === 'string') {
const indexedBook = existingBook || book;
if (indexedBook.filePath) {
const key = normalizeFilePathForIndex(indexedBook.filePath, osPlatform);

View file

@ -74,6 +74,11 @@ export const SUPPORTED_BOOK_EXTS = [
'mhtml',
'mht',
'rbooks',
// docx/rtf are never parsed natively: importBook converts them to EPUB and
// imports the result. Listed here so every picker / drag-drop / folder-walk
// entry point lets them through to that conversion.
'docx',
'rtf',
];
export const BOOK_ACCEPT_FORMATS = SUPPORTED_BOOK_EXTS.map((ext) => `.${ext}`).join(', ');
export const BOOK_UNGROUPED_NAME = '';

View file

@ -1,8 +1,12 @@
import { browserFetch as tauriFetch } from '@/services/webBrowser/browserFetch';
import { isTauriAppPlatform } from '@/services/environment';
import { imageFetchHeaders } from './httpHeaders';
import type { EpubImage } from './types';
// Not `isTauriAppPlatform` from services/environment: that module reaches
// appService → bookService → the conversion worker, so this module (bundled
// into send-conversion.worker) would spawn its own worker and hang the build.
const isTauriAppPlatform = () => process.env['NEXT_PUBLIC_APP_PLATFORM'] === 'tauri';
// On Tauri we go through the Rust HTTP client (no browser-CORS); on web
// we use the native fetch — the bundler is only ever invoked from a
// CORS-free caller there (the browser extension's service worker, which

View file

@ -1,5 +1,4 @@
import { browserFetch as tauriFetch } from '@/services/webBrowser/browserFetch';
import { isTauriAppPlatform } from '@/services/environment';
import { imageFetchHeaders } from './httpHeaders';
/**
@ -29,6 +28,11 @@ const HOSTED_FALLBACK_PATHS = [
'/favicon.ico',
];
// Not `isTauriAppPlatform` from services/environment: that module reaches
// appService → bookService → the conversion worker, so this module (bundled
// into send-conversion.worker) would spawn its own worker and hang the build.
const isTauriAppPlatform = () => process.env['NEXT_PUBLIC_APP_PLATFORM'] === 'tauri';
const httpFetch = (url: string, referer: string | null, init?: RequestInit): Promise<Response> => {
if (!isTauriAppPlatform()) {
// In the extension SW (the only non-Tauri caller today) include