apiController.js 11 KB

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