webshot.js 18 KB

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