webshot.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const fs_1 = 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: 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. (0, fs_1.writeFileSync)(path, html);
  165. logger.warn(`saved debug html to ${path}`);
  166. }).then(() => page.route('**/*', route => route.abort().catch(err => {
  167. logger.error(`error aborting all requests for debug screenshot, error: ${err}`);
  168. }))).then(() => page.screenshot({ fullPage: true })).then(screenshot => {
  169. sharpToFile(sharp(screenshot).jpeg({ quality: 90 })).then(fileUri => {
  170. logger.warn(`saved debug screenshot to ${fileUri.substring(7)}`);
  171. });
  172. }).then(() => null);
  173. })
  174. .then(handle => {
  175. if (handle === null)
  176. throw new puppeteer.errors.TimeoutError();
  177. let cropTop;
  178. return (0, utils_1.chainPromises)(morePostProcessings.map(func => () => func(page, handle)))
  179. .then(() => (0, util_1.promisify)(setTimeout)(getTimeout()))
  180. .then(() => page.evaluate(() => document.documentElement.scrollTop))
  181. .then(scrollTop => { cropTop = scrollTop * zoomFactor; })
  182. .then(() => page.evaluate(() => document.activeElement.blur()))
  183. .then(() => handle.evaluateHandle(div => {
  184. const minHeight = Number(div.style.transform.match(/translateY\((.+)px\)/)[1]) + div.offsetHeight;
  185. const parentDiv = div.parentElement;
  186. parentDiv.setAttribute('style', `min-height: ${minHeight}px; margin: 0 -1px; padding: 0 1px`);
  187. return parentDiv;
  188. }))
  189. .catch(err => {
  190. logger.error(`error while parsing content height, failing this webshot`);
  191. throw err;
  192. })
  193. .then(parentDivHandle => parentDivHandle.screenshot())
  194. .then(screenshot => [screenshot, cropTop]);
  195. })
  196. .then(([screenshot, cropTop]) => {
  197. new pngjs_1.PNG({
  198. filterType: 4,
  199. deflateLevel: 0,
  200. }).on('parsed', function () {
  201. let png = this;
  202. if (cropTop > 0) {
  203. logger.info(`cropping screenshot at y offset ${cropTop}...`);
  204. png = new pngjs_1.PNG({ width: this.width, height: this.height - cropTop });
  205. this.bitblt(png, 0, cropTop, png.width, png.height, 0, 0);
  206. }
  207. sharpToFile(jpeg(png.pack())).then(path => {
  208. logger.info(`finished webshot for ${url}`);
  209. resolve({ path, boundary: png.height });
  210. });
  211. }).parse(screenshot);
  212. })
  213. .catch(err => {
  214. if (err instanceof Error && err.name !== 'TimeoutError')
  215. throw err;
  216. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  217. resolve({ path: '', boundary: 0 });
  218. })
  219. .finally(() => { page.close(); });
  220. })
  221. .catch(reject);
  222. });
  223. return promise.then(data => {
  224. if (data.boundary === null) {
  225. return this.renderWebshot(url, height + 1920, webshotDelay, ...morePostProcessings);
  226. }
  227. else
  228. return data.path;
  229. }).catch(error => this.reconnect(error)
  230. .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings)));
  231. };
  232. this.fetchMedia = (url) => (url.match(/^file:/) ? Promise.resolve(url) : axiosGet(url, 'arraybuffer').then(data => {
  233. var _a;
  234. return (ext => {
  235. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  236. (0, fs_1.writeFileSync)(mediaTempFilePath, Buffer.from(data));
  237. return `file://${mediaTempFilePath}`;
  238. })(((_a = (/\?format=([a-z]+)&/.exec(url))) !== null && _a !== void 0 ? _a : (/.*\/.*\.([^?]+)/.exec(url)))[1]);
  239. })).then(path => {
  240. switch ((/.*\.(.*?)$/.exec(path) || [])[1]) {
  241. case 'jpg':
  242. case 'png':
  243. return koishi_1.Message.Image(path);
  244. case 'mp4':
  245. return koishi_1.Message.Video(path);
  246. }
  247. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  248. throw Error();
  249. });
  250. if (this.mode = mode) {
  251. onready();
  252. }
  253. else {
  254. this.wsUrl = wsUrl;
  255. this.connect(onready);
  256. }
  257. }
  258. webshot(tweets, callback, webshotDelay) {
  259. const promises = tweets.map((twi, index) => {
  260. let promise = (0, util_1.promisify)(setTimeout)(webshotDelay / 4 * index).then(() => {
  261. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  262. });
  263. const originTwi = twi.retweeted_status || twi;
  264. let messageChain = '';
  265. let truncatedAt;
  266. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  267. author += `${new Date(twi.created_at)}\n`;
  268. if (twi.retweeted_status)
  269. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  270. let text = originTwi.full_text;
  271. promise = promise.then(() => {
  272. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  273. originTwi.entities.urls.forEach(url => {
  274. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  275. });
  276. }
  277. if (originTwi.extended_entities) {
  278. originTwi.extended_entities.media.forEach(media => {
  279. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  280. });
  281. }
  282. if (this.mode > 0)
  283. messageChain += (author + xmlEntities.decode(text));
  284. });
  285. if (this.mode === 0) {
  286. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  287. const extendEntity = (cardMedia) => {
  288. var _a;
  289. return (media => {
  290. if (!media.some(entity => entity.id_str === cardMedia.id_str))
  291. media.push(cardMedia);
  292. })((_a = (originTwi.extended_entities || (originTwi.extended_entities = {}))).media || (_a.media = []));
  293. };
  294. const truncateLongThread = (atId) => {
  295. if (!atId)
  296. return;
  297. logger.info(`thread too long, truncating at tweet ${atId}...`);
  298. truncatedAt = atId;
  299. };
  300. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay, (_, tweetHandle) => tweetHandle.evaluate(div => {
  301. try {
  302. const selector = '[data-testid="tweet"] :nth-child(2)>:first-child a';
  303. const getProfileUrl = () => (div.querySelector(selector) || { href: '' }).href;
  304. const ownerProfileUrl = getProfileUrl();
  305. const bottom = div;
  306. while (div = div.previousElementSibling) {
  307. if (getProfileUrl() !== ownerProfileUrl || div === bottom.previousElementSibling)
  308. continue;
  309. const top = document.documentElement.scrollTop = window.scrollY + div.getBoundingClientRect().top;
  310. if (top > 10)
  311. return div.querySelector('article a[aria-label]').href.replace(/.*\/status\//, '');
  312. }
  313. }
  314. catch (_a) { }
  315. document.documentElement.scrollTop = 0;
  316. }).then(truncateLongThread), (page, tweetHandle) => tweetHandle.evaluate(div => {
  317. const cardMedia = div.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img, video');
  318. let match;
  319. if ((cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.tagName) === 'IMG' && typeof (cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.getAttribute('src')) === 'string') {
  320. match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.getAttribute('src'));
  321. }
  322. if ((cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.tagName) === 'VIDEO' && typeof (cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.getAttribute('poster')) === 'string') {
  323. match = /^(.*\/amplify_video_thumb\/(\d+)\/img\/.*$)/.exec(cardMedia === null || cardMedia === void 0 ? void 0 : cardMedia.getAttribute('poster'));
  324. }
  325. if (match) {
  326. const [media_url_https, id_str] = match.slice(1);
  327. return {
  328. type: cardMedia.tagName,
  329. entityBase: {
  330. media_url: media_url_https.replace(/^https/, 'http'),
  331. media_url_https,
  332. url: '',
  333. display_url: '',
  334. expanded_url: '',
  335. id: Number(id_str),
  336. id_str,
  337. sizes: undefined,
  338. }
  339. };
  340. }
  341. return {};
  342. }).then(({ type, entityBase }) => {
  343. if (type === 'IMG')
  344. extendEntity(Object.assign(Object.assign({}, entityBase), { type: 'photo' }));
  345. if (type === 'VIDEO')
  346. page.evaluate(id_str => {
  347. var _a;
  348. return (_a = window['__scrapedVideoUrls']) === null || _a === void 0 ? void 0 : _a.filter(videoUrl => new RegExp(`.*/amplify_video/${id_str}.*\\.m3u8(?:\\?|$)`).exec(videoUrl));
  349. }, entityBase.id_str).then(videoUrls => {
  350. if (videoUrls && videoUrls.length) {
  351. Promise.all(videoUrls.map(streamlistUrl => axiosGet(streamlistUrl, 'text')
  352. .then(streamlist => utils_1.M3u8.parseStreamlist(streamlist)[0])
  353. .then(({ bandwidth, playlistPath, resolution }) => {
  354. const [width, height] = /(.*)x(.*)/.exec(resolution).slice(1).map(Number);
  355. const playlistUrl = new URL(playlistPath, streamlistUrl);
  356. const mediaTempFilePath = temp.path({ suffix: `.mp4` });
  357. return axiosGet(playlistUrl.href, 'text')
  358. .then(playlist => utils_1.M3u8.parsePlaylist(playlist))
  359. .then(({ duration, segmentPaths }) => (0, utils_1.chainPromises)(segmentPaths.map(path => () => axiosGet(new URL(path, playlistUrl).href, 'arraybuffer').then(data => {
  360. (0, fs_1.writeFileSync)(mediaTempFilePath, Buffer.from(data), { flag: 'a' });
  361. }))).then(() => ({
  362. duration_millis: duration * 1000,
  363. aspect_ratio: [width, height],
  364. variants: [{
  365. bitrate: bandwidth,
  366. content_type: 'video/mp4',
  367. url: `file://${mediaTempFilePath}`,
  368. }]
  369. })));
  370. }))).then(videoInfos => videoInfos.reduce((vi1, vi2) => (Object.assign(Object.assign({}, vi1), { variants: vi1.variants.concat(vi2.variants) })))).then(videoInfo => extendEntity(Object.assign(Object.assign({}, entityBase), { type: 'video', video_info: videoInfo }))).catch(error => {
  371. logger.warn('unable to fetch scraped video, ignoring...');
  372. });
  373. }
  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;