apiController.js 12 KB

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