webshot.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import axios from 'axios';
  2. import * as CallableInstance from 'callable-instance';
  3. import { XmlEntities } from 'html-entities';
  4. import { PNG } from 'pngjs';
  5. import * as puppeteer from 'puppeteer';
  6. import { Browser } from 'puppeteer';
  7. import * as sharp from 'sharp';
  8. import { Readable } from 'stream';
  9. import gifski from './gifski';
  10. import { getLogger } from './loggers';
  11. import { Message, MessageChain } from './mirai';
  12. import { Tweets } from './twitter';
  13. const xmlEntities = new XmlEntities();
  14. const ZHType = (type: string) => new class extends String {
  15. public type = super.toString();
  16. public toString = () => `[${super.toString()}]`;
  17. }(type);
  18. const typeInZH = {
  19. photo: ZHType('图片'),
  20. video: ZHType('视频'),
  21. animated_gif: ZHType('GIF'),
  22. };
  23. const logger = getLogger('webshot');
  24. class Webshot
  25. extends CallableInstance<
  26. [Tweets, (...args) => Promise<any>, (...args) => void, number],
  27. Promise<void>
  28. > {
  29. private browser: Browser;
  30. private mode: number;
  31. constructor(mode: number, onready?: () => any) {
  32. super('webshot');
  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: Readable) => data.pipe(sharp()).jpeg({quality: 90, trellisQuantisation: true});
  56. const sharpToBase64 = (pic: sharp.Sharp) => new Promise<string>(resolve => {
  57. pic.toBuffer().then(buffer => resolve(`data:image/jpeg;base64,${buffer.toString('base64')}`));
  58. });
  59. const promise = new Promise<{ base64: string, boundary: null | number }>((resolve, reject) => {
  60. const width = 720;
  61. const zoomFactor = 2;
  62. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  63. this.browser.newPage()
  64. .then(page => {
  65. page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  66. .then(() => page.setViewport({
  67. width: width / zoomFactor,
  68. height: height / zoomFactor,
  69. isMobile: true,
  70. deviceScaleFactor: zoomFactor,
  71. }))
  72. .then(() => page.setBypassCSP(true))
  73. .then(() => page.goto(url, {waitUntil: 'load', timeout: 150000}))
  74. // hide header, "more options" button, like and retweet count
  75. .then(() => page.addStyleTag({
  76. 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;}',
  77. }))
  78. .then(() => page.waitFor(webshotDelay))
  79. .then(() => page.addScriptTag({
  80. content: 'document.documentElement.scrollTop=0;',
  81. }))
  82. .then(() => page.screenshot())
  83. .then(screenshot => {
  84. new PNG({
  85. filterType: 4,
  86. deflateLevel: 0,
  87. }).on('parsed', function () {
  88. // remove comment area
  89. // tslint:disable-next-line: no-shadowed-variable
  90. const idx = (x: number, y: number) => (this.width * y + x) << 2;
  91. let boundary = null;
  92. let x = zoomFactor * 2;
  93. for (let y = 0; y < this.height; y++) {
  94. if (this.data[idx(x, y)] !== 255) {
  95. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  96. // footer kicks in
  97. boundary = null;
  98. } else {
  99. boundary = y;
  100. }
  101. break;
  102. }
  103. }
  104. if (boundary !== null) {
  105. logger.info(`found boundary at ${boundary}, cropping image`);
  106. this.data = this.data.slice(0, idx(this.width, boundary));
  107. this.height = boundary;
  108. boundary = null;
  109. x = Math.floor(16 * zoomFactor);
  110. let flag = false;
  111. let cnt = 0;
  112. for (let y = this.height - 1; y >= 0; y--) {
  113. if ((this.data[idx(x, y)] === 255) === flag) {
  114. cnt++;
  115. flag = !flag;
  116. } else continue;
  117. // line above the "comment", "retweet", "like", "share" button row
  118. if (cnt === 2) {
  119. boundary = y + 1;
  120. }
  121. // if there are a "retweet" count and "like" count row, this will be the line above it
  122. if (cnt === 4) {
  123. const b = y + 1;
  124. if (this.height - boundary - (boundary - b) <= 1) {
  125. boundary = b;
  126. // }
  127. // }
  128. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  129. // if (cnt === 6) {
  130. // const c = y + 1;
  131. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  132. // boundary = c;
  133. break;
  134. }
  135. }
  136. }
  137. if (boundary != null) {
  138. logger.info(`found boundary at ${boundary}, trimming image`);
  139. this.data = this.data.slice(0, idx(this.width, boundary));
  140. this.height = boundary;
  141. }
  142. sharpToBase64(jpeg(this.pack())).then(base64 => {
  143. logger.info(`finished webshot for ${url}`);
  144. resolve({base64, boundary});
  145. });
  146. } else if (height >= 8 * 1920) {
  147. logger.warn('too large, consider as a bug, returning');
  148. sharpToBase64(jpeg(this.pack())).then(base64 => {
  149. resolve({base64, boundary: 0});
  150. });
  151. } else {
  152. logger.info('unable to find boundary, try shooting a larger image');
  153. resolve({base64: '', boundary});
  154. }
  155. }).parse(screenshot);
  156. })
  157. .then(() => page.close());
  158. })
  159. .catch(reject);
  160. });
  161. return promise.then(data => {
  162. if (data.boundary === null) return this.renderWebshot(url, height + 1920, webshotDelay);
  163. else return data.base64;
  164. }).catch(error =>
  165. new Promise(resolve => this.reconnect(error, resolve))
  166. .then(() => this.renderWebshot(url, height, webshotDelay))
  167. );
  168. }
  169. private fetchMedia = (url: string): Promise<string> =>
  170. new Promise<ArrayBuffer>((resolve, reject) => {
  171. logger.info(`fetching ${url}`);
  172. axios({
  173. method: 'get',
  174. url,
  175. responseType: 'arraybuffer',
  176. }).then(res => {
  177. if (res.status === 200) {
  178. logger.info(`successfully fetched ${url}`);
  179. resolve(res.data);
  180. } else {
  181. logger.error(`failed to fetch ${url}: ${res.status}`);
  182. reject();
  183. }
  184. }).catch (err => {
  185. logger.error(`failed to fetch ${url}: ${err.message}`);
  186. reject();
  187. });
  188. }).then(data =>
  189. (async ext => {
  190. switch (ext) {
  191. case 'jpg':
  192. return {mimetype: 'image/jpeg', data};
  193. case 'png':
  194. return {mimetype: 'image/png', data};
  195. case 'mp4':
  196. const [ width, height ] = url.match(/\/(\d+)x(\d+)\//).slice(1).map(Number);
  197. const factor = width + height > 1600 ? 0.375 : 0.5;
  198. try {
  199. return {mimetype: 'image/gif', data: await gifski(data, width * factor)};
  200. } catch (err) {
  201. throw Error(err);
  202. }
  203. }
  204. })(url.split('/').slice(-1)[0].match(/\.([^:?&]+)/)[1])
  205. ).then(typedData =>
  206. `data:${typedData.mimetype};base64,${Buffer.from(typedData.data).toString('base64')}`
  207. )
  208. public webshot(
  209. tweets: Tweets,
  210. uploader: (
  211. img: ReturnType<typeof Message.Image>,
  212. lastResort: (...args) => ReturnType<typeof Message.Plain>)
  213. => Promise<ReturnType<typeof Message.Image | typeof Message.Plain>>,
  214. callback: (msgs: MessageChain, text: string, author: string) => void,
  215. webshotDelay: number
  216. ): Promise<void> {
  217. let promise = new Promise<void>(resolve => {
  218. resolve();
  219. });
  220. tweets.forEach(twi => {
  221. promise = promise.then(() => {
  222. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  223. });
  224. const originTwi = twi;
  225. const messageChain: MessageChain = [];
  226. // text processing
  227. const author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  228. let text = originTwi.full_text;
  229. promise = promise.then(() => {
  230. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  231. originTwi.entities.urls.forEach(url => {
  232. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  233. });
  234. }
  235. if (originTwi.extended_entities) {
  236. originTwi.extended_entities.media.forEach(media => {
  237. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  238. });
  239. }
  240. if (this.mode > 0) messageChain.push(Message.Plain(author + xmlEntities.decode(text)));
  241. });
  242. // invoke webshot
  243. if (this.mode === 0) {
  244. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  245. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  246. .then(base64url => {
  247. if (base64url) {
  248. return uploader(Message.Image('', base64url, url), () => Message.Plain(author + text));
  249. }
  250. })
  251. .then(msg => {
  252. if (msg) messageChain.push(msg);
  253. });
  254. }
  255. // fetch extra entities
  256. if (1 - this.mode % 2) {
  257. if (originTwi.extended_entities) {
  258. originTwi.extended_entities.media.forEach(media => {
  259. let url: string;
  260. if (media.type === 'photo') {
  261. url = media.media_url_https + ':orig';
  262. } else {
  263. url = media.video_info.variants
  264. .filter(variant => variant.bitrate)
  265. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  266. .map(variant => variant.url)[0]; // largest video
  267. }
  268. const altMessage = Message.Plain(`[失败的${typeInZH[media.type].type}:${url}]`);
  269. promise = promise.then(() => this.fetchMedia(url))
  270. .then(base64url =>
  271. uploader(Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage)
  272. )
  273. .catch(error => {
  274. logger.warn('unable to fetch media, sending plain text instead...');
  275. return altMessage;
  276. })
  277. .then(msg => {
  278. messageChain.push(msg);
  279. });
  280. });
  281. }
  282. }
  283. // append URLs, if any
  284. if (this.mode === 0) {
  285. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  286. promise = promise.then(() => {
  287. const urls = originTwi.entities.urls
  288. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  289. .map(urlObj => urlObj.expanded_url);
  290. if (urls.length) {
  291. messageChain.push(Message.Plain(urls.join('\n')));
  292. }
  293. });
  294. }
  295. }
  296. promise.then(() => {
  297. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  298. logger.info(JSON.stringify(messageChain));
  299. callback(messageChain, xmlEntities.decode(text), author);
  300. });
  301. });
  302. return promise;
  303. }
  304. }
  305. export default Webshot;