sandboxApp.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 menu
  69. */
  70. app.get('/parts/:repoSlug', getPartsRepo);
  71. /**
  72. * Index page: render with only repo list in menu
  73. */
  74. app.get('/', getIndexBare);
  75. /**
  76. * Repo page: render with repo list and selected repo's example list in menu
  77. */
  78. app.get('/:repoSlug', getIndexRepo);
  79. /**
  80. * Example page: render with repo list and selected repo's example list in menu,
  81. * and the editor with the selected example
  82. */
  83. app.get('/:repoSlug/:exampleSlug', getIndexExample);
  84. /**
  85. * Create a new example for specified repo
  86. */
  87. app.post('/:repoSlug/examples', function(req, res) {
  88. // Check for title and extract params
  89. if(! req.body || ! req.body.title) {
  90. res.status(400).send('Le titre ne peut pas être vide !');
  91. }
  92. const { title } = req.body;
  93. const { repoSlug } = req.params;
  94. // Get repo from store
  95. var repo = exStore.getRepo(repoSlug);
  96. if(! repo) {
  97. res.status(404).send("Repo " + repoSlug + "not found");
  98. }
  99. // Prevent duplicate title
  100. var existingTitle = _.find(repo.examples, { title: title });
  101. if(existingTitle) {
  102. res.status(400).send("L'exemple '" + title + "' existe déjà !");
  103. }
  104. var exampleSlug = slug(req.body.title.toLowerCase());
  105. // Prepare config
  106. var config = Object.assign({
  107. slug: exampleSlug,
  108. title,
  109. category: repo.defaultCategory
  110. }, exampleTmpl);
  111. // Prepare files to write
  112. var targetDir = __dirname + '/exemples/' + repoSlug + '/' + exampleSlug;
  113. var files = mapObjToArray({
  114. 'example.html': '<!-- ' + title + '-->\n',
  115. 'script.js': '// ' + title,
  116. 'config.json': beautify(config, null, 2, 100)
  117. }, 'file', 'content');
  118. fs.mkdirAsync(targetDir)
  119. .then(() => Promise.map(
  120. files, ({ file, content }) => fs.writeFileAsync(targetDir + '/' + file, content)
  121. ))
  122. .then(files => repo.examples.push(config))
  123. .then(() => res.json(config));
  124. });
  125. app.get('/examples/:slug', function(req, res) {
  126. const { slug } = req.params;
  127. const config = readConfigJson(slug);
  128. const { title, html, js, css, libsCss, libsJs } = config;
  129. readFileAsync(__dirname + '/exemples/' + slug + '/example.html')
  130. .then(body =>
  131. Mustache.render(sandboxTpml, { body, slug, title, js, css, libsCss, libsJs })
  132. )
  133. .then(html => res.send(html));
  134. });
  135. app.get('/menu', (rea, res) => {
  136. res.send(exStore.getMenu());
  137. });
  138. app.get('/list/:repoPath', function(req, res) {
  139. const { repoPath } = req.params;
  140. const repo = exStore.getList(repoPath);
  141. if(! repo) {
  142. return res.status(404).send('Repo ' + repoPath + ' not found');
  143. }
  144. console.log('found repo', repo);
  145. const data = repo.examples.map(e => (
  146. { slug: e.slug, title: e.title }
  147. ));
  148. res.json(data);
  149. });
  150. app.put('/examples/:slug', function(req, res) {
  151. var slug = req.params.slug;
  152. var existing = _.find(examples, { slug: slug });
  153. if(! existing) {
  154. res.status(404).send("L'exemple avec l'identifiant '" + slug + "' est introuvable !");
  155. }
  156. var targetDir = __dirname + '/exemples/' + slug;
  157. if(req.body.html) {
  158. fs.writeFileSync(targetDir + '/contenu.html', req.body.html);
  159. }
  160. if(req.body.javascript) {
  161. fs.writeFileSync(targetDir + '/script.js', req.body.javascript);
  162. }
  163. var theDate = new Date();
  164. console.log(theDate.getHours() + ':' + theDate.getMinutes() + " - Sauvegarde de l'exemple '" + existing.title + " effectuée'");
  165. res.json({ success: true });
  166. });
  167. module.exports = app;