Files
legolog/src/routes/cdn.js
Ben 7a45951daf are you schewpic
Former-commit-id: 5858160470aae5fbb85510a991f708d2ab1e7341
2022-04-29 19:19:42 +01:00

87 lines
2.5 KiB
JavaScript

const Logger = require('../logger.js');
const md5 = require('md5');
const fs = require('fs');
// fast thumbnail generation
const sharp = require('sharp');
function Get(req, res) {
// get id from url
let id = req.params.id;
let thumbnail = false;
if (id.includes('-thumb')) {
thumbnail = true;
id = id.replace('-thumb', '');
}
// TODO: bricks with a modifier should show the modified colour in the thumbnail
// I HAVE NO IDEA HOW TO DO THIS WITHOUT A LOT OF WORK
// if linux
let defaultFile = `${process.cwd()}\\db\\img\\default.png`;
if (process.platform !== 'win32') {
defaultFile = defaultFile.replace(/\\/g, '/');
}
// this very randomly fails sometimes
try {
// work out hash from id
const hash = md5(id.split('.png')[0]);
const bucket = hash.substring(0, 4);
// if linux
let file = `${process.cwd()}\\db\\img\\${bucket[0]}\\${bucket[1]}\\${bucket[2]}\\${bucket[3]}\\${id}`;
if (process.platform !== 'win32') {
file = file.replace(/\\/g, '/');
}
if (fs.existsSync(file)) {
if (thumbnail) {
// generate thumbnail
sharp(file)
.resize({
height: 50,
}) // keep aspect ratio
.toBuffer()
.then(data => {
res.set('Content-Type', 'image/png');
res.send(data);
})
.catch(err => {
Logger.Error(err);
res.sendStatus(404);
});
return;
}
res.sendFile(file);
} else {
if (thumbnail) {
sharp(defaultFile)
.resize({
height: 50,
}) // keep aspect ratio
.toBuffer()
.then(data => {
res.set('Content-Type', 'image/png');
res.send(data);
})
.catch(err => {
Logger.Error(err);
res.sendStatus(404);
});
return;
}
res.sendFile(defaultFile);
}
} catch (err) {
Logger.Error(err);
res.sendStatus(404);
}
}
module.exports = {
Get,
};