webshot.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const log4js = require("log4js");
  4. const webshot = require("webshot");
  5. const read = require("read-all-stream");
  6. const pngjs_1 = require("pngjs");
  7. const logger = log4js.getLogger('webshot');
  8. logger.level = 'info';
  9. function renderWebshot(url, height) {
  10. let promise = new Promise(resolve => {
  11. const options = {
  12. windowSize: {
  13. width: 1080,
  14. height: height,
  15. },
  16. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  17. renderDelay: 5000,
  18. quality: 100,
  19. customCSS: 'html{zoom:2}header{display:none!important}',
  20. };
  21. logger.info(`shooting ${options.windowSize.width}*${height} webshot for ${url}`);
  22. webshot(url, options).pipe(new pngjs_1.PNG({
  23. filterType: 4
  24. }))
  25. .on('parsed', function () {
  26. let boundary = null;
  27. for (let y = 0; y < this.height; y++) {
  28. const x = 0;
  29. let idx = (this.width * y + x) << 2;
  30. if (this.data[idx] !== 255) {
  31. boundary = y;
  32. break;
  33. }
  34. }
  35. if (boundary !== null) {
  36. logger.info(`found boundary at ${boundary}, cropping image`);
  37. this.data = this.data.slice(0, (this.width * boundary) << 2);
  38. this.height = boundary;
  39. read(this.pack(), 'base64').then(data => {
  40. logger.info(`finished webshot for ${url}`);
  41. resolve({ data, boundary });
  42. });
  43. }
  44. else if (height >= 8 * 1920) {
  45. logger.warn(`too large, consider as a bug, returning`);
  46. read(this.pack(), 'base64').then(data => {
  47. logger.info(`finished webshot for ${url}`);
  48. resolve({ data, boundary: 0 });
  49. });
  50. }
  51. else {
  52. logger.info(`unable to found boundary, try shooting a larger image`);
  53. resolve({ data: '', boundary });
  54. }
  55. });
  56. });
  57. return promise.then(data => {
  58. if (data.boundary === null)
  59. return renderWebshot(url, height + 1920);
  60. else
  61. return data.data;
  62. });
  63. }
  64. /*function fetchImage(): Promise<string> {
  65. }*/
  66. function default_1(twitter, callback) {
  67. twitter.forEach(twi => {
  68. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  69. renderWebshot(url, 1920)
  70. .then(base64Webshot => {
  71. console.log(base64Webshot);
  72. });
  73. });
  74. }
  75. exports.default = default_1;