mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-11-30 01:00:27 +03:00
fix(core): report files skipped during import (#15892)
Markdown, HTML and Word imports silently dropped a file when it could not be read or converted: the per-file loop only kept files that returned a doc id, and the file picker's snapshot step dropped unreadable files with a `console.error`. The dialog then reported "Import completed". This change: - moves snapshotting of picked files into the importer (`snapshotReadableFiles`, already used by the Obsidian import), which records unreadable files as warnings; the picker no longer has a `snapshot` option - records files the converter returned no doc for as `skipped_doc` warnings - shows "Import completed with warnings" and the list of warnings instead of the success message when there are any - sets `sourcePath` on Markdown zip docs so skipped entries are named by path instead of a generated id fix #15718 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Import status now reports when files are skipped, unreadable, or only partially imported. * Imported Markdown documents retain their source paths within the archive. * File and directory pickers can use the standard browser picker instead of the File System Access API. * **Bug Fixes** * Importing multiple files now handles unreadable files and files that cannot be converted without interrupting the remaining imports. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: DarkSky <darksky2048@gmail.com>
This commit is contained in:
1 parent
c31c1323e4
commit
97602cf734
8 files changed
+158
-142
No files matched your search
@@ -168,7 +168,6 @@ type AcceptTypes =
|
||||
|
||||
type OpenFileOptions = {
|
||||
fileSystemAccess?: boolean;
|
||||
snapshot?: boolean;
|
||||
};
|
||||
|
||||
function copyToArrayBuffer(bytes: Uint8Array) {
|
||||
@@ -211,21 +210,6 @@ export async function snapshotFile(file: File, relativePath?: string) {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export async function snapshotFiles(files: File[]) {
|
||||
const results = await Promise.allSettled(
|
||||
files.map(file => snapshotFile(file))
|
||||
);
|
||||
const snapshots: File[] = [];
|
||||
for (const result of results) {
|
||||
if (result.status === 'fulfilled') {
|
||||
snapshots.push(result.value);
|
||||
} else {
|
||||
console.error('Failed to snapshot file', result.reason);
|
||||
}
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
function canUseFileSystemAccessAPI(
|
||||
api: 'showOpenFilePicker' | 'showDirectoryPicker'
|
||||
) {
|
||||
@@ -241,10 +225,6 @@ function canUseFileSystemAccessAPI(
|
||||
);
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown) {
|
||||
return error instanceof Error && error.name === 'AbortError';
|
||||
}
|
||||
|
||||
function isNotReadableError(error: unknown) {
|
||||
return error instanceof Error && error.name === 'NotReadableError';
|
||||
}
|
||||
@@ -274,19 +254,15 @@ export async function openFilesWith(
|
||||
// Show the file picker, optionally allowing multiple files.
|
||||
const handles = await window.showOpenFilePicker(pickerOpts);
|
||||
|
||||
const files = await Promise.all(handles.map(handle => handle.getFile()));
|
||||
return options?.snapshot ? await snapshotFiles(files) : files;
|
||||
return await Promise.all(handles.map(handle => handle.getFile()));
|
||||
} catch (err) {
|
||||
if (options?.snapshot && !isAbortError(err)) {
|
||||
throw err;
|
||||
}
|
||||
console.error(err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback if the File System Access API is not supported.
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise(resolve => {
|
||||
// Append a new `<input type="file" multiple? />` and hide it.
|
||||
const input = document.createElement('input');
|
||||
input.classList.add('affine-upload-input');
|
||||
@@ -303,21 +279,9 @@ export async function openFilesWith(
|
||||
document.body.append(input);
|
||||
// The `change` event fires when the user interacts with the dialog.
|
||||
input.addEventListener('change', () => {
|
||||
const files = input.files ? Array.from(input.files) : null;
|
||||
const finish = (result: File[] | null) => {
|
||||
// Remove the `<input type="file" multiple? />` again from the DOM.
|
||||
input.remove();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
if (files && options?.snapshot) {
|
||||
snapshotFiles(files).then(finish, error => {
|
||||
input.remove();
|
||||
reject(error);
|
||||
});
|
||||
} else {
|
||||
finish(files);
|
||||
}
|
||||
// Remove the `<input type="file" multiple? />` again from the DOM.
|
||||
input.remove();
|
||||
resolve(input.files ? Array.from(input.files) : null);
|
||||
});
|
||||
// The `cancel` event fires when the user cancels the dialog.
|
||||
input.addEventListener('cancel', () => {
|
||||
@@ -359,19 +323,11 @@ export async function openDirectory(
|
||||
const fileHandle = handle as FileSystemFileHandle;
|
||||
if (fileHandle.getFile) {
|
||||
const file = await fileHandle.getFile();
|
||||
if (options?.snapshot) {
|
||||
try {
|
||||
files.push(await snapshotFile(file, relativePath));
|
||||
} catch (error) {
|
||||
console.error('Failed to snapshot file', relativePath, error);
|
||||
}
|
||||
} else {
|
||||
Object.defineProperty(file, 'webkitRelativePath', {
|
||||
value: relativePath,
|
||||
writable: false,
|
||||
});
|
||||
files.push(file);
|
||||
}
|
||||
Object.defineProperty(file, 'webkitRelativePath', {
|
||||
value: relativePath,
|
||||
writable: false,
|
||||
});
|
||||
files.push(file);
|
||||
}
|
||||
} else if (handle.kind === 'directory') {
|
||||
await readDirectory(
|
||||
@@ -385,15 +341,12 @@ export async function openDirectory(
|
||||
await readDirectory(dirHandle, '');
|
||||
return files;
|
||||
} catch (err) {
|
||||
if (options?.snapshot && !isAbortError(err)) {
|
||||
throw err;
|
||||
}
|
||||
console.error(err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.classList.add('affine-upload-input');
|
||||
input.style.display = 'none';
|
||||
@@ -405,20 +358,8 @@ export async function openDirectory(
|
||||
document.body.append(input);
|
||||
|
||||
input.addEventListener('change', () => {
|
||||
const files = input.files ? Array.from(input.files) : null;
|
||||
const finish = (result: File[] | null) => {
|
||||
input.remove();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
if (files && options?.snapshot) {
|
||||
snapshotFiles(files).then(finish, error => {
|
||||
input.remove();
|
||||
reject(error);
|
||||
});
|
||||
} else {
|
||||
finish(files);
|
||||
}
|
||||
input.remove();
|
||||
resolve(input.files ? Array.from(input.files) : null);
|
||||
});
|
||||
|
||||
input.addEventListener('cancel', () => {
|
||||
|
||||
@@ -836,6 +836,7 @@ async function planMarkdownZipInternal({
|
||||
applySnapshotTitle(snapshot, preferredTitle);
|
||||
docs.push({
|
||||
id: pageId,
|
||||
sourcePath: fullPath,
|
||||
snapshot,
|
||||
meta: {
|
||||
...meta,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { importFilesAsDocs } from './file-import';
|
||||
|
||||
function unreadableFile(name: string) {
|
||||
const file = new File(['# unreadable'], name);
|
||||
Object.defineProperty(file, 'arrayBuffer', {
|
||||
value: () =>
|
||||
Promise.reject(new DOMException('Permission denied', 'SecurityError')),
|
||||
});
|
||||
return file;
|
||||
}
|
||||
|
||||
describe('importFilesAsDocs', () => {
|
||||
test.each([
|
||||
{
|
||||
name: 'imports every converted file without warnings',
|
||||
files: [new File(['# a'], 'a.md'), new File(['# b'], 'b.md')],
|
||||
failingNames: [],
|
||||
docIds: ['doc:a.md', 'doc:b.md'],
|
||||
warnings: [],
|
||||
},
|
||||
{
|
||||
name: 'reports files the importer could not convert',
|
||||
files: [new File(['# a'], 'a.md'), new File(['# b'], 'b.md')],
|
||||
failingNames: ['b.md'],
|
||||
docIds: ['doc:a.md'],
|
||||
warnings: [{ code: 'skipped_doc', sourcePath: 'b.md' }],
|
||||
},
|
||||
{
|
||||
name: 'reports files that cannot be read',
|
||||
files: [new File(['# a'], 'a.md'), unreadableFile('b.md')],
|
||||
failingNames: [],
|
||||
docIds: ['doc:a.md'],
|
||||
warnings: [{ code: 'file-unreadable', sourcePath: 'b.md' }],
|
||||
},
|
||||
])('$name', async ({ files, failingNames, docIds, warnings }) => {
|
||||
const result = await importFilesAsDocs(files, async file =>
|
||||
failingNames.includes(file.name) ? undefined : `doc:${file.name}`
|
||||
);
|
||||
|
||||
expect(result.docIds).toEqual(docIds);
|
||||
expect(result.warnings).toEqual(
|
||||
warnings.map(warning => expect.objectContaining(warning))
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { snapshotFile } from '@blocksuite/affine/shared/utils';
|
||||
import type { ImportWarning } from '@blocksuite/affine/widgets/linked-doc';
|
||||
|
||||
export async function snapshotReadableFiles(files: File[]) {
|
||||
const snapshots: File[] = [];
|
||||
const warnings: ImportWarning[] = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
snapshots.push(await snapshotFile(file));
|
||||
} catch (error) {
|
||||
const sourcePath = file.webkitRelativePath || file.name;
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
warnings.push({
|
||||
code: 'file-unreadable',
|
||||
message: `Skipped unreadable file: ${sourcePath}. ${reason}`,
|
||||
sourcePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { files: snapshots, warnings };
|
||||
}
|
||||
|
||||
export async function importFilesAsDocs(
|
||||
files: File[],
|
||||
importFile: (file: File) => Promise<string | undefined>
|
||||
) {
|
||||
const { files: readableFiles, warnings } = await snapshotReadableFiles(files);
|
||||
const docIds: string[] = [];
|
||||
for (const file of readableFiles) {
|
||||
const docId = await importFile(file);
|
||||
if (docId) {
|
||||
docIds.push(docId);
|
||||
} else {
|
||||
warnings.push({
|
||||
code: 'skipped_doc',
|
||||
message: `Skipped ${file.name}: the file could not be converted to a document`,
|
||||
sourcePath: file.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { docIds, warnings };
|
||||
}
|
||||
@@ -25,7 +25,11 @@ import {
|
||||
import { DebugLogger } from '@affine/debug';
|
||||
import { useI18n } from '@affine/i18n';
|
||||
import track from '@affine/track';
|
||||
import { openDirectory, openFilesWith } from '@blocksuite/affine/shared/utils';
|
||||
import {
|
||||
openDirectory,
|
||||
openFilesWith,
|
||||
snapshotFile,
|
||||
} from '@blocksuite/affine/shared/utils';
|
||||
import type { Workspace } from '@blocksuite/affine/store';
|
||||
import {
|
||||
DocxTransformer,
|
||||
@@ -56,15 +60,11 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
import { importFilesAsDocs } from './file-import';
|
||||
import * as style from './styles.css';
|
||||
|
||||
const logger = new DebugLogger('import');
|
||||
|
||||
function shouldSnapshotPickedFiles(type: ImportType, acceptType: AcceptType) {
|
||||
if (acceptType === 'Directory' || acceptType === 'Skip') return false;
|
||||
return !['markdownZip', 'notion', 'bear', 'oneNote'].includes(type);
|
||||
}
|
||||
|
||||
type ImportType =
|
||||
| 'markdown'
|
||||
| 'markdownZip'
|
||||
@@ -292,22 +292,17 @@ const importConfigs: Record<ImportType, ImportConfig> = {
|
||||
markdown: {
|
||||
fileOptions: { acceptType: 'Markdown', multiple: true },
|
||||
importFunction: async ({ docCollection, files }) => {
|
||||
const docIds: string[] = [];
|
||||
for (const file of files) {
|
||||
return importFilesAsDocs(files, async file => {
|
||||
const text = await file.text();
|
||||
const fileName = file.name.split('.').slice(0, -1).join('.');
|
||||
const docId = await MarkdownTransformer.importMarkdownToDoc({
|
||||
return MarkdownTransformer.importMarkdownToDoc({
|
||||
collection: docCollection,
|
||||
schema: getAFFiNEWorkspaceSchema(),
|
||||
markdown: text,
|
||||
fileName,
|
||||
extensions: getStoreManager().config.init().value.get('store'),
|
||||
});
|
||||
if (docId) docIds.push(docId);
|
||||
}
|
||||
return {
|
||||
docIds,
|
||||
};
|
||||
});
|
||||
},
|
||||
},
|
||||
markdownZip: {
|
||||
@@ -326,22 +321,17 @@ const importConfigs: Record<ImportType, ImportConfig> = {
|
||||
html: {
|
||||
fileOptions: { acceptType: 'Html', multiple: true },
|
||||
importFunction: async ({ docCollection, files }) => {
|
||||
const docIds: string[] = [];
|
||||
for (const file of files) {
|
||||
return importFilesAsDocs(files, async file => {
|
||||
const text = await file.text();
|
||||
const fileName = file.name.split('.').slice(0, -1).join('.');
|
||||
const docId = await HtmlTransformer.importHTMLToDoc({
|
||||
return HtmlTransformer.importHTMLToDoc({
|
||||
collection: docCollection,
|
||||
schema: getAFFiNEWorkspaceSchema(),
|
||||
extensions: getStoreManager().config.init().value.get('store'),
|
||||
html: text,
|
||||
fileName,
|
||||
});
|
||||
if (docId) docIds.push(docId);
|
||||
}
|
||||
return {
|
||||
docIds,
|
||||
};
|
||||
});
|
||||
},
|
||||
},
|
||||
notion: {
|
||||
@@ -390,17 +380,14 @@ const importConfigs: Record<ImportType, ImportConfig> = {
|
||||
docx: {
|
||||
fileOptions: { acceptType: 'Docx', multiple: false },
|
||||
importFunction: async ({ docCollection, files }) => {
|
||||
const docIds: string[] = [];
|
||||
for (const file of files) {
|
||||
const docId = await DocxTransformer.importDocx({
|
||||
return importFilesAsDocs(files, file =>
|
||||
DocxTransformer.importDocx({
|
||||
collection: docCollection,
|
||||
schema: getAFFiNEWorkspaceSchema(),
|
||||
imported: file,
|
||||
extensions: getStoreManager().config.init().value.get('store'),
|
||||
});
|
||||
if (docId) docIds.push(docId);
|
||||
}
|
||||
return { docIds };
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
snapshot: {
|
||||
@@ -414,7 +401,7 @@ const importConfigs: Record<ImportType, ImportConfig> = {
|
||||
await ZipTransformer.importDocs(
|
||||
docCollection,
|
||||
getAFFiNEWorkspaceSchema(),
|
||||
file
|
||||
await snapshotFile(file)
|
||||
)
|
||||
)
|
||||
.filter((doc): doc is NonNullable<typeof doc> => doc !== undefined)
|
||||
@@ -577,27 +564,35 @@ const SuccessStatus = ({
|
||||
return (
|
||||
<>
|
||||
<div className={style.importModalTitle}>
|
||||
{t['com.affine.import.status.success.title']()}
|
||||
{warnings.length
|
||||
? t['com.affine.import.status.warning.title']()
|
||||
: t['com.affine.import.status.success.title']()}
|
||||
</div>
|
||||
<p className={style.importStatusContent}>
|
||||
{t['com.affine.import.status.success.message']()}{' '}
|
||||
<a
|
||||
className={style.link}
|
||||
href={BUILD_CONFIG.discordUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Discord
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
{warnings.length ? (
|
||||
<div className={style.importWarnings}>
|
||||
{warnings.map((warning, index) => (
|
||||
<div key={`${warning}-${index}`}>{warning}</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<>
|
||||
<p className={style.importStatusContent}>
|
||||
{t['com.affine.import.status.warning.message']()}
|
||||
</p>
|
||||
<div className={style.importWarnings}>
|
||||
{warnings.map((warning, index) => (
|
||||
<div key={`${warning}-${index}`}>{warning}</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className={style.importStatusContent}>
|
||||
{t['com.affine.import.status.success.message']()}{' '}
|
||||
<a
|
||||
className={style.link}
|
||||
href={BUILD_CONFIG.discordUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
Discord
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<div className={style.importModalButtonContainer}>
|
||||
<Button onClick={onComplete} variant="primary">
|
||||
{t['Complete']()}
|
||||
@@ -721,7 +716,6 @@ export const ImportDialog = ({
|
||||
})
|
||||
: await openFilesWith(acceptType, multiple, {
|
||||
fileSystemAccess: false,
|
||||
snapshot: shouldSnapshotPickedFiles(type, acceptType),
|
||||
});
|
||||
|
||||
if (!files || (files.length === 0 && acceptType !== 'Skip')) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getStoreManager } from '@affine/core/blocksuite/manager/store';
|
||||
import { ImportCommitService } from '@affine/core/desktop/dialogs/import/commit-service';
|
||||
import { snapshotReadableFiles } from '@affine/core/desktop/dialogs/import/file-import';
|
||||
import { commitNativeImport } from '@affine/core/desktop/dialogs/import/native-backend';
|
||||
import {
|
||||
preflightWebFilesImport,
|
||||
@@ -9,7 +10,6 @@ import { DebugLogger } from '@affine/debug';
|
||||
import { snapshotFile } from '@blocksuite/affine/shared/utils';
|
||||
import {
|
||||
BearTransformer,
|
||||
type ImportWarning,
|
||||
MarkdownTransformer,
|
||||
NotionHtmlTransformer,
|
||||
ObsidianTransformer,
|
||||
@@ -180,22 +180,3 @@ async function detectNotionZipFormat(file: File): Promise<'markdown' | 'html'> {
|
||||
if (hasHtml) return 'html';
|
||||
throw new Error('No Notion Markdown or HTML pages found in the archive');
|
||||
}
|
||||
|
||||
async function snapshotReadableFiles(files: File[]) {
|
||||
const snapshots: File[] = [];
|
||||
const warnings: ImportWarning[] = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
snapshots.push(await snapshotFile(file));
|
||||
} catch (error) {
|
||||
const sourcePath = file.webkitRelativePath || file.name;
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
warnings.push({
|
||||
code: 'file-unreadable',
|
||||
message: `Skipped unreadable file: ${sourcePath}. ${reason}`,
|
||||
sourcePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { files: snapshots, warnings };
|
||||
}
|
||||
@@ -2807,6 +2807,14 @@ export function useAFFiNEI18N(): {
|
||||
* `Import completed`
|
||||
*/
|
||||
["com.affine.import.status.success.title"](): string;
|
||||
/**
|
||||
* `Some items were skipped or only partly imported:`
|
||||
*/
|
||||
["com.affine.import.status.warning.message"](): string;
|
||||
/**
|
||||
* `Import completed with warnings`
|
||||
*/
|
||||
["com.affine.import.status.warning.title"](): string;
|
||||
/**
|
||||
* `Cancel`
|
||||
*/
|
||||
|
||||
@@ -693,6 +693,8 @@
|
||||
"com.affine.import.status.importing.title": "Importing...",
|
||||
"com.affine.import.status.success.message": "Your document has been imported successfully, thank you for choosing AFFiNE. Any questions please feel free to feedback to us",
|
||||
"com.affine.import.status.success.title": "Import completed",
|
||||
"com.affine.import.status.warning.message": "Some items were skipped or only partly imported:",
|
||||
"com.affine.import.status.warning.title": "Import completed with warnings",
|
||||
"com.affine.inviteModal.button.cancel": "Cancel",
|
||||
"com.affine.issue-feedback.cancel": "Maybe later",
|
||||
"com.affine.issue-feedback.confirm": "Create issue on GitHub",
|
||||
|
||||
Reference in new issue
Block a user