apiController.js 9.5 KB

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