apiController.js 12 KB

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