webshot.ts 7.6 KB

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