sandboxApp.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /* global __dirname */
  2. /* jshint strict:false */
  3. "use strict";
  4. var express = require('express');
  5. var bodyParser = require('body-parser');
  6. var slug = require('slug');
  7. var beautify = require('json-beautify');
  8. var _ = require('lodash');
  9. var path = require('path');
  10. var Mustache = require('mustache');
  11. var app = express();
  12. var fs = require('fs');
  13. var Promise = require('bluebird'); Promise.promisifyAll(fs);
  14. var sandboxTpml = fs.readFileSync(__dirname + '/html/template.mustache.html').toString();
  15. var exampleTmpl = require('./lib/exampleTmpl.json');
  16. var repoTmpl = require('./lib/repoTmpl.json');
  17. var ExampleStore = require('./lib/ExampleStore');
  18. var isTesting = process.env.NODE_ENV === 'testing';
  19. var examplesDir = ! isTesting ? __dirname + '/exemples' :
  20. __dirname + '/test/integration/test-examples';
  21. var exStore = new ExampleStore(examplesDir);
  22. var {
  23. readFileAsync,
  24. readFilesAsync
  25. } = require('./lib/fsio');
  26. var {
  27. getAcceptLanguage,
  28. getIndexBare,
  29. getIndexRepo,
  30. getIndexExample
  31. } = require('./lib/indexHandlers')(exStore, examplesDir, isTesting);
  32. var {
  33. // getIndexBare,
  34. getPartsRepo,
  35. getPartsExample
  36. } = require('./lib/partHandlers')(exStore, examplesDir);
  37. /**
  38. * Initialize example store
  39. */
  40. exStore.init();
  41. // .then(() => console.log(exStore.getMenu()));
  42. /**
  43. * Initialize Express app:
  44. * - root folder as static
  45. * - body parsers
  46. * - browser language detection middleware
  47. */
  48. app.use(express.static(__dirname));
  49. app.use(bodyParser.json());
  50. app.use(bodyParser.urlencoded({ extended: true }));
  51. app.use(getAcceptLanguage);
  52. function addExample(slug, title) {
  53. return fs.writeFileAsync(examplesJSON, beautify(examples, null, 2, 100));
  54. }
  55. function readConfigJson(exampleSlug) {
  56. console.log(exampleSlug);
  57. return require('./exemples/jquery/' + exampleSlug + '/config.json');
  58. }
  59. function mapObjToArray(obj, key, value) {
  60. var arr = [];
  61. for(var p in obj) {
  62. arr.push({
  63. [key]: p,
  64. [value]: obj[p]
  65. });
  66. }
  67. return arr;
  68. }
  69. function checkBodyPropsExist(props) {
  70. return function(req, res, next) {
  71. if(! props) {
  72. throw new Error('checkBodyPropsExist was called with empty props argument');
  73. }
  74. if(! req.body) {
  75. return res.status(400).send('request doest not have a body: please set "content-type" header to "application/json"');
  76. }
  77. props = typeof props === 'string' ? [props] : props;
  78. for(let p = 0 ; p < props.length ; p++) {
  79. const prop = props[p];
  80. if(! req.body[prop]) {
  81. return res.status(400).send('request body doest not have a `' + prop + '` parameter: please provide it.');
  82. }
  83. }
  84. next();
  85. };
  86. }
  87. /**
  88. * Get repo parts
  89. */
  90. app.get('/parts/:repoSlug', getPartsRepo);
  91. /**
  92. * Get example parts
  93. */
  94. app.get('/parts/:repoSlug/:exampleSlug', getPartsExample);
  95. /**
  96. * Index page: render with only repo list in menu
  97. */
  98. app.get('/', getIndexBare);
  99. /**
  100. * Index page: render for tests
  101. */
  102. // if(isTesting) {
  103. // app.get('/test', getIndexTest);
  104. // }
  105. /**
  106. * Repo page: render with repo list and selected repo's example list in menu
  107. */
  108. app.get('/:repoSlug', getIndexRepo);
  109. /**
  110. * Example page: render with repo list and selected repo's example list in menu,
  111. * and the editor with the selected example
  112. */
  113. app.get('/:repoSlug/:exampleSlug', getIndexExample);
  114. function checkRepoExists(req, res, next) {
  115. const { repoSlug } = req.params;
  116. console.log('### checkRepoExists', repoSlug);
  117. // Get repo from store
  118. req.repo = exStore.getRepo(repoSlug);
  119. if(! req.repo) {
  120. res.status(404).send("Repo " + repoSlug + "not found");
  121. }
  122. next();
  123. }
  124. /**
  125. * Create a new repo
  126. */
  127. app.post('/repos', function(req, res) {
  128. // Check for title and extract params
  129. if(! req.body || ! req.body.title) {
  130. res.status(400).send('Le titre ne peut pas être vide !');
  131. }
  132. const { title } = req.body;
  133. const repoSlug = slug(title.toLowerCase());
  134. const existingRepo = exStore.getRepo(repoSlug);
  135. // Prevent duplicate title
  136. if(existingRepo) {
  137. return res.status(409).send("La collection '" + title + "' existe déjà !");
  138. }
  139. // Prepare config
  140. var config = Object.assign({
  141. title
  142. }, repoTmpl);
  143. exStore.addRepository(repoSlug, config)
  144. .then(repo => res.json(config));
  145. });
  146. app.post('/:repoSlug/examples/:exampleSlug/file',
  147. checkRepoExists,
  148. checkBodyPropsExist('name'),
  149. function(req, res) {
  150. const { name } = req.body;
  151. const { repoSlug, exampleSlug } = req.params;
  152. const re = /^[A-Za-z0-9_\-\.]+$/;
  153. const targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
  154. const fullPath = targetDir + '/' + name;
  155. if(! re.test(name)) {
  156. return res.status(400).json('Le paramètre `name` est incorrect: caractères autorisés: lettres, chiffres, _, - et .' );
  157. }
  158. fs.statAsync(fullPath)
  159. // Invert the usual flow of a Promise. fs.stat() fails if file does not exist (which is what we want)
  160. // Hence .catch() is a success handler and .then() an error handler (has to rethrow)
  161. .catch(err => {
  162. return fs.writeFileAsync(fullPath, '')
  163. .then(() => res.json({
  164. name,
  165. path: fullPath
  166. }));
  167. })
  168. .then(stats => {
  169. throw new Error('Le fichier `' + name + '` existe déjà !');
  170. })
  171. .catch(err => {
  172. const statusCode = err.message.startsWith('Le fichier') ? 409 : 500;
  173. return res.status(statusCode).send(err.message);
  174. });
  175. }
  176. );
  177. /**
  178. * Create a new example for specified repo
  179. */
  180. app.post('/:repoSlug/examples',
  181. checkRepoExists,
  182. checkBodyPropsExist('title'),
  183. function(req, res) {
  184. const { title } = req.body;
  185. const { repoSlug } = req.params;
  186. // Prevent duplicate title
  187. var existingTitle = _.find(req.repo.examples, { title: title });
  188. if(existingTitle) {
  189. return res.status(409).send("L'exemple '" + title + "' existe déjà !");
  190. }
  191. var exampleSlug = slug(req.body.title.toLowerCase());
  192. // Prepare config
  193. var config = Object.assign({
  194. slug: exampleSlug,
  195. title,
  196. category: req.repo.defaultCategory
  197. }, exampleTmpl);
  198. // Prepare files to write
  199. var targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
  200. var files = mapObjToArray({
  201. 'example.html': '<!-- ' + title + ' -->\n',
  202. 'script.js': '// ' + title,
  203. 'config.json': beautify(config, null, 2, 100)
  204. }, 'file', 'content');
  205. fs.mkdirAsync(targetDir)
  206. .then(() => Promise.map(
  207. files, ({ file, content }) => fs.writeFileAsync(targetDir + '/' + file, content)
  208. ))
  209. .then(files => req.repo.examples.push(config))
  210. .then(() => res.json(config));
  211. }
  212. );
  213. app.get('/examples/:repoSlug/:slug',
  214. checkRepoExists,
  215. function(req, res) {
  216. const { repoSlug, slug } = req.params;
  217. var example = _.find(req.repo.examples, { slug });
  218. const { title, html, js, css, libsCss, libsJs } = example;
  219. console.log(example, title, html, js, css, libsCss, libsJs);
  220. readFileAsync(__dirname + '/exemples/' + repoSlug + '/' + slug + '/example.html')
  221. .then(body =>
  222. Mustache.render(sandboxTpml, { body, repoSlug, slug, title, js, css, libsCss, libsJs })
  223. )
  224. .then(html => res.send(html));
  225. }
  226. );
  227. app.get('/menu', (rea, res) => {
  228. res.send(exStore.getMenu());
  229. });
  230. app.get('/list/:repoPath', function(req, res) {
  231. const { repoPath } = req.params;
  232. const repo = exStore.getList(repoPath);
  233. if(! repo) {
  234. return res.status(404).send('Repo ' + repoPath + ' not found');
  235. }
  236. console.log('found repo', repo);
  237. const data = repo.examples.map(e => (
  238. { slug: e.slug, title: e.title }
  239. ));
  240. res.json(data);
  241. });
  242. app.put('/examples/:slug', function(req, res) {
  243. var slug = req.params.slug;
  244. var existing = _.find(examples, { slug: slug });
  245. if(! existing) {
  246. res.status(404).send("L'exemple avec l'identifiant '" + slug + "' est introuvable !");
  247. }
  248. var targetDir = __dirname + '/exemples/' + slug;
  249. if(req.body.html) {
  250. fs.writeFileSync(targetDir + '/contenu.html', req.body.html);
  251. }
  252. if(req.body.javascript) {
  253. fs.writeFileSync(targetDir + '/script.js', req.body.javascript);
  254. }
  255. var theDate = new Date();
  256. console.log(theDate.getHours() + ':' + theDate.getMinutes() + " - Sauvegarde de l'exemple '" + existing.title + " effectuée'");
  257. res.json({ success: true });
  258. });
  259. module.exports = app;