Skip to content

Commit

Permalink
fix(embedFile): improve the file retrieval from the payload
Browse files Browse the repository at this point in the history
This will fix several missing file paths.

Close: #1133
Related-to: #901
  • Loading branch information
aalemayhu committed Jul 22, 2023
1 parent c3bf3d9 commit 01607fb
Showing 1 changed file with 47 additions and 22 deletions.
69 changes: 47 additions & 22 deletions src/lib/parser/exporters/embedFile.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,62 @@
import fs from 'fs';

import Bugsnag from '@bugsnag/js';
import { File } from '../../anki/zip';
import { SuffixFrom } from '../../misc/file';
import getUniqueFileName from '../../misc/getUniqueFileName';
import CustomExporter from './CustomExporter';

const getFile = (
exporter: CustomExporter,
files: File[],
filePath: string
): File | undefined => {
const asRootFile = files.find((f) => f.name === filePath);
if (asRootFile) {
return asRootFile;
}
const parent = exporter.firstDeckName.replace(/.html /, '/');
const asChildFile = files.find((f) => f.name === `${parent}/${filePath}`);
if (asChildFile) {
return asChildFile;
}

/*
* Could not find file, try to find it by ending.
* This happens in deeply nested directories.
* Example: using a huge database
*/
const normalized = filePath.replace(/\.\.\//g, '');
const usingSuffix = files.find(
(f) => f.name.endsWith(filePath) || f.name.endsWith(normalized)
);
if (usingSuffix) {
return usingSuffix;
}

return undefined;
};

export const embedFile = (
exporter: CustomExporter,
files: File[],
filePath: string
): string | null => {
const suffix = SuffixFrom(filePath);
let file = files.find((f) => f.name === filePath);
if (!file) {
const lookup = `${exporter.firstDeckName}/${filePath}`.replace(
/\.\.\//g,
''
);
file = files.find((f) => {
if (f.name === lookup || f.name.endsWith(filePath)) {
return f;
}
});
if (!file) {
Bugsnag.notify(
`Missing relative path to ${filePath} used ${exporter.firstDeckName}`
);
return null;
const file = getFile(exporter, files, filePath);

if (file) {
const newName = getUniqueFileName(filePath) + suffix;
const contents = file.contents as string;
if (contents) {
exporter.addMedia(newName, contents);
}
return newName;
} else {
Bugsnag.notify(
`Missing relative path to ${filePath} used ${exporter.firstDeckName}`
);
}
const newName = getUniqueFileName(filePath) + suffix;
const contents = file.contents as string;
if (contents) {
exporter.addMedia(newName, contents);
}
return newName;

return null;
};

0 comments on commit 01607fb

Please sign in to comment.