webshot.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const CallableInstance = require("callable-instance");
  4. const https = require("https");
  5. const log4js = require("log4js");
  6. const pngjs_1 = require("pngjs");
  7. const puppeteer = require("puppeteer");
  8. const read = require("read-all-stream");
  9. const logger = log4js.getLogger('webshot');
  10. logger.level = global.loglevel;
  11. class Webshot extends CallableInstance {
  12. constructor(onready) {
  13. super('webshot');
  14. this.renderWebshot = (url, height, webshotDelay) => {
  15. const promise = new Promise(resolve => {
  16. const width = 1080;
  17. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  18. this.browser.newPage()
  19. .then(page => {
  20. page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  21. .then(() => page.setViewport({
  22. width,
  23. height,
  24. isMobile: true,
  25. }))
  26. .then(() => page.setBypassCSP(true))
  27. .then(() => page.goto(url))
  28. // hide header, "more options" button, like and retweet count
  29. .then(() => page.addStyleTag({
  30. content: 'html{zoom:2}header{display:none!important}path[d=\'M20.207 7.043a1 1 0 0 0-1.414 0L12 13.836 5.207 7.043a1 1 0 0 0-1.414 1.414l7.5 7.5a.996.996 0 0 0 1.414 0l7.5-7.5a1 1 0 0 0 0-1.414z\'],div[role=\'button\']{display: none;}',
  31. }))
  32. .then(() => page.waitFor(webshotDelay))
  33. .then(() => page.addScriptTag({
  34. content: 'document.documentElement.scrollTop=0;',
  35. }))
  36. .then(() => page.screenshot())
  37. .then(screenshot => {
  38. new pngjs_1.PNG({
  39. filterType: 4,
  40. }).on('parsed', function () {
  41. // remove comment area
  42. let boundary = null;
  43. let x = 0;
  44. for (let y = 0; y < this.height; y++) {
  45. const idx = (this.width * y + x) << 2;
  46. if (this.data[idx] !== 255) {
  47. boundary = y;
  48. break;
  49. }
  50. }
  51. if (boundary !== null) {
  52. logger.info(`found boundary at ${boundary}, cropping image`);
  53. this.data = this.data.slice(0, (this.width * boundary) << 2);
  54. this.height = boundary;
  55. boundary = null;
  56. x = Math.floor(this.width / 2);
  57. let flag = false;
  58. let cnt = 0;
  59. for (let y = this.height - 1; y >= 0; y--) {
  60. const idx = (this.width * y + x) << 2;
  61. if ((this.data[idx] === 255) === flag) {
  62. cnt++;
  63. flag = !flag;
  64. }
  65. else
  66. continue;
  67. // line above the "comment", "retweet", "like", "share" button row
  68. if (cnt === 2) {
  69. boundary = y + 1;
  70. }
  71. // if there are a "retweet" count and "like" count row, this will be the line above it
  72. if (cnt === 4) {
  73. const b = y + 1;
  74. if (this.height - b <= 200)
  75. boundary = b;
  76. break;
  77. }
  78. }
  79. if (boundary != null) {
  80. logger.info(`found boundary at ${boundary}, trimming image`);
  81. this.data = this.data.slice(0, (this.width * boundary) << 2);
  82. this.height = boundary;
  83. }
  84. read(this.pack(), 'base64').then(data => {
  85. logger.info(`finished webshot for ${url}`);
  86. resolve({ data, boundary });
  87. });
  88. }
  89. else if (height >= 8 * 1920) {
  90. logger.warn('too large, consider as a bug, returning');
  91. read(this.pack(), 'base64').then(data => {
  92. logger.info(`finished webshot for ${url}`);
  93. resolve({ data, boundary: 0 });
  94. });
  95. }
  96. else {
  97. logger.info('unable to found boundary, try shooting a larger image');
  98. resolve({ data: '', boundary });
  99. }
  100. }).parse(screenshot);
  101. })
  102. .then(() => page.close());
  103. });
  104. });
  105. return promise.then(data => {
  106. if (data.boundary === null)
  107. return this.renderWebshot(url, height + 1920, webshotDelay);
  108. else
  109. return data.data;
  110. });
  111. };
  112. this.fetchImage = (url) => new Promise(resolve => {
  113. logger.info(`fetching ${url}`);
  114. https.get(url, res => {
  115. if (res.statusCode === 200) {
  116. read(res, 'base64').then(data => {
  117. logger.info(`successfully fetched ${url}`);
  118. resolve(data);
  119. });
  120. }
  121. else {
  122. logger.error(`failed to fetch ${url}: ${res.statusCode}`);
  123. resolve();
  124. }
  125. }).on('error', (err) => {
  126. logger.error(`failed to fetch ${url}: ${err.message}`);
  127. resolve();
  128. });
  129. });
  130. puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--lang=zh-CN,zh'] })
  131. .then(browser => this.browser = browser)
  132. .then(() => {
  133. logger.info('launched puppeteer browser');
  134. if (onready)
  135. onready();
  136. });
  137. }
  138. webshot(tweets, callback, webshotDelay) {
  139. let promise = new Promise(resolve => {
  140. resolve();
  141. });
  142. tweets.forEach(twi => {
  143. let cqstr = '';
  144. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  145. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  146. .then(base64Webshot => {
  147. if (base64Webshot)
  148. cqstr += `[CQ:image,file=base64://${base64Webshot}]`;
  149. });
  150. if (twi.extended_entities) {
  151. twi.extended_entities.media.forEach(media => {
  152. promise = promise.then(() => this.fetchImage(media.media_url_https))
  153. .then(base64Image => {
  154. if (base64Image)
  155. cqstr += `[CQ:image,file=base64://${base64Image}]`;
  156. });
  157. });
  158. }
  159. if (twi.entities && twi.entities.urls && twi.entities.urls.length) {
  160. promise = promise.then(() => {
  161. const urls = twi.entities.urls
  162. .filter(urlObj => urlObj.indices[0] < twi.display_text_range[1])
  163. .map(urlObj => urlObj.expanded_url);
  164. if (urls.length) {
  165. cqstr += '\n';
  166. cqstr += urls.join('\n');
  167. }
  168. });
  169. }
  170. promise.then(() => callback(cqstr, twi.full_text));
  171. });
  172. return promise;
  173. }
  174. }
  175. exports.default = Webshot;