2017-02-22 19:29:35 +00:00
|
|
|
import jsdom, { serializeDocument } from 'jsdom';
|
2016-09-05 20:08:08 +00:00
|
|
|
import Project from '../models/project';
|
2016-11-16 18:12:36 +00:00
|
|
|
import {
|
|
|
|
injectMediaUrls,
|
|
|
|
resolvePathsForElementsWithAttribute,
|
|
|
|
resolveScripts,
|
2019-01-16 22:56:18 +00:00
|
|
|
resolveStyles
|
|
|
|
} from '../utils/previewGeneration';
|
2017-11-27 21:58:53 +00:00
|
|
|
import { get404Sketch } from '../views/404Page';
|
2016-09-05 20:08:08 +00:00
|
|
|
|
|
|
|
export function serveProject(req, res) {
|
|
|
|
Project.findById(req.params.project_id)
|
|
|
|
.exec((err, project) => {
|
2017-11-27 21:58:53 +00:00
|
|
|
if (err || !project) {
|
2017-11-27 22:32:03 +00:00
|
|
|
get404Sketch(html => res.send(html));
|
|
|
|
return;
|
2017-11-27 21:58:53 +00:00
|
|
|
}
|
2016-11-17 16:15:35 +00:00
|
|
|
// TODO this does not parse html
|
2018-05-05 00:59:43 +00:00
|
|
|
const { files } = project;
|
2017-01-11 20:50:36 +00:00
|
|
|
const htmlFile = files.find(file => file.name.match(/\.html$/i)).content;
|
2016-11-16 18:12:36 +00:00
|
|
|
const filesToInject = files.filter(file => file.name.match(/\.(js|css)$/i));
|
|
|
|
injectMediaUrls(filesToInject, files, req.params.project_id);
|
2016-09-05 20:08:08 +00:00
|
|
|
|
2017-01-11 20:50:36 +00:00
|
|
|
jsdom.env(htmlFile, (innerErr, window) => {
|
2016-11-16 18:12:36 +00:00
|
|
|
const sketchDoc = window.document;
|
2016-11-30 17:38:53 +00:00
|
|
|
|
|
|
|
const base = sketchDoc.createElement('base');
|
2018-10-16 15:43:07 +00:00
|
|
|
const fullUrl = `https://${req.get('host')}${req.originalUrl}`;
|
2016-11-30 17:38:53 +00:00
|
|
|
base.href = `${fullUrl}/`;
|
|
|
|
sketchDoc.head.appendChild(base);
|
|
|
|
|
2016-11-16 18:12:36 +00:00
|
|
|
resolvePathsForElementsWithAttribute('src', sketchDoc, files);
|
|
|
|
resolvePathsForElementsWithAttribute('href', sketchDoc, files);
|
|
|
|
resolveScripts(sketchDoc, files);
|
|
|
|
resolveStyles(sketchDoc, files);
|
2016-09-05 20:08:08 +00:00
|
|
|
|
2016-11-16 18:12:36 +00:00
|
|
|
res.send(serializeDocument(sketchDoc));
|
2016-09-05 20:08:08 +00:00
|
|
|
});
|
|
|
|
});
|
2016-11-17 16:15:35 +00:00
|
|
|
}
|
2017-02-22 19:29:35 +00:00
|
|
|
|
|
|
|
export default serveProject;
|