webshot.js 20 KB

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