webshot.js 17 KB

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