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