webshot.ts 18 KB

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