apiController.js 11 KB

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