webshot.js 21 KB

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