webshot.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import axios from 'axios';
  2. import * as CallableInstance from 'callable-instance';
  3. import { spawnSync } from 'child_process';
  4. import { existsSync, readFileSync, statSync, unlinkSync, writeSync } from 'fs';
  5. import { XmlEntities } from 'html-entities';
  6. import { PNG } from 'pngjs';
  7. import * as puppeteer from 'playwright';
  8. import * as sharp from 'sharp';
  9. import { Readable } from 'stream';
  10. import * as temp from 'temp';
  11. import { promisify } from 'util';
  12. import gifski from './gifski';
  13. import { getLogger } from './loggers';
  14. import { Message, MessageChain } from './mirai';
  15. import { MediaEntity, Tweets } from './twitter';
  16. import { chainPromises } from './utils';
  17. const xmlEntities = new XmlEntities();
  18. const ZHType = (type: string) => new class extends String {
  19. public type = super.toString();
  20. public toString = () => `[${super.toString()}]`;
  21. }(type);
  22. const typeInZH = {
  23. photo: ZHType('图片'),
  24. video: ZHType('视频'),
  25. animated_gif: ZHType('GIF'),
  26. };
  27. const logger = getLogger('webshot');
  28. const wsUrl = 'https://ilg-server.ling.uni-stuttgart.de/playwright-ws.json';
  29. class Webshot
  30. extends CallableInstance<
  31. [Tweets, (...args) => Promise<any>, (...args) => void, number],
  32. Promise<void>
  33. > {
  34. private browser: puppeteer.Browser;
  35. private mode: number;
  36. constructor(mode: number, onready?: () => any) {
  37. super('webshot');
  38. // tslint:disable-next-line: no-conditional-assignment
  39. if (this.mode = mode) {
  40. onready();
  41. } else {
  42. this.connect(onready);
  43. }
  44. }
  45. private connect = (onready) => axios.get(wsUrl)
  46. .then(res => {
  47. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  48. const browserType = Object.keys(res.data)[0];
  49. return (puppeteer[browserType] as puppeteer.BrowserType<puppeteer.Browser>).connect({wsEndpoint: res.data[browserType]});
  50. })
  51. .then(browser => this.browser = browser)
  52. .then(() => {
  53. logger.info('launched puppeteer browser');
  54. if (onready) return onready();
  55. })
  56. .catch(error => this.reconnect(error, onready))
  57. private reconnect = (error, onready?) => {
  58. logger.error(`connection error, reason: ${error}`);
  59. logger.warn('trying to reconnect in 2.5s...');
  60. return promisify(setTimeout)(2500)
  61. .then(() => this.connect(onready));
  62. }
  63. private extendEntity = (media: MediaEntity) => {
  64. logger.info('not working on a tweet');
  65. }
  66. private renderWebshot = (url: string, height: number, webshotDelay: number): Promise<string> => {
  67. const jpeg = (data: Readable) => data.pipe(sharp()).jpeg({quality: 90, trellisQuantisation: true});
  68. const sharpToBase64 = (pic: sharp.Sharp) => new Promise<string>(resolve => {
  69. pic.toBuffer().then(buffer => resolve(`data:image/jpeg;base64,${buffer.toString('base64')}`));
  70. });
  71. const promise = new Promise<{ base64: string, boundary: null | number }>((resolve, reject) => {
  72. const width = 720;
  73. const zoomFactor = 2;
  74. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  75. this.browser.newPage({
  76. bypassCSP: true,
  77. deviceScaleFactor: zoomFactor,
  78. locale: 'ja-JP',
  79. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  80. })
  81. .then(page => {
  82. const startTime = new Date().getTime();
  83. const getTimerTime = () => new Date().getTime() - startTime;
  84. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  85. page.setViewportSize({
  86. width: width / zoomFactor,
  87. height: height / zoomFactor,
  88. })
  89. .then(() => page.goto(url, {waitUntil: 'load', timeout: getTimeout()}))
  90. // hide header, "more options" button, like and retweet count
  91. .then(() => page.addStyleTag({
  92. 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;}',
  93. }))
  94. .then(() => page.addStyleTag({
  95. content: '*{font-family:-apple-system,SF Pro Display,Hiragino Sans,sans-serif!important}',
  96. }))
  97. // remove listeners
  98. .then(() => page.evaluate(() => {
  99. const poll = setInterval(() => {
  100. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  101. if (container) {
  102. container.innerHTML = container.innerHTML;
  103. clearInterval(poll);
  104. }
  105. });
  106. }, 250);
  107. }))
  108. .then(() => page.waitForSelector('article', {timeout: getTimeout()}))
  109. .catch((err: Error): Promise<puppeteer.ElementHandle<Element> | null> => {
  110. if (err.name !== 'TimeoutError') throw err;
  111. logger.warn(`navigation timed out at ${getTimerTime()} seconds`);
  112. return null;
  113. })
  114. .then(handle => {
  115. if (handle === null) throw new puppeteer.errors.TimeoutError();
  116. })
  117. .then(() => page.evaluate(() => {
  118. const cardImg = document.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  119. if (typeof cardImg?.getAttribute('src') === 'string') {
  120. const match = cardImg?.getAttribute('src')
  121. .match(/^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/);
  122. if (match) {
  123. // tslint:disable-next-line: variable-name
  124. const [media_url_https, id_str] = match.slice(1);
  125. return {
  126. media_url: media_url_https.replace(/^https/, 'http'),
  127. media_url_https,
  128. url: '',
  129. display_url: '',
  130. expanded_url: '',
  131. type: 'photo',
  132. id: Number(id_str),
  133. id_str,
  134. sizes: undefined,
  135. };
  136. }
  137. }
  138. }))
  139. .then(cardImg => { if (cardImg) this.extendEntity(cardImg); })
  140. .then(() => page.addScriptTag({
  141. content: 'document.documentElement.scrollTop=0;',
  142. }))
  143. .then(() => promisify(setTimeout)(getTimeout()))
  144. .then(() => page.screenshot())
  145. .then(screenshot => {
  146. new PNG({
  147. filterType: 4,
  148. deflateLevel: 0,
  149. }).on('parsed', function () {
  150. // remove comment area
  151. // tslint:disable-next-line: no-shadowed-variable
  152. const idx = (x: number, y: number) => (this.width * y + x) << 2;
  153. let boundary = null;
  154. let x = zoomFactor * 2;
  155. for (let y = 0; y < this.height; y += zoomFactor) {
  156. if (
  157. this.data[idx(x, y)] !== 255 &&
  158. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]
  159. ) {
  160. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  161. // footer kicks in
  162. boundary = null;
  163. } else {
  164. boundary = y;
  165. }
  166. break;
  167. }
  168. }
  169. if (boundary !== null) {
  170. logger.info(`found boundary at ${boundary}, cropping image`);
  171. this.data = this.data.slice(0, idx(this.width, boundary));
  172. this.height = boundary;
  173. boundary = null;
  174. x = Math.floor(16 * zoomFactor);
  175. let flag = false;
  176. let cnt = 0;
  177. for (let y = this.height - 1 - zoomFactor; y >= 0; y -= zoomFactor) {
  178. if ((this.data[idx(x, y)] === 255) === flag) {
  179. cnt++;
  180. flag = !flag;
  181. } else continue;
  182. // line above the "comment", "retweet", "like", "share" button row
  183. if (cnt === 2) {
  184. boundary = y + 1;
  185. }
  186. // if there are a "retweet" count and "like" count row, this will be the line above it
  187. if (cnt === 4) {
  188. const b = y + 1;
  189. if (Math.abs(this.height - boundary - (boundary - b)) <= 3 * zoomFactor) {
  190. boundary = b;
  191. }
  192. }
  193. // if "retweet" count and "like" count are two rows, this will be the line above the first
  194. if (cnt === 6) {
  195. const c = y + 1;
  196. if (Math.abs(this.height - boundary - 2 * (boundary - c)) <= 3 * zoomFactor) {
  197. boundary = c;
  198. break;
  199. }
  200. }
  201. }
  202. if (boundary != null) {
  203. logger.info(`found boundary at ${boundary}, trimming image`);
  204. this.data = this.data.slice(0, idx(this.width, boundary));
  205. this.height = boundary;
  206. }
  207. sharpToBase64(jpeg(this.pack())).then(base64 => {
  208. logger.info(`finished webshot for ${url}`);
  209. resolve({base64, boundary});
  210. });
  211. } else if (height >= 8 * 1920) {
  212. logger.warn('too large, consider as a bug, returning');
  213. sharpToBase64(jpeg(this.pack())).then(base64 => {
  214. resolve({base64, boundary: 0});
  215. });
  216. } else {
  217. logger.info('unable to find boundary, try shooting a larger image');
  218. resolve({base64: '', boundary});
  219. }
  220. }).parse(screenshot);
  221. })
  222. .catch(err => {
  223. if (err.name !== 'TimeoutError') throw err;
  224. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  225. resolve({base64: '', boundary: 0});
  226. })
  227. .finally(() => page.close());
  228. })
  229. .catch(reject);
  230. });
  231. return promise.then(data => {
  232. if (data.boundary === null) return this.renderWebshot(url, height + 1920, webshotDelay);
  233. else return data.base64;
  234. }).catch(error =>
  235. new Promise(resolve => this.reconnect(error, resolve))
  236. .then(() => this.renderWebshot(url, height, webshotDelay))
  237. );
  238. }
  239. private fetchMedia = (url: string): Promise<string> => {
  240. const gif = (data: ArrayBuffer) => {
  241. const matchDims = url.match(/\/(\d+)x(\d+)\//);
  242. if (matchDims) {
  243. const [ width, height ] = matchDims.slice(1).map(Number);
  244. const factor = width + height > 1600 ? 0.375 : 0.5;
  245. return gifski(data, width * factor);
  246. }
  247. return gifski(data);
  248. };
  249. return new Promise<ArrayBuffer>((resolve, reject) => {
  250. logger.info(`fetching ${url}`);
  251. axios({
  252. method: 'get',
  253. url,
  254. responseType: 'arraybuffer',
  255. timeout: 150000,
  256. }).then(res => {
  257. if (res.status === 200) {
  258. logger.info(`successfully fetched ${url}`);
  259. resolve(res.data);
  260. } else {
  261. logger.error(`failed to fetch ${url}: ${res.status}`);
  262. reject();
  263. }
  264. }).catch (err => {
  265. logger.error(`failed to fetch ${url}: ${err.message}`);
  266. reject();
  267. });
  268. }).then(data =>
  269. (async ext => {
  270. switch (ext) {
  271. case 'jpg':
  272. return {mimetype: 'image/jpeg', data};
  273. case 'png':
  274. return {mimetype: 'image/png', data};
  275. case 'mp4':
  276. try {
  277. return {mimetype: 'video/x-matroska', data: await gif(data)};
  278. } catch (err) {
  279. logger.error(err);
  280. throw Error(err);
  281. }
  282. }
  283. })((url.match(/\?format=([a-z]+)&/) ?? url.match(/.*\/.*\.([^?]+)/))[1])
  284. .catch(() => {
  285. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  286. throw Error();
  287. })
  288. ).then(typedData =>
  289. `data:${typedData.mimetype};base64,${Buffer.from(typedData.data).toString('base64')}`
  290. );
  291. }
  292. public webshot(
  293. tweets: Tweets,
  294. uploader: <T extends ReturnType<typeof Message.Image | typeof Message.Voice>>(
  295. msg: T,
  296. lastResort: (...args) => ReturnType<typeof Message.Plain>)
  297. => Promise<T | ReturnType<typeof Message.Plain>>,
  298. callback: (msgs: MessageChain, text: string, author: string) => void,
  299. webshotDelay: number
  300. ): Promise<void> {
  301. let promise = new Promise<void>(resolve => {
  302. resolve();
  303. });
  304. tweets.forEach(twi => {
  305. promise = promise.then(() => {
  306. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  307. });
  308. const originTwi = twi.retweeted_status || twi;
  309. const messageChain: MessageChain = [];
  310. // text processing
  311. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  312. if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
  313. let text = originTwi.full_text;
  314. promise = promise.then(() => {
  315. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  316. originTwi.entities.urls.forEach(url => {
  317. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  318. });
  319. }
  320. if (originTwi.extended_entities) {
  321. originTwi.extended_entities.media.forEach(media => {
  322. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  323. });
  324. }
  325. if (this.mode > 0) messageChain.push(Message.Plain(author + xmlEntities.decode(text)));
  326. });
  327. // invoke webshot
  328. if (this.mode === 0) {
  329. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  330. this.extendEntity = (cardImg: MediaEntity) => {
  331. originTwi.extended_entities = {
  332. ...originTwi.extended_entities,
  333. media: [
  334. ...originTwi.extended_entities?.media ?? [],
  335. cardImg,
  336. ],
  337. };
  338. };
  339. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  340. .then(base64url => {
  341. if (base64url) return uploader(Message.Image('', base64url, url), () => Message.Plain(author + text));
  342. return Message.Plain(author + text);
  343. })
  344. .then(msg => {
  345. if (msg) messageChain.push(msg);
  346. });
  347. }
  348. // fetch extra entities
  349. // tslint:disable-next-line: curly
  350. if (1 - this.mode % 2) promise = promise.then(() => {
  351. if (originTwi.extended_entities) {
  352. return chainPromises(originTwi.extended_entities.media.map(media => {
  353. let url: string;
  354. if (media.type === 'photo') {
  355. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  356. } else {
  357. url = media.video_info.variants
  358. .filter(variant => variant.bitrate !== undefined)
  359. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  360. .map(variant => variant.url)[0]; // largest video
  361. }
  362. const altMessage = Message.Plain(`\n[失败的${typeInZH[media.type].type}:${url}]`);
  363. return this.fetchMedia(url)
  364. .then(base64url => {
  365. let mediaPromise = Promise.resolve([] as (
  366. Parameters<typeof uploader>[0] |
  367. ReturnType<Parameters<typeof uploader>[1]>
  368. )[]);
  369. if (base64url.match(/^data:video.+;/)) {
  370. // demux mkv into gif and pcm16le
  371. const input = () => Buffer.from(base64url.split(',')[1], 'base64');
  372. const imgReturns = spawnSync('ffmpeg', [
  373. '-i', '-',
  374. '-an',
  375. '-f', 'gif',
  376. '-c', 'copy',
  377. '-',
  378. ], {stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input()});
  379. const voiceReturns = spawnSync('ffmpeg', [
  380. '-i', '-',
  381. '-vn',
  382. '-f', 's16le',
  383. '-ac', '1',
  384. '-ar', '24000',
  385. '-',
  386. ], {stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input()});
  387. if (!imgReturns.stdout.byteLength) throw Error(imgReturns.stderr.toString());
  388. base64url = `data:image/gif;base64,${imgReturns.stdout.toString('base64')}`;
  389. if (voiceReturns.stdout.byteLength) {
  390. logger.info('video has an audio track, trying to convert it to voice...');
  391. temp.track();
  392. const inputFile = temp.openSync();
  393. writeSync(inputFile.fd, voiceReturns.stdout);
  394. spawnSync('silk-encoder', [
  395. inputFile.path,
  396. inputFile.path + '.silk',
  397. '-tencent',
  398. ]);
  399. temp.cleanup();
  400. if (existsSync(inputFile.path + '.silk')) {
  401. if (statSync(inputFile.path + '.silk').size !== 0) {
  402. const audioBase64Url = `data:audio/silk-v3;base64,${
  403. readFileSync(inputFile.path + '.silk').toString('base64')
  404. }`;
  405. mediaPromise = mediaPromise.then(chain =>
  406. uploader(Message.Voice('', audioBase64Url, `${url} as amr`), () => Message.Plain('\n[失败的语音]'))
  407. .then(msg => [msg, ...chain])
  408. );
  409. }
  410. unlinkSync(inputFile.path + '.silk');
  411. }
  412. }
  413. }
  414. return mediaPromise.then(chain =>
  415. uploader(Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage)
  416. .then(msg => [msg, ...chain])
  417. );
  418. })
  419. .catch(error => {
  420. logger.error(`unable to fetch media, error: ${error}`);
  421. logger.warn('unable to fetch media, sending plain text instead...');
  422. return [altMessage];
  423. })
  424. .then(msgs => {
  425. messageChain.push(...msgs);
  426. });
  427. }));
  428. }
  429. });
  430. // append URLs, if any
  431. if (this.mode === 0) {
  432. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  433. promise = promise.then(() => {
  434. const urls = originTwi.entities.urls
  435. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  436. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  437. if (urls.length) {
  438. messageChain.push(Message.Plain(urls.join('')));
  439. }
  440. });
  441. }
  442. }
  443. // refer to quoted tweet, if any
  444. if (originTwi.is_quote_status) {
  445. promise = promise.then(() => {
  446. messageChain.push(
  447. Message.Plain(`\n回复此命令查看引用的推文:\n/twitter_view ${originTwi.quoted_status_id_str}`)
  448. );
  449. });
  450. }
  451. promise.then(() => {
  452. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  453. logger.info(JSON.stringify(messageChain));
  454. callback(messageChain, xmlEntities.decode(text), author);
  455. });
  456. });
  457. return promise.catch(err => logger.error(`failed to shoot webshot, error: ${JSON.stringify(err)}`));
  458. }
  459. }
  460. export default Webshot;