sandboxApp.js 8.3 KB

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