webshot.ts 15 KB

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