webshot.js 20 KB

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