apiController.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. var debug = require('debug')('ylt:server');
  2. var Q = require('q');
  3. var ylt = require('../../index');
  4. var ScreenshotHandler = require('../../screenshotHandler');
  5. var RunsQueue = require('../datastores/runsQueue');
  6. var RunsDatastore = require('../datastores/runsDatastore');
  7. var ResultsDatastore = require('../datastores/resultsDatastore');
  8. var ApiController = function(app) {
  9. 'use strict';
  10. var queue = new RunsQueue();
  11. var runsDatastore = new RunsDatastore();
  12. var resultsDatastore = new ResultsDatastore();
  13. // Create a new run
  14. app.post('/api/runs', function(req, res) {
  15. // Grab the test parameters and generate a random run ID
  16. var run = {
  17. runId: (Date.now()*1000 + Math.round(Math.random()*1000)).toString(36),
  18. params: {
  19. url: req.body.url,
  20. waitForResponse: req.body.waitForResponse !== false && req.body.waitForResponse !== 'false' && req.body.waitForResponse !== 0,
  21. partialResult: req.body.partialResult || null,
  22. screenshot: req.body.screenshot || false
  23. }
  24. };
  25. // Create a temporary folder to save the screenshot
  26. var screenshot;
  27. if (run.params.screenshot) {
  28. screenshot = ScreenshotHandler.getScreenshotTempFile();
  29. }
  30. // Add test to the testQueue
  31. debug('Adding test %s to the queue', run.runId);
  32. var queuePromise = queue.push(run.runId);
  33. // Save the run to the datastore
  34. runsDatastore.add(run, queuePromise.startingPosition);
  35. // Listening for position updates
  36. queuePromise.progress(function(position) {
  37. runsDatastore.updatePosition(run.runId, position);
  38. });
  39. // Let's start the run
  40. queuePromise.then(function() {
  41. runsDatastore.updatePosition(run.runId, 0);
  42. debug('Launching test %s on %s', run.runId, run.params.url);
  43. var runOptions = {
  44. screenshot: run.params.screenshot ? screenshot.getTmpFilePath() : false
  45. };
  46. return ylt(run.params.url, runOptions);
  47. })
  48. // Phantomas completed, let's save the screenshot if any
  49. .then(function(data) {
  50. debug('Success');
  51. data.runId = run.runId;
  52. // Some conditional steps are made if there is a screenshot
  53. var screenshotPromise = Q.resolve();
  54. if (run.params.screenshot) {
  55. // Replace the empty promise created earlier with Q.resolve()
  56. screenshotPromise = screenshot.toThumbnail(600)
  57. // Read screenshot
  58. .then(function(screenshotBuffer) {
  59. if (screenshotBuffer) {
  60. debug('Image optimized');
  61. data.screenshotBuffer = screenshotBuffer;
  62. // Official path to get the image
  63. data.screenshotUrl = '/api/results/' + data.runId + '/screenshot.jpg';
  64. }
  65. })
  66. // Delete screenshot temporary file
  67. .then(screenshot.deleteTmpFile);
  68. }
  69. // Let's continue
  70. screenshotPromise
  71. // Save results
  72. .then(function() {
  73. delete data.params.options.screenshot;
  74. return resultsDatastore.saveResult(data);
  75. })
  76. // Mark as the run as complete and send the response if the request is still waiting
  77. .then(function() {
  78. debug('Result saved in datastore');
  79. runsDatastore.markAsComplete(run.runId);
  80. if (run.params.waitForResponse) {
  81. // If the user only wants a portion of the result (partialResult option)
  82. switch(run.params.partialResult) {
  83. case 'generalScores':
  84. res.redirect(302, '/api/results/' + run.runId + '/generalScores');
  85. break;
  86. case 'rules':
  87. res.redirect(302, '/api/results/' + run.runId + '/rules');
  88. break;
  89. case 'javascriptExecutionTree':
  90. res.redirect(302, '/api/results/' + run.runId + '/javascriptExecutionTree');
  91. break;
  92. case 'phantomas':
  93. res.redirect(302, '/api/results/' + run.runId + '/toolsResults/phantomas');
  94. break;
  95. default:
  96. res.redirect(302, '/api/results/' + run.runId);
  97. }
  98. }
  99. })
  100. .fail(function(err) {
  101. console.error('Test failed for URL: %s', run.params.url);
  102. console.error(err.toString());
  103. runsDatastore.markAsFailed(run.runId, err.toString());
  104. res.status(500).send('An error occured');
  105. });
  106. })
  107. .fail(function(err) {
  108. console.error('Test failed for URL: %s', run.params.url);
  109. console.error(err.toString());
  110. runsDatastore.markAsFailed(run.runId, err.toString());
  111. res.status(400).send('Bad request');
  112. })
  113. .finally(function() {
  114. queue.remove(run.runId);
  115. });
  116. // The user doesn't want to wait for the response, sending the run ID only
  117. if (!run.params.waitForResponse) {
  118. console.log('Sending response without waiting.');
  119. res.setHeader('Content-Type', 'application/json');
  120. res.send(JSON.stringify({runId: run.runId}));
  121. }
  122. });
  123. // Retrive one run by id
  124. app.get('/api/runs/:id', function(req, res) {
  125. var runId = req.params.id;
  126. var run = runsDatastore.get(runId);
  127. if (run) {
  128. res.setHeader('Content-Type', 'application/json');
  129. res.send(JSON.stringify(run, null, 2));
  130. } else {
  131. res.status(404).send('Not found');
  132. }
  133. });
  134. // Retrieve the list of all runs
  135. /*app.get('/api/runs', function(req, res) {
  136. // NOT YET
  137. });*/
  138. // Delete one run by id
  139. /*app.delete('/api/runs/:id', function(req, res) {
  140. deleteRun()
  141. });*/
  142. // Delete all
  143. /*app.delete('/api/runs', function(req, res) {
  144. purgeRuns()
  145. });
  146. // List all
  147. app.get('/api/runs', function(req, res) {
  148. listRuns()
  149. });
  150. // Exists
  151. app.head('/api/runs/:id', function(req, res) {
  152. existsX();
  153. // Returns 200 if the result exists or 404 if not
  154. });
  155. */
  156. // Retrive one result by id
  157. app.get('/api/results/:id', function(req, res) {
  158. getPartialResults(req.params.id, res, function(data) {
  159. return data;
  160. });
  161. });
  162. // Retrieve one result and return only the generalScores part of the response
  163. app.get('/api/results/:id/generalScores', function(req, res) {
  164. getPartialResults(req.params.id, res, function(data) {
  165. return data.scoreProfiles.generic;
  166. });
  167. });
  168. app.get('/api/results/:id/generalScores/:scoreProfile', function(req, res) {
  169. getPartialResults(req.params.id, res, function(data) {
  170. return data.scoreProfiles[req.params.scoreProfile];
  171. });
  172. });
  173. app.get('/api/results/:id/rules', function(req, res) {
  174. getPartialResults(req.params.id, res, function(data) {
  175. return data.rules;
  176. });
  177. });
  178. app.get('/api/results/:id/javascriptExecutionTree', function(req, res) {
  179. getPartialResults(req.params.id, res, function(data) {
  180. return data.javascriptExecutionTree;
  181. });
  182. });
  183. app.get('/api/results/:id/toolsResults/phantomas', function(req, res) {
  184. getPartialResults(req.params.id, res, function(data) {
  185. return data.toolsResults.phantomas;
  186. });
  187. });
  188. function getPartialResults(runId, res, partialGetterFn) {
  189. resultsDatastore.getResult(runId)
  190. .then(function(data) {
  191. var results = partialGetterFn(data);
  192. if (typeof results === 'undefined') {
  193. res.status(404).send('Not found');
  194. return;
  195. }
  196. res.setHeader('Content-Type', 'application/json');
  197. res.send(JSON.stringify(results, null, 2));
  198. }).fail(function() {
  199. res.status(404).send('Not found');
  200. });
  201. }
  202. // Retrive one result by id
  203. app.get('/api/results/:id/screenshot.jpg', function(req, res) {
  204. var runId = req.params.id;
  205. resultsDatastore.getScreenshot(runId)
  206. .then(function(screenshotBuffer) {
  207. res.setHeader('Content-Type', 'image/jpeg');
  208. res.send(screenshotBuffer);
  209. }).fail(function() {
  210. res.status(404).send('Not found');
  211. });
  212. });
  213. };
  214. module.exports = ApiController;