apiController.js 12 KB

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