webshot.ts 14 KB

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