apiController.js 10.0 KB

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