webshot.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const fs = require("fs");
  4. const util_1 = require("util");
  5. const axios_1 = require("axios");
  6. const CallableInstance = require("callable-instance");
  7. const html_entities_1 = require("html-entities");
  8. const pngjs_1 = require("pngjs");
  9. const puppeteer = require("playwright");
  10. const sharp = require("sharp");
  11. const temp = require("temp");
  12. const loggers_1 = require("./loggers");
  13. const koishi_1 = require("./koishi");
  14. const utils_1 = require("./utils");
  15. const xmlEntities = new html_entities_1.XmlEntities();
  16. const ZHType = (type) => new class extends String {
  17. constructor() {
  18. super(...arguments);
  19. this.type = super.toString();
  20. this.toString = () => `[${super.toString()}]`;
  21. }
  22. }(type);
  23. const typeInZH = {
  24. photo: ZHType('图片'),
  25. video: ZHType('视频'),
  26. animated_gif: ZHType('GIF'),
  27. };
  28. const logger = (0, loggers_1.getLogger)('webshot');
  29. const axiosGet = (url, responseType, timeout = 150000) => {
  30. logger.info(`fetching ${url}`);
  31. return (0, axios_1.default)({
  32. method: 'get',
  33. url,
  34. responseType,
  35. timeout,
  36. }).then(res => {
  37. if (res.status === 200) {
  38. logger.info(`successfully fetched ${url}`);
  39. return res.data;
  40. }
  41. else {
  42. logger.error(`failed to fetch ${url}: ${res.status}`);
  43. throw new Error();
  44. }
  45. }).catch(err => {
  46. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  47. throw new Error();
  48. });
  49. };
  50. class Webshot extends CallableInstance {
  51. constructor(wsUrl, mode, onready) {
  52. super('webshot');
  53. this.connect = (onready) => axios_1.default.get(this.wsUrl)
  54. .then(res => {
  55. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  56. const browserType = Object.keys(res.data)[0];
  57. return puppeteer[browserType]
  58. .connect({ wsEndpoint: res.data[browserType] });
  59. })
  60. .then(browser => this.browser = browser)
  61. .then(() => {
  62. logger.info('launched puppeteer browser');
  63. if (onready)
  64. return onready();
  65. })
  66. .catch(error => this.reconnect(error, onready));
  67. this.reconnect = (error, onready) => {
  68. logger.error(`connection error, reason: ${error}`);
  69. logger.warn('trying to reconnect in 2.5s...');
  70. return (0, util_1.promisify)(setTimeout)(2500)
  71. .then(() => this.connect(onready));
  72. };
  73. this.renderWebshot = (url, height, webshotDelay, ...morePostProcessings) => {
  74. temp.track();
  75. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  76. const sharpToFile = (pic) => new Promise(resolve => {
  77. const webshotTempFilePath = temp.path({ suffix: '.jpg' });
  78. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  79. });
  80. const promise = new Promise((resolve, reject) => {
  81. const width = 720;
  82. const zoomFactor = 2;
  83. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  84. this.browser.newPage({
  85. bypassCSP: true,
  86. deviceScaleFactor: zoomFactor,
  87. locale: 'ja-JP',
  88. timezoneId: 'Asia/Tokyo',
  89. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  90. })
  91. .then(page => {
  92. const startTime = new Date().getTime();
  93. const getTimerTime = () => new Date().getTime() - startTime;
  94. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  95. const gotoUrlAndWaitForTweet = () => page.goto(url, { waitUntil: 'load', timeout: Math.min(10000, getTimeout()) })
  96. .then(() => Promise.race([
  97. page.waitForSelector('article', { state: 'attached', timeout: Math.min(10000, getTimeout()) }),
  98. page.click('#placeholder+#ScriptLoadFailure input[value="Try again"]', { timeout: getTimeout() }),
  99. page.waitForSelector('div[role="button"]>div>span>:text-matches("^やりなおす|更新$")', { state: 'attached', timeout: getTimeout() }).then(() => page.reload({ timeout: getTimeout() })),
  100. ]))
  101. .catch(err => {
  102. if (err.name === 'TimeoutError' && webshotDelay > getTimerTime()) {
  103. logger.warn(`navigation timed out after ${getTimerTime()} ms, retrying...`);
  104. return gotoUrlAndWaitForTweet();
  105. }
  106. throw err;
  107. });
  108. page.setViewportSize({
  109. width: width / zoomFactor,
  110. height: height / zoomFactor,
  111. })
  112. .then(() => page.route('*://video.twimg.com/**', route => route.abort().then(() => page.evaluate(videoUrl => {
  113. let videoUrls = window['__scrapedVideoUrls'];
  114. if (!videoUrls)
  115. videoUrls = window['__scrapedVideoUrls'] = [];
  116. if (!videoUrls.includes(videoUrl)) {
  117. videoUrls.push(videoUrl);
  118. return videoUrl;
  119. }
  120. }, route.request().url())).then(videoUrl => {
  121. if (videoUrl)
  122. logger.info(`scraped ${route.request().url()} from page`);
  123. }).catch(err => {
  124. logger.error(`error aborting request to ${route.request().url()}, error: ${err}`);
  125. })))
  126. .then(gotoUrlAndWaitForTweet)
  127. .then(() => page.addStyleTag({
  128. content: 'header,#layers{display:none!important}article{background-color:transparent!important}' +
  129. '[data-testid="caret"],[role="group"],[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]~div{display:none}',
  130. }))
  131. .then(() => page.addStyleTag({
  132. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
  133. '*{-webkit-font-smoothing:antialiased!important}',
  134. }))
  135. .then(() => page.evaluate(() => {
  136. const poll = setInterval(() => {
  137. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  138. if (container.querySelector('div[role="button"] svg')) {
  139. container.innerHTML = container.innerHTML;
  140. clearInterval(poll);
  141. }
  142. });
  143. }, 250);
  144. }))
  145. .then(() => page.waitForSelector('xpath=//section/*/*/div[.//article[not(.//time[not(ancestor::div[@aria-labelledby])])]]', { state: 'attached', timeout: getTimeout() }))
  146. .then(handle => handle.evaluate(div => div.classList.add('mainTweet'))
  147. .then(() => page.addStyleTag({ content: 'div.mainTweet~div{display:none;}' }))
  148. .then(() => handle))
  149. .then(handle => handle.$$('xpath=(.|preceding-sibling::*)//a[contains(@href,"content_you_see")]/../../..//*[@role="button"]')
  150. .then(sensitiveToggles => {
  151. const count = sensitiveToggles.length;
  152. if (count)
  153. logger.info(`found ${count} sensitive ${count === 1 ? 'tweet' : 'tweets'} on page, uncollapsing...`);
  154. return (0, utils_1.chainPromises)(sensitiveToggles.map(toggle => () => toggle.click()));
  155. })
  156. .then(() => handle))
  157. .then(handle => handle.$('[data-testid="tweet"]').then(owner => owner ? handle : null))
  158. .catch((err) => {
  159. if (err.name !== 'TimeoutError')
  160. throw err;
  161. logger.warn(`${err} (${getTimerTime()} ms)`);
  162. return page.evaluate(() => document.documentElement.outerHTML).then(html => {
  163. const path = temp.path({ suffix: '.html' });
  164. fs.writeFileSync(path, html);
  165. logger.warn(`saved debug html to ${path}`);
  166. }).then(() => page.route('**/*', route => route.abort().catch(() => { }))).then(() => page.screenshot({ fullPage: true })).then(screenshot => {
  167. sharpToFile(sharp(screenshot).jpeg({ quality: 90 })).then(fileUri => {
  168. logger.warn(`saved debug screenshot to ${fileUri.substring(7)}`);
  169. });
  170. }).then(() => null);
  171. })
  172. .then(handle => {
  173. if (handle === null)
  174. throw new puppeteer.errors.TimeoutError();
  175. let cropTop;
  176. return (0, utils_1.chainPromises)(morePostProcessings.map(func => () => func(page, handle)))
  177. .then(() => (0, util_1.promisify)(setTimeout)(getTimeout()))
  178. .then(() => page.evaluate(() => document.documentElement.scrollTop))
  179. .then(scrollTop => { cropTop = scrollTop * zoomFactor; })
  180. .then(() => page.evaluate(() => document.activeElement.blur()))
  181. .then(() => handle.evaluateHandle(div => {
  182. const minHeight = Number(div.style.transform.match(/translateY\((.+)px\)/)[1]) + div.offsetHeight;
  183. const parentDiv = div.parentElement;
  184. parentDiv.setAttribute('style', `min-height: ${minHeight}px; margin: 0 -1px; padding: 0 1px`);
  185. return parentDiv;
  186. }))
  187. .catch(err => {
  188. logger.error(`error while parsing content height, failing this webshot`);
  189. throw err;
  190. })
  191. .then(parentDivHandle => parentDivHandle.screenshot())
  192. .then(screenshot => [screenshot, cropTop]);
  193. })
  194. .then(([screenshot, cropTop]) => {
  195. new pngjs_1.PNG({
  196. filterType: 4,
  197. deflateLevel: 0,
  198. }).on('parsed', function () {
  199. let png = this;
  200. if (cropTop > 0) {
  201. logger.info(`cropping screenshot at y offset ${cropTop}...`);
  202. png = new pngjs_1.PNG({ width: this.width, height: this.height - cropTop });
  203. this.bitblt(png, 0, cropTop, png.width, png.height, 0, 0);
  204. }
  205. sharpToFile(jpeg(png.pack())).then(path => {
  206. logger.info(`finished webshot for ${url}`);
  207. resolve({ path, boundary: png.height });
  208. });
  209. }).parse(screenshot);
  210. })
  211. .catch(err => {
  212. if (err instanceof Error && err.name !== 'TimeoutError')
  213. 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. }
  225. else
  226. return data.path;
  227. }).catch(error => this.reconnect(error)
  228. .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings)));
  229. };
  230. this.fetchMedia = (url) => (url.match(/^file:/) ? Promise.resolve(url) : axiosGet(url, 'arraybuffer').then(data => {
  231. var _a;
  232. return (ext => {
  233. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  234. fs.writeFileSync(mediaTempFilePath, Buffer.from(data));
  235. return `file://${mediaTempFilePath}`;
  236. })(((_a = (/\?format=([a-z]+)&/.exec(url))) !== null && _a !== void 0 ? _a : (/.*\/.*\.([^?]+)/.exec(url)))[1]);
  237. })).then(path => {
  238. switch ((/.*\.(.*?)$/.exec(path) || [])[1]) {
  239. case 'jpg':
  240. case 'png':
  241. return koishi_1.Message.Image(path);
  242. case 'mp4':
  243. case 'ts':
  244. return koishi_1.Message.Video(path);
  245. }
  246. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  247. throw Error();
  248. });
  249. if (this.mode = mode) {
  250. onready();
  251. }
  252. else {
  253. this.wsUrl = wsUrl;
  254. this.connect(onready);
  255. }
  256. }
  257. webshot(tweets, callback, webshotDelay) {
  258. const promises = tweets.map((twi, index) => {
  259. let promise = (0, util_1.promisify)(setTimeout)(webshotDelay / 4 * index).then(() => {
  260. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  261. });
  262. const originTwi = twi.retweeted_status || twi;
  263. let messageChain = '';
  264. let truncatedAt;
  265. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  266. author += `${new Date(twi.created_at)}\n`;
  267. if (twi.retweeted_status)
  268. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  269. let text = originTwi.full_text;
  270. promise = promise.then(() => {
  271. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  272. originTwi.entities.urls.forEach(url => {
  273. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  274. });
  275. }
  276. if (originTwi.extended_entities) {
  277. originTwi.extended_entities.media.forEach(media => {
  278. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  279. });
  280. }
  281. if (this.mode > 0)
  282. messageChain += (author + xmlEntities.decode(text));
  283. });
  284. if (this.mode === 0) {
  285. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  286. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay, (_, tweetHandle) => tweetHandle.evaluate(div => {
  287. try {
  288. const selector = '[data-testid="tweet"] :nth-child(2)>:first-child a';
  289. const getProfileUrl = () => (div.querySelector(selector) || { href: '' }).href;
  290. const ownerProfileUrl = getProfileUrl();
  291. const bottom = div;
  292. while (div = div.previousElementSibling) {
  293. if (getProfileUrl() !== ownerProfileUrl || div === bottom.previousElementSibling)
  294. continue;
  295. const top = document.documentElement.scrollTop = window.scrollY + div.getBoundingClientRect().top;
  296. if (top > 10)
  297. return div.querySelector('article a[aria-label]').href.replace(/.*\/status\//, '');
  298. }
  299. }
  300. catch (_a) { }
  301. document.documentElement.scrollTop = 0;
  302. }).then((id) => {
  303. if (!id)
  304. return;
  305. logger.info(`thread too long, truncating at tweet ${id}...`);
  306. truncatedAt = id;
  307. }), (page, tweetHandle) => tweetHandle.evaluate(div => {
  308. const cardMediaDiv = div.querySelector('div[data-testid^="card.layout"][data-testid$=".media"]');
  309. const cardMedia = cardMediaDiv === null || cardMediaDiv === void 0 ? void 0 : cardMediaDiv.querySelector('img, video');
  310. if (!cardMedia)
  311. return {};
  312. let match;
  313. if (cardMedia.tagName === 'IMG' && typeof cardMedia.getAttribute('src') === 'string') {
  314. match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardMedia.getAttribute('src'));
  315. }
  316. if (cardMedia.tagName === 'VIDEO' && typeof cardMedia.getAttribute('poster') === 'string') {
  317. match = /^(.*\/amplify_video_thumb\/(\d+)\/img\/.*$)/.exec(cardMedia.getAttribute('poster'));
  318. }
  319. if (!match)
  320. return {};
  321. const [media_url_https, id_str] = match.slice(1);
  322. return {
  323. type: cardMedia.tagName,
  324. entityBase: {
  325. media_url: media_url_https.replace(/^https/, 'http'),
  326. media_url_https,
  327. url: '',
  328. display_url: '',
  329. expanded_url: '',
  330. id: Number(id_str),
  331. id_str,
  332. sizes: undefined,
  333. }
  334. };
  335. }).then(({ type, entityBase }) => {
  336. var _a;
  337. if (!type)
  338. return;
  339. const media = (_a = (originTwi.extended_entities || (originTwi.extended_entities = {}))).media || (_a.media = []);
  340. if (media.some(entity => entity.id_str === entityBase.id_str))
  341. return;
  342. if (type === 'IMG')
  343. media.push(Object.assign(Object.assign({}, entityBase), { type: 'photo' }));
  344. if (type === 'VIDEO')
  345. page.evaluate(id_str => {
  346. var _a;
  347. return (_a = window['__scrapedVideoUrls']) === null || _a === void 0 ? void 0 : _a.find(videoUrl => new RegExp(`.*/amplify_video/${id_str}/pl/[^/]*\\.m3u8(?:\\?|$)`).exec(videoUrl));
  348. }, entityBase.id_str).then(streamlistUrl => axiosGet(streamlistUrl, 'text')
  349. .then(utils_1.M3u8.parseStreamlist)
  350. .then(playlists => playlists.sort((pl1, pl2) => pl2.bandwidth - pl1.bandwidth)[0])
  351. .then(({ bandwidth, playlistPath, resolution }) => {
  352. const [width, height] = /(.*)x(.*)/.exec(resolution).slice(1).map(Number);
  353. const playlistUrl = new URL(playlistPath, streamlistUrl);
  354. return axiosGet(playlistUrl.href, 'text')
  355. .then(playlist => utils_1.M3u8.parsePlaylist(playlist))
  356. .then(({ duration, segmentPaths, extension: ext }) => {
  357. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  358. return (0, utils_1.chainPromises)(segmentPaths.map(path => () => axiosGet(new URL(path, playlistUrl).href, 'arraybuffer').then(data => {
  359. fs.writeFileSync(mediaTempFilePath, Buffer.from(data), { flag: 'a' });
  360. })))
  361. .then(() => ({
  362. duration_millis: duration * 1000,
  363. aspect_ratio: [width, height],
  364. variants: [{
  365. bitrate: bandwidth,
  366. content_type: { mp4: 'video/mp4', ts: 'video/mp2t' }[ext],
  367. url: `file://${mediaTempFilePath}`,
  368. }]
  369. }));
  370. });
  371. })).then(videoInfo => media.push(Object.assign(Object.assign({}, entityBase), { type: 'video', video_info: videoInfo }))).catch(error => {
  372. logger.error(`error while fetching scraped video, error: ${error}`);
  373. logger.warn('unable to fetch scraped video, ignoring...');
  374. });
  375. })))
  376. .then(fileurl => {
  377. if (fileurl)
  378. return koishi_1.Message.Image(fileurl);
  379. return '[截图不可用] ' + author + text;
  380. })
  381. .then(msg => {
  382. if (msg)
  383. messageChain += msg;
  384. });
  385. }
  386. if (1 - this.mode % 2)
  387. promise = promise.then(() => {
  388. if (originTwi.extended_entities) {
  389. return (0, utils_1.chainPromises)(originTwi.extended_entities.media.map(media => () => {
  390. let url;
  391. if (media.type === 'photo') {
  392. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  393. }
  394. else {
  395. url = media.video_info.variants
  396. .filter(variant => variant.bitrate !== undefined)
  397. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  398. .map(variant => variant.url)[0];
  399. }
  400. const altMessage = `\n[失败的${typeInZH[media.type].type}:${url}]`;
  401. return this.fetchMedia(url)
  402. .catch(error => {
  403. logger.warn('unable to fetch media, sending plain text instead...');
  404. return altMessage;
  405. })
  406. .then(msg => { messageChain += msg; });
  407. }));
  408. }
  409. });
  410. if (this.mode === 0) {
  411. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  412. promise = promise.then(() => {
  413. const urls = originTwi.entities.urls
  414. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  415. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  416. if (urls.length) {
  417. messageChain += urls.join('');
  418. }
  419. });
  420. }
  421. }
  422. promise = promise.then(() => {
  423. if (truncatedAt) {
  424. messageChain += `\n回复此命令查看对话串中更早的推文:\n/twitter_view ${truncatedAt}`;
  425. }
  426. });
  427. if (originTwi.is_quote_status) {
  428. promise = promise.then(() => {
  429. var _a, _b;
  430. const match = /\/status\/(\d+)/.exec((_a = originTwi.quoted_status_permalink) === null || _a === void 0 ? void 0 : _a.expanded);
  431. const blockQuoteIdStr = match ? match[1] : (_b = originTwi.quoted_status) === null || _b === void 0 ? void 0 : _b.id_str;
  432. if (blockQuoteIdStr)
  433. messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${blockQuoteIdStr}`;
  434. });
  435. }
  436. return promise.then(() => {
  437. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  438. logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
  439. let cacheId = twi.id_str;
  440. if (twi.retweeted_status)
  441. cacheId += `,rt:${twi.retweeted_status.id_str}`;
  442. callback(cacheId, messageChain, xmlEntities.decode(text), author);
  443. });
  444. });
  445. return Promise.all(promises).then();
  446. }
  447. }
  448. exports.default = Webshot;