sandboxApp.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. function checkFilename(filename) {
  88. const base = path.basename(filename);
  89. let ext = path.extname(filename);
  90. ext = ext ? ext.toLowerCase().substr(1) : ext;
  91. return base && ['html', 'js', 'css'].indexOf( ext ) > -1;
  92. }
  93. /**
  94. * Get repo parts
  95. */
  96. app.get('/parts/:repoSlug', getPartsRepo);
  97. /**
  98. * Get example parts
  99. */
  100. app.get('/parts/:repoSlug/:exampleSlug', getPartsExample);
  101. /**
  102. * Index page: render with only repo list in menu
  103. */
  104. app.get('/', getIndexBare);
  105. /**
  106. * Index page: render for tests
  107. */
  108. // if(isTesting) {
  109. // app.get('/test', getIndexTest);
  110. // }
  111. /**
  112. * Repo page: render with repo list and selected repo's example list in menu
  113. */
  114. app.get('/:repoSlug', getIndexRepo);
  115. /**
  116. * Example page: render with repo list and selected repo's example list in menu,
  117. * and the editor with the selected example
  118. */
  119. app.get('/:repoSlug/:exampleSlug', getIndexExample);
  120. function checkRepoExists(req, res, next) {
  121. const { repoSlug } = req.params;
  122. console.log('### checkRepoExists', repoSlug);
  123. // Get repo from store
  124. req.repo = exStore.getRepo(repoSlug);
  125. if(! req.repo) {
  126. return res.status(404).send("Repo " + repoSlug + "not found");
  127. }
  128. next();
  129. }
  130. /**
  131. * Create a new repo
  132. */
  133. app.post('/repos', function(req, res) {
  134. // Check for title and extract params
  135. if(! req.body || ! req.body.title) {
  136. res.status(400).send('Le titre ne peut pas être vide !');
  137. }
  138. const { title } = req.body;
  139. const repoSlug = slug(title.toLowerCase());
  140. const existingRepo = exStore.getRepo(repoSlug);
  141. // Prevent duplicate title
  142. if(existingRepo) {
  143. return res.status(409).send("La collection '" + title + "' existe déjà !");
  144. }
  145. // Prepare config
  146. var config = Object.assign({
  147. title
  148. }, repoTmpl);
  149. exStore.addRepository(repoSlug, config)
  150. .then(repo => res.json(config));
  151. });
  152. app.post('/:repoSlug/examples/:exampleSlug/file',
  153. checkRepoExists,
  154. checkBodyPropsExist('name'),
  155. function(req, res) {
  156. const { name } = req.body;
  157. const { repoSlug, exampleSlug } = req.params;
  158. const re = /^[A-Za-z0-9_\-\.]+$/;
  159. const targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
  160. const fullPath = targetDir + '/' + name;
  161. if(! re.test(name)) {
  162. return res.status(400).json('Le paramètre `name` est incorrect: caractères autorisés: lettres, chiffres, _, - et .' );
  163. }
  164. if( ! checkFilename(name)) {
  165. return res.status(400).json("Le paramètre `name` est incorrect: il doit comporter un nom suivi d'une extension (.html, .js ou .css)" );
  166. }
  167. fs.statAsync(fullPath)
  168. // Invert the usual flow of a Promise. fs.stat() fails if file does not exist (which is what we want)
  169. // Hence .catch() is a success handler and .then() an error handler (has to rethrow)
  170. .then(stats => {
  171. throw new Error('Le fichier `' + name + '` existe déjà !');
  172. })
  173. .catch(err => {
  174. // Rethrow error if it is not a "file not found" thrown by fs.stat()
  175. if( ! err.message.startsWith('ENOENT') ) {
  176. throw err;
  177. }
  178. return fs.writeFileAsync(fullPath, '')
  179. .then(() => res.json({
  180. name,
  181. path: fullPath
  182. }));
  183. })
  184. .catch(err => {
  185. const statusCode = err.message.startsWith('Le fichier') ? 409 : 500;
  186. return res.status(statusCode).send(err.message);
  187. });
  188. }
  189. );
  190. /**
  191. * Create a new example for specified repo
  192. */
  193. app.post('/:repoSlug/examples',
  194. checkRepoExists,
  195. checkBodyPropsExist('title'),
  196. function(req, res) {
  197. const { title } = req.body;
  198. const { repoSlug } = req.params;
  199. // Prevent duplicate title
  200. var existingTitle = _.find(req.repo.examples, { title: title });
  201. if(existingTitle) {
  202. return res.status(409).send("L'exemple '" + title + "' existe déjà !");
  203. }
  204. var exampleSlug = slug(req.body.title.toLowerCase());
  205. // Prepare config
  206. var config = Object.assign({
  207. slug: exampleSlug,
  208. title,
  209. category: req.repo.defaultCategory
  210. }, exampleTmpl);
  211. // Prepare files to write
  212. var targetDir = examplesDir + '/' + repoSlug + '/' + exampleSlug;
  213. var files = mapObjToArray({
  214. 'example.html': '<!-- ' + title + ' -->\n',
  215. 'script.js': '// ' + title,
  216. 'config.json': beautify(config, null, 2, 100)
  217. }, 'file', 'content');
  218. fs.mkdirAsync(targetDir)
  219. .then(() => Promise.map(
  220. files, ({ file, content }) => fs.writeFileAsync(targetDir + '/' + file, content)
  221. ))
  222. .then(files => req.repo.examples.push(config))
  223. .then(() => res.json(config));
  224. }
  225. );
  226. app.get('/examples/:repoSlug/:slug',
  227. checkRepoExists,
  228. function(req, res) {
  229. const { repoSlug, slug } = req.params;
  230. var example = _.find(req.repo.examples, { slug });
  231. const { title, html, js, css, libsCss, libsJs } = example;
  232. console.log(example, title, html, js, css, libsCss, libsJs);
  233. readFileAsync(__dirname + '/exemples/' + repoSlug + '/' + slug + '/example.html')
  234. .then(body =>
  235. Mustache.render(sandboxTpml, { body, repoSlug, slug, title, js, css, libsCss, libsJs })
  236. )
  237. .then(html => res.send(html));
  238. }
  239. );
  240. app.get('/menu', (rea, res) => {
  241. res.send(exStore.getMenu());
  242. });
  243. app.get('/list/:repoPath', function(req, res) {
  244. const { repoPath } = req.params;
  245. const repo = exStore.getList(repoPath);
  246. if(! repo) {
  247. return res.status(404).send('Repo ' + repoPath + ' not found');
  248. }
  249. console.log('found repo', repo);
  250. const data = repo.examples.map(e => (
  251. { slug: e.slug, title: e.title }
  252. ));
  253. res.json(data);
  254. });
  255. app.put('/examples/:slug', function(req, res) {
  256. var slug = req.params.slug;
  257. var existing = _.find(examples, { slug: slug });
  258. if(! existing) {
  259. res.status(404).send("L'exemple avec l'identifiant '" + slug + "' est introuvable !");
  260. }
  261. var targetDir = __dirname + '/exemples/' + slug;
  262. if(req.body.html) {
  263. fs.writeFileSync(targetDir + '/contenu.html', req.body.html);
  264. }
  265. if(req.body.javascript) {
  266. fs.writeFileSync(targetDir + '/script.js', req.body.javascript);
  267. }
  268. var theDate = new Date();
  269. console.log(theDate.getHours() + ':' + theDate.getMinutes() + " - Sauvegarde de l'exemple '" + existing.title + " effectuée'");
  270. res.json({ success: true });
  271. });
  272. module.exports = app;