launchTestController.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * Controller for the test launching page (the waiting page, after the user submited a test on the index page)
  3. */
  4. var async = require('async');
  5. var fs = require ('fs');
  6. var launchTestController = function(req, res, testQueue, googleAnalyticsId) {
  7. 'use strict';
  8. // Generate test id
  9. var testId = (Date.now()*1000 + Math.round(Math.random()*1000)).toString(36);
  10. var resultsPath = 'results/' + testId;
  11. var phantomasResultsPath = resultsPath + '/results.json';
  12. var url = req.body.url;
  13. if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
  14. url = 'http://' + url;
  15. }
  16. var options = {};
  17. if (req.body.timeout) {
  18. options.timeout = req.body.timeout;
  19. }
  20. async.waterfall([
  21. function htmlTemplate(callback) {
  22. fs.readFile('./app/node_views/launchTest.html', {encoding: 'utf8'}, callback);
  23. },
  24. function sendResponse(html, callback) {
  25. html = html.replace('%%TEST_URL%%', url);
  26. html = html.replace('%%TEST_ID%%', testId);
  27. html = html.replace('%%GA_ID%%', googleAnalyticsId);
  28. res.setHeader('Content-Type', 'text/html');
  29. res.send(html);
  30. callback();
  31. },
  32. function createFolder(callback) {
  33. // Create results folder
  34. fs.mkdir(resultsPath, callback);
  35. },
  36. function executePhantomas(callback) {
  37. console.log('Adding test ' + testId + ' on ' + url + ' to the queue');
  38. var task = {
  39. testId: testId,
  40. url: url,
  41. options: options
  42. };
  43. testQueue.push(task, callback);
  44. },
  45. function writeResults(json, resultsObject, callback) {
  46. console.log('Saving Phantomas results file to ' + phantomasResultsPath);
  47. fs.writeFile(phantomasResultsPath, JSON.stringify(json, null, 4), callback);
  48. }
  49. ], function(err) {
  50. if (err) {
  51. console.log('An error occured in the phantomas test: ', err);
  52. fs.writeFile(phantomasResultsPath, JSON.stringify({url: url, error: err}, null, 4), function(err) {
  53. if (err) {
  54. console.log('Could not even write an error message on file ' + phantomasResultsPath);
  55. console.log(err);
  56. }
  57. });
  58. testQueue.testFailed(testId);
  59. } else {
  60. testQueue.testComplete(testId);
  61. }
  62. });
  63. };
  64. module.exports = launchTestController;