webshot.js 9.5 KB

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