webshot.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import axios from 'axios';
  2. import * as CallableInstance from 'callable-instance';
  3. import { createWriteStream, existsSync, mkdirSync } from 'fs';
  4. import { XmlEntities } from 'html-entities';
  5. import { MessageType } from 'mirai-ts';
  6. import Message from 'mirai-ts/dist/message';
  7. import { PNG } from 'pngjs';
  8. import * as puppeteer from 'puppeteer';
  9. import { Browser } from 'puppeteer';
  10. import { Stream } from 'stream';
  11. import { getLogger } from './loggers';
  12. const writeOutTo = async (path: string, data: PNG | Stream) => {
  13. await new Promise(resolve => data.pipe(createWriteStream(path)).on('close', resolve));
  14. return path;
  15. };
  16. const xmlEntities = new XmlEntities();
  17. const typeInZH = {
  18. photo: '[图片]',
  19. video: '[视频]',
  20. animated_gif: '[GIF]',
  21. };
  22. const logger = getLogger('webshot');
  23. const mkdirP = dir => { if (!existsSync(dir)) mkdirSync(dir, {recursive: true}); };
  24. const baseName = path => path.split(/[/\\]/).slice(-1)[0];
  25. type MessageChain = MessageType.MessageChain;
  26. class Webshot extends CallableInstance<[number], Promise<void>> {
  27. private browser: Browser;
  28. private outDir: string;
  29. private mode: number;
  30. constructor(outDir: string, mode: number, onready?: () => any) {
  31. super('webshot');
  32. mkdirP(this.outDir = outDir);
  33. // tslint:disable-next-line: no-conditional-assignment
  34. if (this.mode = mode) {
  35. onready();
  36. } else {
  37. puppeteer.launch({
  38. args: [
  39. '--no-sandbox',
  40. '--disable-setuid-sandbox',
  41. '--disable-dev-shm-usage',
  42. '--disable-accelerated-2d-canvas',
  43. '--no-first-run',
  44. '--no-zygote',
  45. '--single-process', // <- this one doesn't works in Windows
  46. '--disable-gpu',
  47. '--lang=ja-JP,ja',
  48. ]})
  49. .then(browser => this.browser = browser)
  50. .then(() => {
  51. logger.info('launched puppeteer browser');
  52. if (onready) onready();
  53. });
  54. }
  55. }
  56. private renderWebshot = (url: string, height: number, webshotDelay: number): Promise<string> => {
  57. const writeOutPic = (pic: PNG) => writeOutTo(`${this.outDir}/${url.replace(/[:\/]/g, '_')}.png`, pic);
  58. const promise = new Promise<{ data: string, boundary: null | number }>(resolve => {
  59. const width = 600;
  60. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  61. this.browser.newPage()
  62. .then(page => {
  63. page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  64. .then(() => page.setViewport({
  65. width,
  66. height,
  67. isMobile: true,
  68. }))
  69. .then(() => page.setBypassCSP(true))
  70. .then(() => page.goto(url, {waitUntil: 'load', timeout: 150000}))
  71. // hide header, "more options" button, like and retweet count
  72. .then(() => page.addStyleTag({
  73. content: '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;}',
  74. }))
  75. .then(() => page.waitFor(webshotDelay))
  76. .then(() => page.addScriptTag({
  77. content: 'document.documentElement.scrollTop=0;',
  78. }))
  79. .then(() => page.screenshot())
  80. .then(screenshot => {
  81. new PNG({
  82. filterType: 4,
  83. }).on('parsed', function () {
  84. // remove comment area
  85. let boundary = null;
  86. let x = 0;
  87. for (let y = 0; y < this.height; y++) {
  88. const idx = (this.width * y + x) << 2;
  89. if (this.data[idx] !== 255) {
  90. boundary = y;
  91. break;
  92. }
  93. }
  94. if (boundary !== null) {
  95. logger.info(`found boundary at ${boundary}, cropping image`);
  96. this.data = this.data.slice(0, (this.width * boundary) << 2);
  97. this.height = boundary;
  98. boundary = null;
  99. x = Math.floor(this.width / 2);
  100. let flag = false;
  101. let cnt = 0;
  102. for (let y = this.height - 1; y >= 0; y--) {
  103. const idx = (this.width * y + x) << 2;
  104. if ((this.data[idx] === 255) === flag) {
  105. cnt++;
  106. flag = !flag;
  107. } else continue;
  108. // line above the "comment", "retweet", "like", "share" button row
  109. if (cnt === 6) {
  110. boundary = y + 1;
  111. }
  112. // if there are a "retweet" count and "like" count row, this will be the line above it
  113. if (cnt === 8) {
  114. const b = y + 1;
  115. if (this.height - b <= 200) boundary = b;
  116. break;
  117. }
  118. }
  119. if (boundary != null) {
  120. logger.info(`found boundary at ${boundary}, trimming image`);
  121. this.data = this.data.slice(0, (this.width * boundary) << 2);
  122. this.height = boundary;
  123. }
  124. writeOutPic(this.pack()).then(data => {
  125. logger.info(`finished webshot for ${url}`);
  126. resolve({data, boundary});
  127. });
  128. } else if (height >= 8 * 1920) {
  129. logger.warn('too large, consider as a bug, returning');
  130. writeOutPic(this.pack()).then(data => {
  131. resolve({data, boundary: 0});
  132. });
  133. } else {
  134. logger.info('unable to find boundary, try shooting a larger image');
  135. resolve({data: '', boundary});
  136. }
  137. }).parse(screenshot);
  138. })
  139. .then(() => page.close());
  140. });
  141. });
  142. return promise.then(data => {
  143. if (data.boundary === null) return this.renderWebshot(url, height + 1920, webshotDelay);
  144. else return data.data;
  145. });
  146. }
  147. private fetchImage = (url: string, tag: string): Promise<string> =>
  148. new Promise<Stream>(resolve => {
  149. logger.info(`fetching ${url}`);
  150. axios({
  151. method: 'get',
  152. url,
  153. responseType: 'stream',
  154. }).then(res => {
  155. if (res.status === 200) {
  156. logger.info(`successfully fetched ${url}`);
  157. resolve(res.data);
  158. } else {
  159. logger.error(`failed to fetch ${url}: ${res.status}`);
  160. resolve();
  161. }
  162. }).catch (err => {
  163. logger.error(`failed to fetch ${url}: ${err.message}`);
  164. resolve();
  165. });
  166. }).then(data => writeOutTo(`${this.outDir}/${tag}${baseName(url)}`, data))
  167. public webshot(
  168. tweets,
  169. callback: (msgs: MessageChain, text: string, author: string) => void,
  170. webshotDelay: number
  171. ): Promise<void> {
  172. let promise = new Promise<void>(resolve => {
  173. resolve();
  174. });
  175. tweets.forEach(twi => {
  176. promise = promise.then(() => {
  177. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  178. });
  179. const originTwi = twi.retweeted_status || twi;
  180. const messageChain: MessageChain = [];
  181. // text processing
  182. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  183. if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
  184. let text = originTwi.full_text;
  185. promise = promise.then(() => {
  186. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  187. originTwi.entities.urls.forEach(url => {
  188. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  189. });
  190. }
  191. if (originTwi.extended_entities) {
  192. originTwi.extended_entities.media.forEach(media => {
  193. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  194. });
  195. }
  196. if (this.mode > 0) messageChain.push(Message.Plain(author + xmlEntities.decode(text)));
  197. });
  198. // invoke webshot
  199. if (this.mode === 0) {
  200. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  201. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  202. .then(webshotFilePath => {
  203. if (webshotFilePath) messageChain.push(Message.Image('', '', baseName(webshotFilePath)));
  204. });
  205. // fetch extra images
  206. } else if (1 - this.mode % 2) {
  207. if (originTwi.extended_entities) {
  208. promise = promise.then(() => originTwi.extended_entities.media.forEach(media => {
  209. this.fetchImage(media.media_url_https, `${twi.user.screen_name}-${twi.id_str}--`)
  210. .then(path =>
  211. messageChain.push(Message.Image('', '', baseName(path)))
  212. );
  213. }));
  214. }
  215. // append URLs, if any
  216. } else if (this.mode === 0) {
  217. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  218. promise = promise.then(() => {
  219. const urls = originTwi.entities.urls
  220. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  221. .map(urlObj => urlObj.expanded_url);
  222. if (urls.length) {
  223. messageChain.push(Message.Plain(urls.join('\n')));
  224. }
  225. });
  226. }
  227. }
  228. promise.then(() => {
  229. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  230. logger.info(JSON.stringify(messageChain));
  231. callback(messageChain, text, author);
  232. });
  233. });
  234. return promise;
  235. }
  236. }
  237. export default Webshot;