webshot.ts 16 KB

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