webshot.js 23 KB

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