webshot.js 25 KB

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