webshot.js 21 KB

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