Skip to content

Commit

Permalink
Fix a bug where image resizing may be called on an unfinished downloa…
Browse files Browse the repository at this point in the history
…d and failing
  • Loading branch information
slmnio committed Mar 27, 2022
1 parent 54af157 commit 55c290a
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions server/src/images.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ async function getImage(filename, size) {
return null;
}
}
async function getOrWaitForDownload(url, filename, size) {
let p = getHeldPromise(["download", url, size, filename]);
if (p) {
console.log("[image] downloading in other promise, waiting for it");
await p;
}
return getImage(filename, size);
}

async function downloadImage(url, filename, size) {
return await heldPromise(["download", url, size, filename], new Promise((resolve, reject) => {
Expand Down Expand Up @@ -76,7 +84,7 @@ async function resizeImage(filename, sizeText, sizeData) {
try {
return await sharp(origFilePath).resize(sizeData).toFile(resizedFilePath);
} catch (e) {
console.warn(e);
console.error("Resize image error", e, origFilePath, sizeData);
if (e.code === "EEXIST") {
return await getImage(filename, sizeText);
}
Expand Down Expand Up @@ -197,11 +205,12 @@ module.exports = ({ app, cors, Cache }) => {
// no image

// first download or retrieve to orig/
let orig = await getImage(filename, "orig");
let orig = await getOrWaitForDownload(url, filename, "orig");
// let orig = await getImage(filename, "orig");
// console.log("[image]", "orig", orig);
if (!orig) {
const t = Date.now();
// console.log("[image]", `downloading ${originalFilename} @ orig...`);
console.log("[image]", `downloading ${originalFilename} @ orig...`);
await downloadImage(url, filename, "orig");
console.log("[image]", `downloaded ${originalFilename} @ orig in ${Date.now() - t}ms`);
orig = await getImage(filename, "orig");
Expand All @@ -220,6 +229,7 @@ module.exports = ({ app, cors, Cache }) => {
if (resizedImagePath) return res.sendFile(resizedImagePath);

} catch (e) {
console.error("Image error", e);
return res.status(400).send(e.message);
}
res.status(400).send("An error occurred");
Expand Down Expand Up @@ -278,7 +288,7 @@ module.exports = ({ app, cors, Cache }) => {
});

} catch (e) {
console.error(e);
console.error("Theme image error", e);
}
res.status(400).send("An error occurred");

Expand Down Expand Up @@ -375,7 +385,7 @@ module.exports = ({ app, cors, Cache }) => {
return res.header("Content-Type", "image/png").send(thumbBuffer);
}
} catch (e) {
console.error(e);
console.error("Match image error", e);
}
res.status(400).send("An error occurred");
}
Expand Down

0 comments on commit 55c290a

Please sign in to comment.