webshot.js 21 KB

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