webshot.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 { PNG } from 'pngjs';
  6. import * as puppeteer from 'puppeteer';
  7. import { Browser } from 'puppeteer';
  8. import * as sharp from 'sharp';
  9. import { Stream } from 'stream';
  10. import { getLogger } from './loggers';
  11. import { Message, MessageChain } from './mirai';
  12. import { Tweets } from './twitter';
  13. const writeOutTo = (path: string, data: Stream) =>
  14. new Promise<string>(resolve => {
  15. data.pipe(createWriteStream(path)).on('close', () => resolve(path));
  16. });
  17. const xmlEntities = new XmlEntities();
  18. const typeInZH = {
  19. photo: '[图片]',
  20. video: '[视频]',
  21. animated_gif: '[GIF]',
  22. };
  23. const logger = getLogger('webshot');
  24. const mkdirP = dir => { if (!existsSync(dir)) mkdirSync(dir, {recursive: true}); };
  25. const baseName = path => path.split(/[/\\]/).slice(-1)[0];
  26. class Webshot extends CallableInstance<[Tweets, (...args) => void, 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. this.connect(onready);
  38. }
  39. }
  40. // use local Chromium
  41. private connect = (onready) => puppeteer.connect({browserURL: 'http://127.0.0.1:9222'})
  42. .then(browser => this.browser = browser)
  43. .then(() => {
  44. logger.info('launched puppeteer browser');
  45. if (onready) return onready();
  46. })
  47. .catch(error => this.reconnect(error, onready))
  48. private reconnect = (error, onready?) => {
  49. logger.error(`connection error, reason: ${error}`);
  50. logger.warn('trying to reconnect in 2.5s...');
  51. return new Promise(resolve => setTimeout(resolve, 2500))
  52. .then(() => this.connect(onready));
  53. }
  54. private renderWebshot = (url: string, height: number, webshotDelay: number): Promise<string> => {
  55. const jpeg = (data: Stream) => data.pipe(sharp()).jpeg({quality: 90, trellisQuantisation: true});
  56. const writeOutPic = (pic: Stream) => writeOutTo(`${this.outDir}/${url.replace(/[:\/]/g, '_')}.jpg`, pic);
  57. const promise = new Promise<{ path: string, boundary: null | number }>((resolve, reject) => {
  58. const width = 720;
  59. const zoomFactor = 2;
  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: width / zoomFactor,
  66. height: height / zoomFactor,
  67. isMobile: true,
  68. deviceScaleFactor: zoomFactor,
  69. }))
  70. .then(() => page.setBypassCSP(true))
  71. .then(() => page.goto(url, {waitUntil: 'load', timeout: 150000}))
  72. // hide header, "more options" button, like and retweet count
  73. .then(() => page.addStyleTag({
  74. 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;}',
  75. }))
  76. .then(() => page.waitFor(webshotDelay))
  77. .then(() => page.addScriptTag({
  78. content: 'document.documentElement.scrollTop=0;',
  79. }))
  80. .then(() => page.screenshot())
  81. .then(screenshot => {
  82. new PNG({
  83. filterType: 4,
  84. deflateLevel: 0,
  85. }).on('parsed', function () {
  86. // remove comment area
  87. // tslint:disable-next-line: no-shadowed-variable
  88. const idx = (x: number, y: number) => (this.width * y + x) << 2;
  89. let boundary = null;
  90. let x = zoomFactor * 2;
  91. for (let y = 0; y < this.height; y++) {
  92. if (this.data[idx(x, y)] !== 255) {
  93. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  94. // footer kicks in
  95. boundary = null;
  96. } else {
  97. boundary = y;
  98. }
  99. break;
  100. }
  101. }
  102. if (boundary !== null) {
  103. logger.info(`found boundary at ${boundary}, cropping image`);
  104. this.data = this.data.slice(0, idx(this.width, boundary));
  105. this.height = boundary;
  106. boundary = null;
  107. x = Math.floor(16 * zoomFactor);
  108. let flag = false;
  109. let cnt = 0;
  110. for (let y = this.height - 1; y >= 0; y--) {
  111. if ((this.data[idx(x, y)] === 255) === flag) {
  112. cnt++;
  113. flag = !flag;
  114. } else continue;
  115. // line above the "comment", "retweet", "like", "share" button row
  116. if (cnt === 2) {
  117. boundary = y + 1;
  118. }
  119. // if there are a "retweet" count and "like" count row, this will be the line above it
  120. if (cnt === 4) {
  121. const b = y + 1;
  122. if (this.height - boundary - (boundary - b) <= 1) {
  123. boundary = b;
  124. // }
  125. // }
  126. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  127. // if (cnt === 6) {
  128. // const c = y + 1;
  129. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  130. // boundary = c;
  131. break;
  132. }
  133. }
  134. }
  135. if (boundary != null) {
  136. logger.info(`found boundary at ${boundary}, trimming image`);
  137. this.data = this.data.slice(0, idx(this.width, boundary));
  138. this.height = boundary;
  139. }
  140. writeOutPic(jpeg(this.pack())).then(path => {
  141. logger.info(`finished webshot for ${url}`);
  142. resolve({path, boundary});
  143. });
  144. } else if (height >= 8 * 1920) {
  145. logger.warn('too large, consider as a bug, returning');
  146. writeOutPic(jpeg(this.pack())).then(path => {
  147. resolve({path, boundary: 0});
  148. });
  149. } else {
  150. logger.info('unable to find boundary, try shooting a larger image');
  151. resolve({path: '', boundary});
  152. }
  153. }).parse(screenshot);
  154. })
  155. .then(() => page.close());
  156. })
  157. .catch(reject);
  158. });
  159. return promise.then(data => {
  160. if (data.boundary === null) return this.renderWebshot(url, height + 1920, webshotDelay);
  161. else return data.path;
  162. }).catch(error =>
  163. new Promise(resolve => this.reconnect(error, resolve))
  164. .then(() => this.renderWebshot(url, height, webshotDelay))
  165. );
  166. }
  167. private fetchImage = (url: string, tag: string): Promise<string> =>
  168. new Promise<Stream>(resolve => {
  169. logger.info(`fetching ${url}`);
  170. axios({
  171. method: 'get',
  172. url,
  173. responseType: 'stream',
  174. }).then(res => {
  175. if (res.status === 200) {
  176. logger.info(`successfully fetched ${url}`);
  177. resolve(res.data);
  178. } else {
  179. logger.error(`failed to fetch ${url}: ${res.status}`);
  180. resolve();
  181. }
  182. }).catch (err => {
  183. logger.error(`failed to fetch ${url}: ${err.message}`);
  184. resolve();
  185. });
  186. }).then(data => {
  187. const imgName = `${tag}${baseName(url.replace(/(\.[a-z]+):(.*)/, '$1__$2$1'))}`;
  188. return writeOutTo(`${this.outDir}/${imgName}`, data);
  189. })
  190. public webshot(
  191. tweets: Tweets,
  192. callback: (msgs: MessageChain, text: string, author: string) => void,
  193. webshotDelay: number
  194. ): Promise<void> {
  195. let promise = new Promise<void>(resolve => {
  196. resolve();
  197. });
  198. tweets.forEach(twi => {
  199. promise = promise.then(() => {
  200. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  201. });
  202. const originTwi = twi.retweeted_status || twi;
  203. const messageChain: MessageChain = [];
  204. // text processing
  205. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  206. if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
  207. let text = originTwi.full_text;
  208. promise = promise.then(() => {
  209. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  210. originTwi.entities.urls.forEach(url => {
  211. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  212. });
  213. }
  214. if (originTwi.extended_entities) {
  215. originTwi.extended_entities.media.forEach(media => {
  216. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  217. });
  218. }
  219. if (this.mode > 0) messageChain.push(Message.Plain(author + xmlEntities.decode(text)));
  220. });
  221. // invoke webshot
  222. if (this.mode === 0) {
  223. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  224. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  225. .then(webshotFilePath => {
  226. if (webshotFilePath) messageChain.push(Message.Image('', '', baseName(webshotFilePath)));
  227. });
  228. }
  229. // fetch extra images
  230. if (1 - this.mode % 2) {
  231. if (originTwi.extended_entities) {
  232. originTwi.extended_entities.media.forEach(media =>
  233. promise = promise.then(() =>
  234. this.fetchImage(media.media_url_https + ':orig', `${twi.user.screen_name}-${twi.id_str}--`)
  235. .then(path => {
  236. messageChain.push(Message.Image('', '', baseName(path)));
  237. })
  238. ));
  239. }
  240. }
  241. // append URLs, if any
  242. if (this.mode === 0) {
  243. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  244. promise = promise.then(() => {
  245. const urls = originTwi.entities.urls
  246. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  247. .map(urlObj => urlObj.expanded_url);
  248. if (urls.length) {
  249. messageChain.push(Message.Plain(urls.join('\n')));
  250. }
  251. });
  252. }
  253. }
  254. promise.then(() => {
  255. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  256. logger.info(JSON.stringify(messageChain));
  257. callback(messageChain, xmlEntities.decode(text), author);
  258. });
  259. });
  260. return promise;
  261. }
  262. }
  263. export default Webshot;