webshot.ts 8.9 KB

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