webshot.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 axios_1 = require("axios");
  13. const CallableInstance = require("callable-instance");
  14. const child_process_1 = require("child_process");
  15. const fs_1 = require("fs");
  16. const html_entities_1 = require("html-entities");
  17. const pngjs_1 = require("pngjs");
  18. const puppeteer = require("playwright");
  19. const sharp = require("sharp");
  20. const temp = require("temp");
  21. const util_1 = require("util");
  22. const gifski_1 = require("./gifski");
  23. const loggers_1 = require("./loggers");
  24. const mirai_1 = require("./mirai");
  25. const utils_1 = require("./utils");
  26. const xmlEntities = new html_entities_1.XmlEntities();
  27. const ZHType = (type) => new class extends String {
  28. constructor() {
  29. super(...arguments);
  30. this.type = super.toString();
  31. this.toString = () => `[${super.toString()}]`;
  32. }
  33. }(type);
  34. const typeInZH = {
  35. photo: ZHType('图片'),
  36. video: ZHType('视频'),
  37. animated_gif: ZHType('GIF'),
  38. };
  39. const logger = loggers_1.getLogger('webshot');
  40. const wsUrl = 'https://ilg-server.ling.uni-stuttgart.de/playwright-ws.json';
  41. class Webshot extends CallableInstance {
  42. constructor(mode, onready) {
  43. super('webshot');
  44. this.connect = (onready) => axios_1.default.get(wsUrl)
  45. .then(res => {
  46. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  47. const browserType = Object.keys(res.data)[0];
  48. return puppeteer[browserType].connect({ wsEndpoint: res.data[browserType] });
  49. })
  50. .then(browser => this.browser = browser)
  51. .then(() => {
  52. logger.info('launched puppeteer browser');
  53. if (onready)
  54. return onready();
  55. })
  56. .catch(error => this.reconnect(error, onready));
  57. this.reconnect = (error, onready) => {
  58. logger.error(`connection error, reason: ${error}`);
  59. logger.warn('trying to reconnect in 2.5s...');
  60. return util_1.promisify(setTimeout)(2500)
  61. .then(() => this.connect(onready));
  62. };
  63. this.extendEntity = (media) => {
  64. logger.info('not working on a tweet');
  65. };
  66. this.renderWebshot = (url, height, webshotDelay) => {
  67. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  68. const sharpToBase64 = (pic) => new Promise(resolve => {
  69. pic.toBuffer().then(buffer => resolve(`data:image/jpeg;base64,${buffer.toString('base64')}`));
  70. });
  71. const promise = new Promise((resolve, reject) => {
  72. const width = 720;
  73. const zoomFactor = 2;
  74. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  75. this.browser.newPage({
  76. bypassCSP: true,
  77. deviceScaleFactor: zoomFactor,
  78. locale: 'ja-JP',
  79. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  80. })
  81. .then(page => {
  82. const startTime = new Date().getTime();
  83. const getTimerTime = () => new Date().getTime() - startTime;
  84. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  85. page.setViewportSize({
  86. width: width / zoomFactor,
  87. height: height / zoomFactor,
  88. })
  89. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  90. // hide header, "more options" button, like and retweet count
  91. .then(() => page.addStyleTag({
  92. 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;}',
  93. }))
  94. .then(() => page.addStyleTag({
  95. content: '*{font-family:-apple-system,SF Pro Display,Hiragino Sans,sans-serif!important}',
  96. }))
  97. // remove listeners
  98. .then(() => page.evaluate(() => {
  99. const poll = setInterval(() => {
  100. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  101. if (container) {
  102. container.innerHTML = container.innerHTML;
  103. clearInterval(poll);
  104. }
  105. });
  106. }, 250);
  107. }))
  108. .then(() => page.waitForSelector('article', { timeout: getTimeout() }))
  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. })
  119. .then(() => page.evaluate(() => {
  120. const cardImg = document.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  121. if (typeof (cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src')) === 'string') {
  122. const match = cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src').match(/^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/);
  123. if (match) {
  124. // tslint:disable-next-line: variable-name
  125. const [media_url_https, id_str] = match.slice(1);
  126. return {
  127. media_url: media_url_https.replace(/^https/, 'http'),
  128. media_url_https,
  129. url: '',
  130. display_url: '',
  131. expanded_url: '',
  132. type: 'photo',
  133. id: Number(id_str),
  134. id_str,
  135. sizes: undefined,
  136. };
  137. }
  138. }
  139. }))
  140. .then(cardImg => { if (cardImg)
  141. this.extendEntity(cardImg); })
  142. .then(() => page.addScriptTag({
  143. content: 'document.documentElement.scrollTop=0;',
  144. }))
  145. .then(() => util_1.promisify(setTimeout)(getTimeout()))
  146. .then(() => page.screenshot())
  147. .then(screenshot => {
  148. new pngjs_1.PNG({
  149. filterType: 4,
  150. deflateLevel: 0,
  151. }).on('parsed', function () {
  152. // remove comment area
  153. // tslint:disable-next-line: no-shadowed-variable
  154. const idx = (x, y) => (this.width * y + x) << 2;
  155. let boundary = null;
  156. let x = zoomFactor * 2;
  157. for (let y = 0; y < this.height; y += zoomFactor) {
  158. if (this.data[idx(x, y)] !== 255 &&
  159. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]) {
  160. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  161. // footer kicks in
  162. boundary = null;
  163. }
  164. else {
  165. boundary = y;
  166. }
  167. break;
  168. }
  169. }
  170. if (boundary !== null) {
  171. logger.info(`found boundary at ${boundary}, cropping image`);
  172. this.data = this.data.slice(0, idx(this.width, boundary));
  173. this.height = boundary;
  174. boundary = null;
  175. x = Math.floor(16 * zoomFactor);
  176. let flag = false;
  177. let cnt = 0;
  178. for (let y = this.height - 1 - zoomFactor; y >= 0; y -= zoomFactor) {
  179. if ((this.data[idx(x, y)] === 255) === flag) {
  180. cnt++;
  181. flag = !flag;
  182. }
  183. else
  184. continue;
  185. // line above the "comment", "retweet", "like", "share" button row
  186. if (cnt === 2) {
  187. boundary = y + 1;
  188. }
  189. // if there are a "retweet" count and "like" count row, this will be the line above it
  190. if (cnt === 4) {
  191. const b = y + 1;
  192. if (Math.abs(this.height - boundary - (boundary - b)) <= 3 * zoomFactor) {
  193. boundary = b;
  194. }
  195. }
  196. // if "retweet" count and "like" count are two rows, this will be the line above the first
  197. if (cnt === 6) {
  198. const c = y + 1;
  199. if (Math.abs(this.height - boundary - 2 * (boundary - c)) <= 3 * zoomFactor) {
  200. boundary = c;
  201. break;
  202. }
  203. }
  204. }
  205. if (boundary != null) {
  206. logger.info(`found boundary at ${boundary}, trimming image`);
  207. this.data = this.data.slice(0, idx(this.width, boundary));
  208. this.height = boundary;
  209. }
  210. sharpToBase64(jpeg(this.pack())).then(base64 => {
  211. logger.info(`finished webshot for ${url}`);
  212. resolve({ base64, boundary });
  213. });
  214. }
  215. else if (height >= 8 * 1920) {
  216. logger.warn('too large, consider as a bug, returning');
  217. sharpToBase64(jpeg(this.pack())).then(base64 => {
  218. resolve({ base64, boundary: 0 });
  219. });
  220. }
  221. else {
  222. logger.info('unable to find boundary, try shooting a larger image');
  223. resolve({ base64: '', boundary });
  224. }
  225. }).parse(screenshot);
  226. })
  227. .catch(err => {
  228. if (err.name !== 'TimeoutError')
  229. throw err;
  230. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  231. resolve({ base64: '', boundary: 0 });
  232. })
  233. .finally(() => page.close());
  234. })
  235. .catch(reject);
  236. });
  237. return promise.then(data => {
  238. if (data.boundary === null)
  239. return this.renderWebshot(url, height + 1920, webshotDelay);
  240. else
  241. return data.base64;
  242. }).catch(error => new Promise(resolve => this.reconnect(error, resolve))
  243. .then(() => this.renderWebshot(url, height, webshotDelay)));
  244. };
  245. this.fetchMedia = (url) => {
  246. const gif = (data) => {
  247. const matchDims = url.match(/\/(\d+)x(\d+)\//);
  248. if (matchDims) {
  249. const [width, height] = matchDims.slice(1).map(Number);
  250. const factor = width + height > 1600 ? 0.375 : 0.5;
  251. return gifski_1.default(data, width * factor);
  252. }
  253. return gifski_1.default(data);
  254. };
  255. return new Promise((resolve, reject) => {
  256. logger.info(`fetching ${url}`);
  257. axios_1.default({
  258. method: 'get',
  259. url,
  260. responseType: 'arraybuffer',
  261. timeout: 150000,
  262. }).then(res => {
  263. if (res.status === 200) {
  264. logger.info(`successfully fetched ${url}`);
  265. resolve(res.data);
  266. }
  267. else {
  268. logger.error(`failed to fetch ${url}: ${res.status}`);
  269. reject();
  270. }
  271. }).catch(err => {
  272. logger.error(`failed to fetch ${url}: ${err.message}`);
  273. reject();
  274. });
  275. }).then(data => {
  276. var _a;
  277. return ((ext) => __awaiter(this, void 0, void 0, function* () {
  278. switch (ext) {
  279. case 'jpg':
  280. return { mimetype: 'image/jpeg', data };
  281. case 'png':
  282. return { mimetype: 'image/png', data };
  283. case 'mp4':
  284. try {
  285. return { mimetype: 'video/x-matroska', data: yield gif(data) };
  286. }
  287. catch (err) {
  288. logger.error(err);
  289. throw Error(err);
  290. }
  291. }
  292. }))(((_a = url.match(/\?format=([a-z]+)&/)) !== null && _a !== void 0 ? _a : url.match(/.*\/.*\.([^?]+)/))[1])
  293. .catch(() => {
  294. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  295. throw Error();
  296. });
  297. }).then(typedData => `data:${typedData.mimetype};base64,${Buffer.from(typedData.data).toString('base64')}`);
  298. };
  299. // tslint:disable-next-line: no-conditional-assignment
  300. if (this.mode = mode) {
  301. onready();
  302. }
  303. else {
  304. this.connect(onready);
  305. }
  306. }
  307. webshot(tweets, uploader, callback, webshotDelay) {
  308. let promise = new Promise(resolve => {
  309. resolve();
  310. });
  311. tweets.forEach(twi => {
  312. promise = promise.then(() => {
  313. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  314. });
  315. const originTwi = twi.retweeted_status || twi;
  316. const messageChain = [];
  317. // text processing
  318. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  319. if (twi.retweeted_status)
  320. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  321. let text = originTwi.full_text;
  322. promise = promise.then(() => {
  323. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  324. originTwi.entities.urls.forEach(url => {
  325. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  326. });
  327. }
  328. if (originTwi.extended_entities) {
  329. originTwi.extended_entities.media.forEach(media => {
  330. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  331. });
  332. }
  333. if (this.mode > 0)
  334. messageChain.push(mirai_1.Message.Plain(author + xmlEntities.decode(text)));
  335. });
  336. // invoke webshot
  337. if (this.mode === 0) {
  338. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  339. this.extendEntity = (cardImg) => {
  340. var _a, _b;
  341. originTwi.extended_entities = Object.assign(Object.assign({}, originTwi.extended_entities), { media: [
  342. ...(_b = (_a = originTwi.extended_entities) === null || _a === void 0 ? void 0 : _a.media) !== null && _b !== void 0 ? _b : [],
  343. cardImg,
  344. ] });
  345. };
  346. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  347. .then(base64url => {
  348. if (base64url)
  349. return uploader(mirai_1.Message.Image('', base64url, url), () => mirai_1.Message.Plain(author + text));
  350. return mirai_1.Message.Plain(author + text);
  351. })
  352. .then(msg => {
  353. if (msg)
  354. messageChain.push(msg);
  355. });
  356. }
  357. // fetch extra entities
  358. // tslint:disable-next-line: curly
  359. if (1 - this.mode % 2)
  360. promise = promise.then(() => {
  361. if (originTwi.extended_entities) {
  362. return utils_1.chainPromises(originTwi.extended_entities.media.map(media => {
  363. let url;
  364. if (media.type === 'photo') {
  365. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  366. }
  367. else {
  368. url = media.video_info.variants
  369. .filter(variant => variant.bitrate !== undefined)
  370. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  371. .map(variant => variant.url)[0]; // largest video
  372. }
  373. const altMessage = mirai_1.Message.Plain(`\n[失败的${typeInZH[media.type].type}:${url}]`);
  374. return this.fetchMedia(url)
  375. .then(base64url => {
  376. let mediaPromise = Promise.resolve([]);
  377. if (base64url.match(/^data:video.+;/)) {
  378. // demux mkv into gif and pcm16le
  379. const input = () => Buffer.from(base64url.split(',')[1], 'base64');
  380. const imgReturns = child_process_1.spawnSync('ffmpeg', [
  381. '-i', '-',
  382. '-an',
  383. '-f', 'gif',
  384. '-c', 'copy',
  385. '-',
  386. ], { stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input() });
  387. const voiceReturns = child_process_1.spawnSync('ffmpeg', [
  388. '-i', '-',
  389. '-vn',
  390. '-f', 's16le',
  391. '-ac', '1',
  392. '-ar', '24000',
  393. '-',
  394. ], { stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input() });
  395. if (!imgReturns.stdout.byteLength)
  396. throw Error(imgReturns.stderr.toString());
  397. base64url = `data:image/gif;base64,${imgReturns.stdout.toString('base64')}`;
  398. if (voiceReturns.stdout.byteLength) {
  399. logger.info('video has an audio track, trying to convert it to voice...');
  400. temp.track();
  401. const inputFile = temp.openSync();
  402. fs_1.writeSync(inputFile.fd, voiceReturns.stdout);
  403. child_process_1.spawnSync('silk-encoder', [
  404. inputFile.path,
  405. inputFile.path + '.silk',
  406. '-tencent',
  407. ]);
  408. temp.cleanup();
  409. if (fs_1.existsSync(inputFile.path + '.silk')) {
  410. if (fs_1.statSync(inputFile.path + '.silk').size !== 0) {
  411. const audioBase64Url = `data:audio/silk-v3;base64,${fs_1.readFileSync(inputFile.path + '.silk').toString('base64')}`;
  412. mediaPromise = mediaPromise.then(chain => uploader(mirai_1.Message.Voice('', audioBase64Url, `${url} as amr`), () => mirai_1.Message.Plain('\n[失败的语音]'))
  413. .then(msg => [msg, ...chain]));
  414. }
  415. fs_1.unlinkSync(inputFile.path + '.silk');
  416. }
  417. }
  418. }
  419. return mediaPromise.then(chain => uploader(mirai_1.Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage)
  420. .then(msg => [msg, ...chain]));
  421. })
  422. .catch(error => {
  423. logger.error(`unable to fetch media, error: ${error}`);
  424. logger.warn('unable to fetch media, sending plain text instead...');
  425. return [altMessage];
  426. })
  427. .then(msgs => {
  428. messageChain.push(...msgs);
  429. });
  430. }));
  431. }
  432. });
  433. // append URLs, if any
  434. if (this.mode === 0) {
  435. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  436. promise = promise.then(() => {
  437. const urls = originTwi.entities.urls
  438. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  439. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  440. if (urls.length) {
  441. messageChain.push(mirai_1.Message.Plain(urls.join('')));
  442. }
  443. });
  444. }
  445. }
  446. // refer to quoted tweet, if any
  447. if (originTwi.is_quote_status) {
  448. promise = promise.then(() => {
  449. messageChain.push(mirai_1.Message.Plain(`\n回复此命令查看引用的推文:\n/twitter_view ${originTwi.quoted_status_id_str}`));
  450. });
  451. }
  452. promise.then(() => {
  453. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  454. logger.info(JSON.stringify(messageChain));
  455. callback(messageChain, xmlEntities.decode(text), author);
  456. });
  457. });
  458. return promise.catch(err => logger.error(`failed to shoot webshot, error: ${JSON.stringify(err)}`));
  459. }
  460. }
  461. exports.default = Webshot;