sandboxApp.js 5.0 KB

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