webshot.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const util_1 = require("util");
  4. const axios_1 = require("axios");
  5. const CallableInstance = require("callable-instance");
  6. const html_entities_1 = require("html-entities");
  7. const pngjs_1 = require("pngjs");
  8. const puppeteer = require("playwright");
  9. const sharp = require("sharp");
  10. const loggers_1 = require("./loggers");
  11. const koishi_1 = require("./koishi");
  12. const utils_1 = require("./utils");
  13. const xmlEntities = new html_entities_1.XmlEntities();
  14. const ZHType = (type) => new class extends String {
  15. constructor() {
  16. super(...arguments);
  17. this.type = super.toString();
  18. this.toString = () => `[${super.toString()}]`;
  19. }
  20. }(type);
  21. const typeInZH = {
  22. photo: ZHType('图片'),
  23. video: ZHType('视频'),
  24. animated_gif: ZHType('GIF'),
  25. };
  26. const logger = loggers_1.getLogger('webshot');
  27. class Webshot extends CallableInstance {
  28. constructor(wsUrl, mode, onready) {
  29. super('webshot');
  30. this.connect = (onready) => axios_1.default.get(this.wsUrl)
  31. .then(res => {
  32. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  33. const browserType = Object.keys(res.data)[0];
  34. return puppeteer[browserType]
  35. .connect({ wsEndpoint: res.data[browserType] });
  36. })
  37. .then(browser => this.browser = browser)
  38. .then(() => {
  39. logger.info('launched puppeteer browser');
  40. if (onready)
  41. return onready();
  42. })
  43. .catch(error => this.reconnect(error, onready));
  44. this.reconnect = (error, onready) => {
  45. logger.error(`connection error, reason: ${error}`);
  46. logger.warn('trying to reconnect in 2.5s...');
  47. return util_1.promisify(setTimeout)(2500)
  48. .then(() => this.connect(onready));
  49. };
  50. this.extendEntity = (media) => {
  51. logger.info('not working on a tweet');
  52. };
  53. this.renderWebshot = (url, height, webshotDelay) => {
  54. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  55. const sharpToBase64 = (pic) => new Promise(resolve => {
  56. pic.toBuffer().then(buffer => resolve(`base64://${buffer.toString('base64')}`));
  57. });
  58. const promise = new Promise((resolve, reject) => {
  59. const width = 720;
  60. const zoomFactor = 2;
  61. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  62. this.browser.newPage({
  63. bypassCSP: true,
  64. deviceScaleFactor: zoomFactor,
  65. locale: 'ja-JP',
  66. timezoneId: 'Asia/Tokyo',
  67. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  68. })
  69. .then(page => {
  70. const startTime = new Date().getTime();
  71. const getTimerTime = () => new Date().getTime() - startTime;
  72. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  73. page.setViewportSize({
  74. width: width / zoomFactor,
  75. height: height / zoomFactor,
  76. })
  77. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  78. .then(() => page.addStyleTag({
  79. content: 'header{display:none!important}path[d=\'M20.207 7.043a1 1 0 0 0-1.414 0L12 13.836 5.207 7.043a1 1 0 0 0-1.414 1.414l7.5 7.5a.996.996 0 0 0 1.414 0l7.5-7.5a1 1 0 0 0 0-1.414z\'],div[role=\'button\']{display: none;}',
  80. }))
  81. .then(() => page.addStyleTag({
  82. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  83. }))
  84. .then(() => page.evaluate(() => {
  85. const poll = setInterval(() => {
  86. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  87. if (container) {
  88. container.innerHTML = container.innerHTML;
  89. clearInterval(poll);
  90. }
  91. });
  92. }, 250);
  93. }))
  94. .then(() => page.waitForSelector('article', { timeout: getTimeout() }))
  95. .catch((err) => {
  96. if (err.name !== 'TimeoutError')
  97. throw err;
  98. logger.warn(`navigation timed out at ${getTimerTime()} seconds`);
  99. return null;
  100. })
  101. .then(handle => {
  102. if (handle === null)
  103. throw new puppeteer.errors.TimeoutError();
  104. })
  105. .then(() => page.evaluate(() => {
  106. const cardImg = document.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  107. if (typeof (cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src')) === 'string') {
  108. const match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src'));
  109. if (match) {
  110. const [media_url_https, id_str] = match.slice(1);
  111. return {
  112. media_url: media_url_https.replace(/^https/, 'http'),
  113. media_url_https,
  114. url: '',
  115. display_url: '',
  116. expanded_url: '',
  117. type: 'photo',
  118. id: Number(id_str),
  119. id_str,
  120. sizes: undefined,
  121. };
  122. }
  123. }
  124. }))
  125. .then(cardImg => {
  126. if (cardImg)
  127. this.extendEntity(cardImg);
  128. })
  129. .then(() => page.addScriptTag({
  130. content: 'document.documentElement.scrollTop=0;',
  131. }))
  132. .then(() => util_1.promisify(setTimeout)(getTimeout()))
  133. .then(() => page.screenshot())
  134. .then(screenshot => {
  135. new pngjs_1.PNG({
  136. filterType: 4,
  137. deflateLevel: 0,
  138. }).on('parsed', function () {
  139. const idx = (x, y) => (this.width * y + x) << 2;
  140. let boundary = null;
  141. let x = zoomFactor * 2;
  142. for (let y = 0; y < this.height; y += zoomFactor) {
  143. if (this.data[idx(x, y)] !== 255 &&
  144. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]) {
  145. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  146. boundary = null;
  147. }
  148. else {
  149. boundary = y;
  150. }
  151. break;
  152. }
  153. }
  154. if (boundary !== null) {
  155. logger.info(`found boundary at ${boundary}, cropping image`);
  156. this.data = this.data.slice(0, idx(this.width, boundary));
  157. this.height = boundary;
  158. boundary = null;
  159. x = Math.floor(16 * zoomFactor);
  160. let flag = false;
  161. let cnt = 0;
  162. for (let y = this.height - 1 - zoomFactor; y >= 0; y -= zoomFactor) {
  163. if ((this.data[idx(x, y)] === 255) === flag) {
  164. cnt++;
  165. flag = !flag;
  166. }
  167. else
  168. continue;
  169. if (cnt === 2) {
  170. boundary = y + 1;
  171. }
  172. if (cnt === 4) {
  173. const b = y + 1;
  174. if (Math.abs(this.height - boundary - (boundary - b)) <= 3 * zoomFactor) {
  175. boundary = b;
  176. }
  177. }
  178. if (cnt === 6) {
  179. const c = y + 1;
  180. if (Math.abs(this.height - boundary - 2 * (boundary - c)) <= 3 * zoomFactor) {
  181. boundary = c;
  182. break;
  183. }
  184. }
  185. }
  186. if (boundary !== null) {
  187. logger.info(`found boundary at ${boundary}, trimming image`);
  188. this.data = this.data.slice(0, idx(this.width, boundary));
  189. this.height = boundary;
  190. }
  191. sharpToBase64(jpeg(this.pack())).then(base64 => {
  192. logger.info(`finished webshot for ${url}`);
  193. resolve({ base64, boundary });
  194. });
  195. }
  196. else if (height >= 8 * 1920) {
  197. logger.warn('too large, consider as a bug, returning');
  198. sharpToBase64(jpeg(this.pack())).then(base64 => {
  199. resolve({ base64, boundary: 0 });
  200. });
  201. }
  202. else {
  203. logger.info('unable to find boundary, try shooting a larger image');
  204. resolve({ base64: '', boundary });
  205. }
  206. }).parse(screenshot);
  207. })
  208. .catch(err => {
  209. if (err instanceof Error && err.name !== 'TimeoutError')
  210. throw err;
  211. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  212. resolve({ base64: '', boundary: 0 });
  213. })
  214. .finally(() => { page.close(); });
  215. })
  216. .catch(reject);
  217. });
  218. return promise.then(data => {
  219. if (data.boundary === null)
  220. return this.renderWebshot(url, height + 1920, webshotDelay);
  221. else
  222. return data.base64;
  223. }).catch(error => this.reconnect(error)
  224. .then(() => this.renderWebshot(url, height, webshotDelay)));
  225. };
  226. this.fetchMedia = (url) => new Promise((resolve, reject) => {
  227. logger.info(`fetching ${url}`);
  228. axios_1.default({
  229. method: 'get',
  230. url,
  231. responseType: 'arraybuffer',
  232. timeout: 150000,
  233. }).then(res => {
  234. if (res.status === 200) {
  235. logger.info(`successfully fetched ${url}`);
  236. resolve(res.data);
  237. }
  238. else {
  239. logger.error(`failed to fetch ${url}: ${res.status}`);
  240. reject();
  241. }
  242. }).catch(err => {
  243. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  244. reject();
  245. });
  246. }).then(data => {
  247. var _a;
  248. return (ext => {
  249. const base64 = `base64://${Buffer.from(data).toString('base64')}`;
  250. switch (ext) {
  251. case 'jpg':
  252. case 'png':
  253. return koishi_1.message.image(base64);
  254. case 'mp4':
  255. return koishi_1.message.video(base64);
  256. }
  257. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  258. throw Error();
  259. })(((_a = (/\?format=([a-z]+)&/.exec(url))) !== null && _a !== void 0 ? _a : (/.*\/.*\.([^?]+)/.exec(url)))[1]);
  260. });
  261. if (this.mode = mode) {
  262. onready();
  263. }
  264. else {
  265. this.wsUrl = wsUrl;
  266. this.connect(onready);
  267. }
  268. }
  269. webshot(tweets, callback, webshotDelay) {
  270. let promise = new Promise(resolve => {
  271. resolve();
  272. });
  273. tweets.forEach(twi => {
  274. promise = promise.then(() => {
  275. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  276. });
  277. const originTwi = twi.retweeted_status || twi;
  278. let messageChain = '';
  279. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  280. if (twi.retweeted_status)
  281. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  282. let text = originTwi.full_text;
  283. promise = promise.then(() => {
  284. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  285. originTwi.entities.urls.forEach(url => {
  286. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  287. });
  288. }
  289. if (originTwi.extended_entities) {
  290. originTwi.extended_entities.media.forEach(media => {
  291. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  292. });
  293. }
  294. if (this.mode > 0)
  295. messageChain += (author + xmlEntities.decode(text));
  296. });
  297. if (this.mode === 0) {
  298. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  299. this.extendEntity = (cardImg) => {
  300. var _a, _b;
  301. originTwi.extended_entities = Object.assign(Object.assign({}, originTwi.extended_entities), { media: [
  302. ...(_b = (_a = originTwi.extended_entities) === null || _a === void 0 ? void 0 : _a.media) !== null && _b !== void 0 ? _b : [],
  303. cardImg,
  304. ] });
  305. };
  306. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  307. .then(base64url => {
  308. if (base64url)
  309. return koishi_1.message.image(base64url);
  310. return author + text;
  311. })
  312. .then(msg => {
  313. if (msg)
  314. messageChain += msg;
  315. });
  316. }
  317. if (1 - this.mode % 2)
  318. promise = promise.then(() => {
  319. if (originTwi.extended_entities) {
  320. return utils_1.chainPromises(originTwi.extended_entities.media.map(media => {
  321. let url;
  322. if (media.type === 'photo') {
  323. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  324. }
  325. else {
  326. url = media.video_info.variants
  327. .filter(variant => variant.bitrate !== undefined)
  328. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  329. .map(variant => variant.url)[0];
  330. }
  331. const altMessage = `\n[失败的${typeInZH[media.type].type}:${url}]`;
  332. return this.fetchMedia(url)
  333. .catch(error => {
  334. logger.warn('unable to fetch media, sending plain text instead...');
  335. return altMessage;
  336. })
  337. .then(msg => { messageChain += msg; });
  338. }));
  339. }
  340. });
  341. if (this.mode === 0) {
  342. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  343. promise = promise.then(() => {
  344. const urls = originTwi.entities.urls
  345. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  346. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  347. if (urls.length) {
  348. messageChain += urls.join('');
  349. }
  350. });
  351. }
  352. }
  353. if (originTwi.is_quote_status) {
  354. promise = promise.then(() => {
  355. messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${originTwi.quoted_status.id_str}`;
  356. });
  357. }
  358. promise.then(() => {
  359. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  360. logger.info(JSON.stringify(koishi_1.ellipseBase64InMessage(messageChain)));
  361. callback(messageChain, xmlEntities.decode(text), author);
  362. });
  363. });
  364. return promise;
  365. }
  366. }
  367. exports.default = Webshot;