apiController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. proxy: req.body.proxy || null,
  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. console.log('Launching test ' + run.runId + ' on ' + run.params.url);
  57. var runOptions = {
  58. screenshot: run.params.screenshot ? screenshot.getTmpFilePath() : false,
  59. device: run.params.device,
  60. proxy: run.params.proxy,
  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. // Here we can remove tools results if not needed
  104. return resultsDatastore.saveResult(data);
  105. })
  106. // Mark as the run as complete and send the response if the request is still waiting
  107. .then(function() {
  108. debug('Result saved in datastore');
  109. runsDatastore.markAsComplete(run.runId);
  110. if (run.params.waitForResponse) {
  111. // If the user only wants a portion of the result (partialResult option)
  112. switch(run.params.partialResult) {
  113. case 'generalScores':
  114. res.redirect(302, '/api/results/' + run.runId + '/generalScores');
  115. break;
  116. case 'rules':
  117. res.redirect(302, '/api/results/' + run.runId + '/rules');
  118. break;
  119. case 'javascriptExecutionTree':
  120. res.redirect(302, '/api/results/' + run.runId + '/javascriptExecutionTree');
  121. break;
  122. case 'phantomas':
  123. res.redirect(302, '/api/results/' + run.runId + '/toolsResults/phantomas');
  124. break;
  125. default:
  126. res.redirect(302, '/api/results/' + run.runId);
  127. }
  128. }
  129. })
  130. .fail(function(err) {
  131. console.error('Test failed for URL: %s', run.params.url);
  132. console.error(err.toString());
  133. runsDatastore.markAsFailed(run.runId, err.toString());
  134. res.status(500).send('An error occured');
  135. });
  136. })
  137. .fail(function(err) {
  138. console.error('Test failed for URL: %s', run.params.url);
  139. console.error(err.toString());
  140. runsDatastore.markAsFailed(run.runId, err.toString());
  141. res.status(400).send('Bad request');
  142. })
  143. .finally(function() {
  144. queue.remove(run.runId);
  145. });
  146. // The user doesn't want to wait for the response, sending the run ID only
  147. if (!run.params.waitForResponse) {
  148. debug('Sending response without waiting.');
  149. res.setHeader('Content-Type', 'application/json');
  150. res.send(JSON.stringify({runId: run.runId}));
  151. }
  152. });
  153. // Retrive one run by id
  154. app.get('/api/runs/:id', function(req, res) {
  155. var runId = req.params.id;
  156. var run = runsDatastore.get(runId);
  157. if (run) {
  158. res.setHeader('Content-Type', 'application/json');
  159. res.send(JSON.stringify(run, null, 2));
  160. } else {
  161. res.status(404).send('Not found');
  162. }
  163. });
  164. // Retrieve the list of all runs
  165. /*app.get('/api/runs', function(req, res) {
  166. // NOT YET
  167. });*/
  168. // Delete one run by id
  169. /*app.delete('/api/runs/:id', function(req, res) {
  170. deleteRun()
  171. });*/
  172. // Delete all
  173. /*app.delete('/api/runs', function(req, res) {
  174. purgeRuns()
  175. });
  176. // List all
  177. app.get('/api/runs', function(req, res) {
  178. listRuns()
  179. });
  180. // Exists
  181. app.head('/api/runs/:id', function(req, res) {
  182. existsX();
  183. // Returns 200 if the result exists or 404 if not
  184. });
  185. */
  186. // Retrive one result by id
  187. app.get('/api/results/:id', function(req, res) {
  188. getPartialResults(req.params.id, res, function(data) {
  189. // Some fields can be excluded from the response, this way:
  190. // /api/results/:id?exclude=field1,field2
  191. if (req.query.exclude && typeof req.query.exclude === 'string') {
  192. var excludedFields = req.query.exclude.split(',');
  193. excludedFields.forEach(function(fieldName) {
  194. if (data[fieldName]) {
  195. delete data[fieldName];
  196. }
  197. });
  198. }
  199. return data;
  200. });
  201. });
  202. // Retrieve one result and return only the generalScores part of the response
  203. app.get('/api/results/:id/generalScores', function(req, res) {
  204. getPartialResults(req.params.id, res, function(data) {
  205. return data.scoreProfiles.generic;
  206. });
  207. });
  208. app.get('/api/results/:id/generalScores/:scoreProfile', function(req, res) {
  209. getPartialResults(req.params.id, res, function(data) {
  210. return data.scoreProfiles[req.params.scoreProfile];
  211. });
  212. });
  213. app.get('/api/results/:id/rules', function(req, res) {
  214. getPartialResults(req.params.id, res, function(data) {
  215. return data.rules;
  216. });
  217. });
  218. app.get('/api/results/:id/javascriptExecutionTree', function(req, res) {
  219. getPartialResults(req.params.id, res, function(data) {
  220. return data.javascriptExecutionTree;
  221. });
  222. });
  223. app.get('/api/results/:id/toolsResults/phantomas', function(req, res) {
  224. getPartialResults(req.params.id, res, function(data) {
  225. return data.toolsResults.phantomas;
  226. });
  227. });
  228. function getPartialResults(runId, res, partialGetterFn) {
  229. resultsDatastore.getResult(runId)
  230. .then(function(data) {
  231. var results = partialGetterFn(data);
  232. if (typeof results === 'undefined') {
  233. res.status(404).send('Not found');
  234. return;
  235. }
  236. res.setHeader('Content-Type', 'application/json');
  237. res.send(JSON.stringify(results, null, 2));
  238. }).fail(function() {
  239. res.status(404).send('Not found');
  240. });
  241. }
  242. // Retrive one result by id
  243. app.get('/api/results/:id/screenshot.jpg', function(req, res) {
  244. var runId = req.params.id;
  245. resultsDatastore.getScreenshot(runId)
  246. .then(function(screenshotBuffer) {
  247. res.setHeader('Content-Type', 'image/jpeg');
  248. res.send(screenshotBuffer);
  249. }).fail(function() {
  250. res.status(404).send('Not found');
  251. });
  252. });
  253. };
  254. module.exports = ApiController;