2018-04-29 22:00:41 +02:00
|
|
|
const logger = require('winston');
|
2019-02-20 07:30:46 +01:00
|
|
|
const transformImage = require('./transformImage');
|
2019-02-24 07:23:56 +01:00
|
|
|
|
2019-02-26 09:32:34 +01:00
|
|
|
const isValidQueryObject = require('server/utils/isValidQueryObj');
|
2019-02-23 04:47:08 +01:00
|
|
|
const {
|
|
|
|
serving: { dynamicFileSizing },
|
|
|
|
} = require('@config/siteConfig');
|
|
|
|
const { enabled: dynamicEnabled } = dynamicFileSizing;
|
2019-02-26 09:32:34 +01:00
|
|
|
|
2019-02-20 07:30:46 +01:00
|
|
|
const serveFile = async ({ filePath, fileType }, res, originalUrl) => {
|
|
|
|
const queryObject = {};
|
|
|
|
// TODO: replace quick/dirty try catch with better practice
|
|
|
|
try {
|
|
|
|
originalUrl
|
|
|
|
.split('?')[1]
|
|
|
|
.split('&')
|
|
|
|
.map(pair => {
|
|
|
|
if (pair.includes('=')) {
|
|
|
|
let parr = pair.split('=');
|
|
|
|
queryObject[parr[0]] = parr[1];
|
|
|
|
} else queryObject[pair] = true;
|
|
|
|
});
|
|
|
|
} catch (e) {}
|
2018-04-29 22:00:41 +02:00
|
|
|
|
2018-07-08 00:03:21 +02:00
|
|
|
if (!fileType) {
|
|
|
|
logger.error(`no fileType provided for ${filePath}`);
|
|
|
|
}
|
2019-02-20 07:30:46 +01:00
|
|
|
|
|
|
|
let mediaType = fileType ? fileType.substr(0, fileType.indexOf('/')) : '';
|
|
|
|
const transform =
|
2019-02-23 04:47:08 +01:00
|
|
|
mediaType === 'image' &&
|
|
|
|
queryObject.hasOwnProperty('h') &&
|
|
|
|
queryObject.hasOwnProperty('w') &&
|
|
|
|
dynamicEnabled;
|
2019-02-20 07:30:46 +01:00
|
|
|
|
2018-04-29 22:00:41 +02:00
|
|
|
const sendFileOptions = {
|
|
|
|
headers: {
|
2019-02-20 07:30:46 +01:00
|
|
|
'X-Content-Type-Options': 'nosniff',
|
|
|
|
'Content-Type': fileType,
|
|
|
|
'Access-Control-Allow-Origin': '*',
|
2018-12-05 20:54:14 +01:00
|
|
|
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
|
2018-04-29 22:00:41 +02:00
|
|
|
},
|
|
|
|
};
|
2018-07-08 00:03:21 +02:00
|
|
|
logger.debug(`fileOptions for ${filePath}:`, sendFileOptions);
|
2019-02-23 04:47:08 +01:00
|
|
|
try {
|
|
|
|
if (transform) {
|
|
|
|
if (!isValidQueryObject(queryObject)) {
|
|
|
|
logger.debug(`Unacceptable querystring`, { queryObject });
|
|
|
|
res.status(400).json({
|
|
|
|
success: false,
|
|
|
|
message: 'Querystring may not have dimensions greater than 2000',
|
|
|
|
});
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
logger.debug(`transforming and sending file`);
|
2019-02-20 07:30:46 +01:00
|
|
|
|
2019-02-23 04:47:08 +01:00
|
|
|
let xformed = await transformImage(filePath, queryObject);
|
|
|
|
res.status(200).set(sendFileOptions.headers);
|
|
|
|
res.end(xformed, 'binary');
|
|
|
|
} else {
|
|
|
|
res.status(200).sendFile(filePath, sendFileOptions);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
logger.debug(e);
|
2019-02-20 07:30:46 +01:00
|
|
|
}
|
2018-04-29 22:00:41 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = serveFile;
|