webshot.js 19 KB

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