sandboxApp.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 ExampleStore = require('./lib/ExampleStore');
  17. var examplesDir = __dirname + '/exemples';
  18. // var examplesDir = __dirname + '/test/integration/test-examples';
  19. var exStore = new ExampleStore(examplesDir);
  20. var {
  21. readFileAsync,
  22. readFilesAsync
  23. } = require('./lib/fsio');
  24. var {
  25. getAcceptLanguage,
  26. getIndexBare,
  27. getIndexRepo,
  28. getIndexExample
  29. } = require('./lib/indexHandlers')(exStore, examplesDir);
  30. var {
  31. // getIndexBare,
  32. getPartsRepo,
  33. getPartsExample
  34. } = require('./lib/partHandlers')(exStore, examplesDir);
  35. /**
  36. * Initialize example store
  37. */
  38. exStore.init();
  39. // .then(() => console.log(exStore.getMenu()));
  40. /**
  41. * Initialize Express app:
  42. * - root folder as static
  43. * - body parsers
  44. * - browser language detection middleware
  45. */
  46. app.use(express.static(__dirname));
  47. app.use(bodyParser.json());
  48. app.use(bodyParser.urlencoded({ extended: true }));
  49. app.use(getAcceptLanguage);
  50. function addExample(slug, title) {
  51. return fs.writeFileAsync(examplesJSON, beautify(examples, null, 2, 100));
  52. }
  53. function readConfigJson(exampleSlug) {
  54. console.log(exampleSlug);
  55. return require('./exemples/jquery/' + exampleSlug + '/config.json');
  56. }
  57. function mapObjToArray(obj, key, value) {
  58. var arr = [];
  59. for(var p in obj) {
  60. arr.push({
  61. [key]: p,
  62. [value]: obj[p]
  63. });
  64. }
  65. return arr;
  66. }
  67. /**
  68. * Get repo parts
  69. */
  70. app.get('/parts/:repoSlug', getPartsRepo);
  71. /**
  72. * Get example parts
  73. */
  74. app.get('/parts/:repoSlug/:exampleSlug', getPartsExample);
  75. /**
  76. * Index page: render with only repo list in menu
  77. */
  78. app.get('/', getIndexBare);
  79. /**
  80. * Repo page: render with repo list and selected repo's example list in menu
  81. */
  82. app.get('/:repoSlug', getIndexRepo);
  83. /**
  84. * Example page: render with repo list and selected repo's example list in menu,
  85. * and the editor with the selected example
  86. */
  87. app.get('/:repoSlug/:exampleSlug', getIndexExample);
  88. function checkRepoExists(req, res, next) {
  89. const { repoSlug } = req.params;
  90. console.log('### checkRepoExists', repoSlug);
  91. // Get repo from store
  92. req.repo = exStore.getRepo(repoSlug);
  93. if(! req.repo) {
  94. res.status(404).send("Repo " + repoSlug + "not found");
  95. }
  96. next();
  97. }
  98. /**
  99. * Create a new example for specified repo
  100. */
  101. app.post('/:repoSlug/examples',
  102. checkRepoExists,
  103. function(req, res) {
  104. // Check for title and extract params
  105. if(! req.body || ! req.body.title) {
  106. res.status(400).send('Le titre ne peut pas être vide !');
  107. }
  108. const { title } = req.body;
  109. const { repoSlug } = req.params;
  110. // Prevent duplicate title
  111. var existingTitle = _.find(req.repo.examples, { title: title });
  112. if(existingTitle) {
  113. res.status(400).send("L'exemple '" + title + "' existe déjà !");
  114. }
  115. var exampleSlug = slug(req.body.title.toLowerCase());
  116. // Prepare config
  117. var config = Object.assign({
  118. slug: exampleSlug,
  119. title,
  120. category: req.repo.defaultCategory
  121. }, exampleTmpl);
  122. // Prepare files to write
  123. var targetDir = __dirname + '/exemples/' + repoSlug + '/' + exampleSlug;
  124. var files = mapObjToArray({
  125. 'example.html': '<!-- ' + title + '-->\n',
  126. 'script.js': '// ' + title,
  127. 'config.json': beautify(config, null, 2, 100)
  128. }, 'file', 'content');
  129. fs.mkdirAsync(targetDir)
  130. .then(() => Promise.map(
  131. files, ({ file, content }) => fs.writeFileAsync(targetDir + '/' + file, content)
  132. ))
  133. .then(files => req.repo.examples.push(config))
  134. .then(() => res.json(config));
  135. }
  136. );
  137. app.get('/examples/:repoSlug/:slug',
  138. checkRepoExists,
  139. function(req, res) {
  140. const { repoSlug, slug } = req.params;
  141. var example = _.find(req.repo.examples, { slug });
  142. const { title, html, js, css, libsCss, libsJs } = example;
  143. console.log(example, title, html, js, css, libsCss, libsJs);
  144. readFileAsync(__dirname + '/exemples/' + repoSlug + '/' + slug + '/example.html')
  145. .then(body =>
  146. Mustache.render(sandboxTpml, { body, repoSlug, slug, title, js, css, libsCss, libsJs })
  147. )
  148. .then(html => res.send(html));
  149. }
  150. );
  151. app.get('/menu', (rea, res) => {
  152. res.send(exStore.getMenu());
  153. });
  154. app.get('/list/:repoPath', function(req, res) {
  155. const { repoPath } = req.params;
  156. const repo = exStore.getList(repoPath);
  157. if(! repo) {
  158. return res.status(404).send('Repo ' + repoPath + ' not found');
  159. }
  160. console.log('found repo', repo);
  161. const data = repo.examples.map(e => (
  162. { slug: e.slug, title: e.title }
  163. ));
  164. res.json(data);
  165. });
  166. app.put('/examples/:slug', function(req, res) {
  167. var slug = req.params.slug;
  168. var existing = _.find(examples, { slug: slug });
  169. if(! existing) {
  170. res.status(404).send("L'exemple avec l'identifiant '" + slug + "' est introuvable !");
  171. }
  172. var targetDir = __dirname + '/exemples/' + slug;
  173. if(req.body.html) {
  174. fs.writeFileSync(targetDir + '/contenu.html', req.body.html);
  175. }
  176. if(req.body.javascript) {
  177. fs.writeFileSync(targetDir + '/script.js', req.body.javascript);
  178. }
  179. var theDate = new Date();
  180. console.log(theDate.getHours() + ':' + theDate.getMinutes() + " - Sauvegarde de l'exemple '" + existing.title + " effectuée'");
  181. res.json({ success: true });
  182. });
  183. module.exports = app;