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
Close: #1133
Related-to: #901
  • Loading branch information
aalemayhu committed Jul 22, 2023
1 parent c3bf3d9 commit af4e705
Showing 1 changed file with 44 additions and 15 deletions.
59 changes: 44 additions & 15 deletions src/lib/parser/exporters/embedFile.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,61 @@
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 (!fs.existsSync('/Users/scanf/Downloads/Downloads/x.txt')) {
fs.writeFileSync(
'/Users/scanf/Downloads/x.txt',
files.map((file: File) => file.name).join('\n')
);
}
const file = getFile(exporter, files, filePath);
if (!file) {
const lookup = `${exporter.firstDeckName}/${filePath}`.replace(
/\.\.\//g,
''
Bugsnag.notify(
`Missing relative path to ${filePath} used ${exporter.firstDeckName}`
);
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;
}
return null;
}
const newName = getUniqueFileName(filePath) + suffix;
const contents = file.contents as string;
Expand Down

0 comments on commit af4e705

Please sign in to comment.