launchTestController.js 2.6 KB

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