apiController.js 12 KB

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