2015-07-15 19:01:23 +03:00
|
|
|
var crypto = require('crypto'),
|
|
|
|
fs = require('fs'),
|
|
|
|
path = require('path'),
|
2016-09-09 13:23:47 +03:00
|
|
|
config = require('../config'),
|
|
|
|
utils = require('../utils');
|
2015-07-15 19:01:23 +03:00
|
|
|
|
|
|
|
// ### ServeSharedFile Middleware
|
|
|
|
// Handles requests to robots.txt and favicon.ico (and caches them)
|
|
|
|
function serveSharedFile(file, type, maxAge) {
|
|
|
|
var content,
|
2015-12-15 13:41:53 +03:00
|
|
|
corePath = config.paths.corePath,
|
|
|
|
filePath,
|
|
|
|
blogRegex = /(\{\{blog-url\}\})/g,
|
|
|
|
apiRegex = /(\{\{api-url\}\})/g;
|
|
|
|
|
|
|
|
filePath = file.match(/^shared/) ? path.join(corePath, file) : path.join(corePath, 'shared', file);
|
2015-07-15 19:01:23 +03:00
|
|
|
|
|
|
|
return function serveSharedFile(req, res, next) {
|
2015-12-15 13:41:53 +03:00
|
|
|
if (req.path === '/' + file) {
|
2015-07-15 19:01:23 +03:00
|
|
|
if (content) {
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
res.end(content.body);
|
|
|
|
} else {
|
|
|
|
fs.readFile(filePath, function readFile(err, buf) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
2015-12-15 13:41:53 +03:00
|
|
|
|
|
|
|
if (type === 'text/xsl' || type === 'text/plain' || type === 'application/javascript') {
|
|
|
|
buf = buf.toString().replace(blogRegex, config.url.replace(/\/$/, ''));
|
2016-09-09 13:23:47 +03:00
|
|
|
buf = buf.toString().replace(apiRegex, utils.url.apiUrl({cors: true}));
|
2015-07-15 19:01:23 +03:00
|
|
|
}
|
|
|
|
content = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': type,
|
|
|
|
'Content-Length': buf.length,
|
|
|
|
ETag: '"' + crypto.createHash('md5').update(buf, 'utf8').digest('hex') + '"',
|
|
|
|
'Cache-Control': 'public, max-age=' + maxAge
|
|
|
|
},
|
|
|
|
body: buf
|
|
|
|
};
|
|
|
|
res.writeHead(200, content.headers);
|
|
|
|
res.end(content.body);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = serveSharedFile;
|