webshot.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. import { writeFileSync } from 'fs';
  2. import { Readable } from 'stream';
  3. import { promisify } from 'util';
  4. import axios from 'axios';
  5. import * as CallableInstance from 'callable-instance';
  6. import { XmlEntities } from 'html-entities';
  7. import { PNG } from 'pngjs';
  8. import * as puppeteer from 'playwright';
  9. import * as sharp from 'sharp';
  10. import * as temp from 'temp';
  11. import { getLogger } from './loggers';
  12. import { Message } from './koishi';
  13. import { MediaEntity, Tweet } from './twitter';
  14. import { chainPromises } from './utils';
  15. const xmlEntities = new XmlEntities();
  16. const ZHType = (type: string) => new class extends String {
  17. public type = super.toString();
  18. public toString = () => `[${super.toString()}]`;
  19. }(type);
  20. const typeInZH = {
  21. photo: ZHType('图片'),
  22. video: ZHType('视频'),
  23. animated_gif: ZHType('GIF'),
  24. };
  25. const logger = getLogger('webshot');
  26. class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Promise<void>> {
  27. private browser: puppeteer.Browser;
  28. private mode: number;
  29. private wsUrl: string;
  30. constructor(wsUrl: string, mode: number, onready?: (...args) => void) {
  31. super('webshot');
  32. // tslint:disable-next-line: no-conditional-assignment
  33. // eslint-disable-next-line no-cond-assign
  34. if (this.mode = mode) {
  35. onready();
  36. } else {
  37. this.wsUrl = wsUrl;
  38. this.connect(onready);
  39. }
  40. }
  41. private connect = (onready?: (...args) => void): Promise<void> =>
  42. axios.get<{[key in 'chromium' | 'firefox' | 'webkit']?: string}>(this.wsUrl)
  43. .then(res => {
  44. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  45. const browserType = Object.keys(res.data)[0] as keyof typeof res.data;
  46. return (puppeteer[browserType] as puppeteer.BrowserType<puppeteer.Browser>)
  47. .connect({wsEndpoint: res.data[browserType]});
  48. })
  49. .then(browser => this.browser = browser)
  50. .then(() => {
  51. logger.info('launched puppeteer browser');
  52. if (onready) return onready();
  53. })
  54. .catch(error => this.reconnect(error, onready));
  55. private reconnect = (error, onready?: (...args) => void) => {
  56. logger.error(`connection error, reason: ${error}`);
  57. logger.warn('trying to reconnect in 2.5s...');
  58. return promisify(setTimeout)(2500)
  59. .then(() => this.connect(onready));
  60. };
  61. private renderWebshot = (
  62. url: string, height: number, webshotDelay: number,
  63. ...morePostProcessings: ((page?: puppeteer.Page, handle?: puppeteer.ElementHandle) => Promise<any>)[]
  64. ): Promise<string> => {
  65. temp.track();
  66. const jpeg = (data: Readable) => data.pipe(sharp()).jpeg({quality: 90, trellisQuantisation: true});
  67. const sharpToFile = (pic: sharp.Sharp) => new Promise<string>(resolve => {
  68. const webshotTempFilePath = temp.path({suffix: '.jpg'});
  69. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  70. });
  71. const promise = new Promise<{ path: 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. timezoneId: 'Asia/Tokyo',
  80. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  81. })
  82. .then(page => {
  83. const startTime = new Date().getTime();
  84. const getTimerTime = () => new Date().getTime() - startTime;
  85. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  86. page.setViewportSize({
  87. width: width / zoomFactor,
  88. height: height / zoomFactor,
  89. })
  90. .then(() => page.route('*:\/\/video.twimg.com\/**', route => { route.abort(); }))
  91. .then(() => page.goto(url, {waitUntil: 'load', timeout: getTimeout()}))
  92. .then(() => Promise.race([
  93. page.waitForSelector('article', {state: 'attached', timeout: getTimeout()}),
  94. page.click('#placeholder+#ScriptLoadFailure input[value="Try again"]', {timeout: getTimeout()}),
  95. page.waitForSelector('div[role="button"]>div>span>:text-matches("^やりなおす|更新$")', {state: 'attached', timeout: getTimeout()})
  96. .then(() => page.reload({timeout: getTimeout()})),
  97. ]))
  98. // hide header, "more options" button, like and retweet count
  99. .then(() => page.addStyleTag({
  100. content: 'header,#layers{display:none!important}article{background-color:transparent!important}' +
  101. '[data-testid="caret"],[role="group"],[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]~div{display:none}',
  102. }))
  103. .then(() => page.addStyleTag({
  104. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  105. }))
  106. // remove listeners
  107. .then(() => page.evaluate(() => {
  108. const poll = setInterval(() => {
  109. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  110. if (container.querySelector('div[role="button"] svg')) {
  111. container.innerHTML = container.innerHTML;
  112. clearInterval(poll);
  113. }
  114. });
  115. }, 250);
  116. }))
  117. // find main tweet
  118. .then(() => page.waitForSelector(
  119. 'xpath=//section/*/*/div[.//article[not(.//time[not(ancestor::div[@aria-labelledby])])]]',
  120. {state: 'attached', timeout: getTimeout()}
  121. ))
  122. // toggle visibility of sensitive tweets
  123. .then(handle => handle.$$('xpath=..//a[contains(@href,"content_you_see")]/../../..//*[@role="button"]')
  124. .then(sensitiveToggles => {
  125. const count = sensitiveToggles.length;
  126. if (count) logger.info(`found ${count} sensitive ${count === 1 ? 'tweet' : 'tweets'} on page, uncollapsing...`);
  127. return chainPromises(sensitiveToggles.filter(toggle => toggle.isVisible()).map(toggle => () => toggle.click()));
  128. })
  129. .then(() => handle)
  130. )
  131. // throw early if tweet is unavailable
  132. .then(handle => handle.$('[data-testid="tweet"]').then(owner => owner ? handle : null))
  133. .catch((err: Error): Promise<puppeteer.ElementHandle<HTMLDivElement> | null> => {
  134. if (err.name !== 'TimeoutError')
  135. throw err;
  136. logger.warn(`${err} (${getTimerTime()} ms)`);
  137. return page.evaluate(() => document.documentElement.outerHTML).then(html => {
  138. const path = temp.path({suffix: '.html'});
  139. writeFileSync(path, html);
  140. logger.warn(`saved debug html to ${path}`);
  141. }).then(() => page.screenshot()).then(screenshot => {
  142. sharpToFile(sharp(screenshot).jpeg({ quality: 90 })).then(fileUri => {
  143. logger.warn(`saved debug screenshot to ${fileUri.substring(7)}`);
  144. });
  145. }).then(() => null);
  146. })
  147. .then(handle => {
  148. if (handle === null) throw new puppeteer.errors.TimeoutError();
  149. return chainPromises(morePostProcessings.map(func => () => func(page, handle)));
  150. })
  151. .then(() => promisify(setTimeout)(getTimeout()))
  152. // hide highlight of retweet header
  153. .then(() => page.evaluate(() => (document.activeElement as unknown as HTMLOrSVGElement).blur()))
  154. .then(() => page.screenshot())
  155. .then(screenshot => {
  156. new PNG({
  157. filterType: 4,
  158. deflateLevel: 0,
  159. }).on('parsed', function () {
  160. // remove comment area
  161. // tslint:disable-next-line: no-shadowed-variable
  162. // eslint-disable-next-line @typescript-eslint/no-shadow
  163. const idx = (x: number, y: number) => (this.width * y + x) << 2;
  164. let boundary: number = null;
  165. const x = zoomFactor * 2;
  166. for (let y = x; y < this.height; y += zoomFactor) {
  167. if (
  168. this.data[idx(x, y)] !== this.data[idx(x, y - zoomFactor)] &&
  169. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]
  170. ) {
  171. boundary = y;
  172. break;
  173. }
  174. }
  175. if (boundary !== null) {
  176. logger.info(`found boundary at ${boundary}, cropping image`);
  177. this.data = this.data.slice(0, idx(this.width, boundary));
  178. this.height = boundary;
  179. sharpToFile(jpeg(this.pack())).then(path => {
  180. logger.info(`finished webshot for ${url}`);
  181. resolve({path, boundary});
  182. });
  183. } else if (height >= 8 * 1920) {
  184. logger.warn('too large, consider as a bug, returning');
  185. sharpToFile(jpeg(this.pack())).then(path => {
  186. resolve({path, boundary: 0});
  187. });
  188. } else {
  189. logger.info('unable to find boundary, try shooting a larger image');
  190. resolve({path: '', boundary});
  191. }
  192. }).parse(screenshot);
  193. })
  194. .catch(err => {
  195. if (err instanceof Error && err.name !== 'TimeoutError') throw err;
  196. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  197. resolve({path: '', boundary: 0});
  198. })
  199. .finally(() => { page.close(); });
  200. })
  201. .catch(reject);
  202. });
  203. return promise.then(data => {
  204. if (data.boundary === null) {
  205. return this.renderWebshot(url, height + 1920, webshotDelay, ...morePostProcessings);
  206. } else return data.path;
  207. }).catch(error => this.reconnect(error)
  208. .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings))
  209. );
  210. };
  211. private fetchMedia = (url: string): Promise<string> => new Promise<ArrayBuffer>((resolve, reject) => {
  212. logger.info(`fetching ${url}`);
  213. axios({
  214. method: 'get',
  215. url,
  216. responseType: 'arraybuffer',
  217. timeout: 150000,
  218. }).then(res => {
  219. if (res.status === 200) {
  220. logger.info(`successfully fetched ${url}`);
  221. resolve(res.data);
  222. } else {
  223. logger.error(`failed to fetch ${url}: ${res.status}`);
  224. reject();
  225. }
  226. }).catch (err => {
  227. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  228. reject();
  229. });
  230. }).then(data =>
  231. (ext => {
  232. const mediaTempFilePath = temp.path({suffix: `.${ext}`});
  233. writeFileSync(mediaTempFilePath, Buffer.from(data));
  234. const path = `file://${mediaTempFilePath}`;
  235. switch (ext) {
  236. case 'jpg':
  237. case 'png':
  238. return Message.Image(path);
  239. case 'mp4':
  240. return Message.Video(path);
  241. }
  242. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  243. throw Error();
  244. })(((/\?format=([a-z]+)&/.exec(url)) ?? (/.*\/.*\.([^?]+)/.exec(url)))[1])
  245. );
  246. public webshot(
  247. tweets: Tweet[],
  248. callback: (cacheId: string, msgs: string, text: string, author: string) => void,
  249. webshotDelay: number
  250. ): Promise<void> {
  251. const promises = tweets.map((twi, index) => {
  252. let promise = promisify(setTimeout)(webshotDelay / 4 * index).then(() => {
  253. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  254. });
  255. const originTwi = twi.retweeted_status || twi;
  256. let messageChain = '';
  257. let truncatedAt: string;
  258. // text processing
  259. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  260. author += `${new Date(twi.created_at)}\n`;
  261. if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
  262. let text = originTwi.full_text;
  263. promise = promise.then(() => {
  264. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  265. originTwi.entities.urls.forEach(url => {
  266. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  267. });
  268. }
  269. if (originTwi.extended_entities) {
  270. originTwi.extended_entities.media.forEach(media => {
  271. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  272. });
  273. }
  274. if (this.mode > 0) messageChain += (author + xmlEntities.decode(text));
  275. });
  276. // invoke webshot
  277. if (this.mode === 0) {
  278. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  279. const extendEntity = (cardImg: MediaEntity) => {
  280. originTwi.extended_entities = {
  281. ...originTwi.extended_entities,
  282. media: [
  283. ...originTwi.extended_entities?.media ?? [],
  284. cardImg,
  285. ],
  286. };
  287. };
  288. const truncateLongThread = (atId: string) => {
  289. if (!atId) return;
  290. logger.info(`thread too long, truncating at tweet ${atId}...`);
  291. truncatedAt = atId;
  292. };
  293. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay,
  294. // scroll back at least 2 tweets revealing 2nd last tweet by owner in thread, or top of thread
  295. (_, tweetHandle: puppeteer.ElementHandle<HTMLDivElement>) => tweetHandle.evaluate(div => {
  296. try {
  297. const selector = '[data-testid="tweet"] :nth-child(2)>:first-child a';
  298. const getProfileUrl = () => (div.querySelector<HTMLAnchorElement>(selector) || {href: ''}).href;
  299. const ownerProfileUrl = getProfileUrl();
  300. const bottom = div;
  301. // eslint-disable-next-line no-cond-assign
  302. while (div = div.previousElementSibling as HTMLDivElement) {
  303. if (getProfileUrl() !== ownerProfileUrl || div === bottom.previousElementSibling) continue;
  304. const top = document.documentElement.scrollTop = window.scrollY + div.getBoundingClientRect().top;
  305. if (top > 10)
  306. return div.querySelector<HTMLAnchorElement>('article a[aria-label]').href.replace(/.*\/status\//, '');
  307. }
  308. } catch {/* handle errors like none-found cases */}
  309. document.documentElement.scrollTop = 0;
  310. }).then(truncateLongThread),
  311. // scrape card image from main tweet
  312. (_, tweetHandle: puppeteer.ElementHandle<HTMLDivElement>) => tweetHandle.evaluate(div => {
  313. const cardImg = div.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  314. if (typeof cardImg?.getAttribute('src') === 'string') {
  315. const match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardImg?.getAttribute('src'));
  316. if (match) {
  317. // tslint:disable-next-line: variable-name
  318. const [media_url_https, id_str] = match.slice(1);
  319. return {
  320. media_url: media_url_https.replace(/^https/, 'http'),
  321. media_url_https,
  322. url: '',
  323. display_url: '',
  324. expanded_url: '',
  325. type: 'photo',
  326. id: Number(id_str),
  327. id_str,
  328. sizes: undefined,
  329. };
  330. }
  331. }
  332. }).then(cardImg => { if (cardImg) extendEntity(cardImg); })
  333. ))
  334. .then(fileurl => {
  335. if (fileurl) return Message.Image(fileurl);
  336. return '[截图不可用] ' + author + text;
  337. })
  338. .then(msg => {
  339. if (msg) messageChain += msg;
  340. });
  341. }
  342. // fetch extra entities
  343. // tslint:disable-next-line: curly
  344. // eslint-disable-next-line curly
  345. if (1 - this.mode % 2) promise = promise.then(() => {
  346. if (originTwi.extended_entities) {
  347. return chainPromises(originTwi.extended_entities.media.map(media => () => {
  348. let url: string;
  349. if (media.type === 'photo') {
  350. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  351. } else {
  352. url = media.video_info.variants
  353. .filter(variant => variant.bitrate !== undefined)
  354. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  355. .map(variant => variant.url)[0]; // largest video
  356. }
  357. const altMessage = `\n[失败的${typeInZH[media.type as keyof typeof typeInZH].type}:${url}]`;
  358. return this.fetchMedia(url)
  359. .catch(error => {
  360. logger.warn('unable to fetch media, sending plain text instead...');
  361. return altMessage;
  362. })
  363. .then(msg => { messageChain += msg; });
  364. }));
  365. }
  366. });
  367. // append URLs, if any
  368. if (this.mode === 0) {
  369. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  370. promise = promise.then(() => {
  371. const urls = originTwi.entities.urls
  372. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  373. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  374. if (urls.length) {
  375. messageChain += urls.join('');
  376. }
  377. });
  378. }
  379. }
  380. // refer to earlier tweets if thread is truncated
  381. promise = promise.then(() => {
  382. if (truncatedAt) {
  383. messageChain += `\n回复此命令查看对话串中更早的推文:\n/twitter_view ${truncatedAt}`;
  384. }
  385. });
  386. // refer to quoted tweet, if any
  387. if (originTwi.is_quote_status) {
  388. promise = promise.then(() => {
  389. const match = /\/status\/(\d+)/.exec(originTwi.quoted_status_permalink?.expanded);
  390. const blockQuoteIdStr = match ? match[1] : originTwi.quoted_status?.id_str;
  391. if (blockQuoteIdStr) messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${blockQuoteIdStr}`;
  392. });
  393. }
  394. return promise.then(() => {
  395. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  396. logger.info(JSON.stringify(Message.ellipseBase64(messageChain)));
  397. let cacheId = twi.id_str;
  398. if (twi.retweeted_status) cacheId += `,rt:${twi.retweeted_status.id_str}`;
  399. callback(cacheId, messageChain, xmlEntities.decode(text), author);
  400. });
  401. });
  402. return Promise.all(promises).then();
  403. }
  404. }
  405. export default Webshot;