lottiecap.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * Command line application to build a 5x5 filmstrip from a Lottie file in the
  3. * browser and then exporting that filmstrip in a 1000x1000 PNG.
  4. *
  5. */
  6. const puppeteer = require('puppeteer');
  7. const express = require('express');
  8. const fs = require('fs');
  9. const commandLineArgs = require('command-line-args');
  10. const commandLineUsage= require('command-line-usage');
  11. const fetch = require('node-fetch');
  12. // Valid values for the --renderer flag.
  13. const RENDERERS = ['svg', 'canvas'];
  14. const opts = [
  15. {
  16. name: 'input',
  17. typeLabel: '{underline file}',
  18. description: 'The Lottie JSON file to process.'
  19. },
  20. {
  21. name: 'output',
  22. typeLabel: '{underline file}',
  23. description: 'The captured filmstrip PNG file to write. Defaults to filmstrip.png',
  24. },
  25. {
  26. name: 'renderer',
  27. typeLabel: '{underline mode}',
  28. description: 'Which renderer to use, "svg" or "canvas". Defaults to "svg".',
  29. },
  30. {
  31. name: 'port',
  32. description: 'The port number to use, defaults to 8081.',
  33. type: Number,
  34. },
  35. {
  36. name: 'lottie_player',
  37. description: 'The path to lottie.min.js, defaults to a local npm install location.',
  38. type: String,
  39. },
  40. {
  41. name: 'post_to',
  42. description: 'If set, the url to post results to for Gold Ingestion.',
  43. type: String,
  44. },
  45. {
  46. name: 'in_docker',
  47. description: 'Is this being run in docker, defaults to false',
  48. type: Boolean,
  49. },
  50. {
  51. name: 'skip_automation',
  52. description: 'If the automation of the screenshot taking should be skipped ' +
  53. '(e.g. debugging). Defaults to false.',
  54. type: Boolean,
  55. },
  56. {
  57. name: 'help',
  58. alias: 'h',
  59. type: Boolean,
  60. description: 'Print this usage guide.'
  61. },
  62. ];
  63. const usage = [
  64. {
  65. header: 'Lottie Filmstrip Capture',
  66. content: `Command line application to build a 5x5 filmstrip
  67. from a Lottie file in the browser and then export
  68. that filmstrip in a 1000x1000 PNG.`
  69. },
  70. {
  71. header: 'Options',
  72. optionList: opts,
  73. },
  74. ];
  75. // Parse and validate flags.
  76. const options = commandLineArgs(opts);
  77. if (!options.output) {
  78. options.output = 'filmstrip.png';
  79. }
  80. if (!options.port) {
  81. options.port = 8081;
  82. }
  83. if (!options.lottie_player) {
  84. options.lottie_player = 'node_modules/lottie-web/build/player/lottie.min.js';
  85. }
  86. if (options.help) {
  87. console.log(commandLineUsage(usage));
  88. process.exit(0);
  89. }
  90. if (!options.input) {
  91. console.error('You must supply a Lottie JSON filename.');
  92. console.log(commandLineUsage(usage));
  93. process.exit(1);
  94. }
  95. if (!options.renderer) {
  96. options.renderer = 'svg';
  97. }
  98. if (!RENDERERS.includes(options.renderer)) {
  99. console.error('The --renderer flag must have as a value one of: ', RENDERERS);
  100. console.log(commandLineUsage(usage));
  101. process.exit(1);
  102. }
  103. // Start up a web server to serve the three files we need.
  104. let lottieJS = fs.readFileSync(options.lottie_player, 'utf8');
  105. let driverHTML = fs.readFileSync('driver.html', 'utf8');
  106. let lottieJSON = fs.readFileSync(options.input, 'utf8');
  107. const app = express();
  108. app.get('/', (req, res) => res.send(driverHTML));
  109. app.get('/lottie.js', (req, res) => res.send(lottieJS));
  110. app.get('/lottie.json', (req, res) => res.send(lottieJSON));
  111. app.listen(options.port, () => console.log('- Local web server started.'))
  112. // Utiltity function.
  113. async function wait(ms) {
  114. await new Promise(resolve => setTimeout(() => resolve(), ms));
  115. return ms;
  116. }
  117. const targetURL = `http://localhost:${options.port}/#${options.renderer}`;
  118. // Drive chrome to load the web page from the server we have running.
  119. async function driveBrowser() {
  120. console.log('- Launching chrome in headless mode.');
  121. let browser = null;
  122. if (options.in_docker) {
  123. browser = await puppeteer.launch({
  124. 'executablePath': '/usr/bin/google-chrome-stable',
  125. 'args': ['--no-sandbox'],
  126. });
  127. } else {
  128. browser = await puppeteer.launch();
  129. }
  130. const page = await browser.newPage();
  131. console.log(`- Loading our Lottie exercising page for ${options.input}.`);
  132. try {
  133. // 20 seconds is plenty of time to wait for the json to be loaded once
  134. // This usually times out for super large json.
  135. await page.goto(targetURL, {
  136. timeout: 20000,
  137. waitUntil: 'networkidle0'
  138. });
  139. // 20 seconds is plenty of time to wait for the frames to be drawn.
  140. // This usually times out for json that causes errors in the player.
  141. console.log('- Waiting 15s for all the tiles to be drawn.');
  142. await page.waitForFunction('window._tileCount === 25', {
  143. timeout: 20000,
  144. });
  145. } catch(e) {
  146. console.log('Timed out while loading or drawing. Either the JSON file was ' +
  147. 'too big or hit a bug in the player.', e);
  148. await browser.close();
  149. process.exit(0);
  150. }
  151. console.log('- Taking screenshot.');
  152. let encoding = 'binary';
  153. if (options.post_to) {
  154. encoding = 'base64';
  155. // prevent writing the image to disk
  156. options.output = '';
  157. }
  158. // See https://github.com/GoogleChrome/puppeteer/blob/v1.6.0/docs/api.md#pagescreenshotoptions
  159. let result = await page.screenshot({
  160. path: options.output,
  161. type: 'png',
  162. clip: {
  163. x: 0,
  164. y: 0,
  165. width: 1000,
  166. height: 1000,
  167. },
  168. encoding: encoding,
  169. });
  170. if (options.post_to) {
  171. console.log(`- Reporting ${options.input} to Gold server ${options.post_to}`);
  172. let shortenedName = options.input;
  173. let lastSlash = shortenedName.lastIndexOf('/');
  174. if (lastSlash !== -1) {
  175. shortenedName = shortenedName.slice(lastSlash+1);
  176. }
  177. await fetch(options.post_to, {
  178. method: 'POST',
  179. mode: 'no-cors',
  180. headers: {
  181. 'Content-Type': 'application/json',
  182. },
  183. body: JSON.stringify({
  184. 'data': result,
  185. 'test_name': shortenedName,
  186. })
  187. });
  188. }
  189. await browser.close();
  190. // Need to call exit() because the web server is still running.
  191. process.exit(0);
  192. }
  193. if (!options.skip_automation) {
  194. driveBrowser();
  195. } else {
  196. console.log(`open ${targetURL} to see the animation.`)
  197. }