webshot.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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("puppeteer");
  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. class Webshot extends CallableInstance {
  41. constructor(mode, onready) {
  42. super('webshot');
  43. // use local Chromium
  44. this.connect = (onready) => puppeteer.connect({ browserURL: 'http://127.0.0.1:9222' })
  45. .then(browser => this.browser = browser)
  46. .then(() => {
  47. logger.info('launched puppeteer browser');
  48. if (onready)
  49. return onready();
  50. })
  51. .catch(error => this.reconnect(error, onready));
  52. this.reconnect = (error, onready) => {
  53. logger.error(`connection error, reason: ${error}`);
  54. logger.warn('trying to reconnect in 2.5s...');
  55. return util_1.promisify(setTimeout)(2500)
  56. .then(() => this.connect(onready));
  57. };
  58. this.extendEntity = (media) => {
  59. logger.info('not working on a tweet');
  60. };
  61. this.renderWebshot = (url, height, webshotDelay) => {
  62. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  63. const sharpToBase64 = (pic) => new Promise(resolve => {
  64. pic.toBuffer().then(buffer => resolve(`data:image/jpeg;base64,${buffer.toString('base64')}`));
  65. });
  66. const promise = new Promise((resolve, reject) => {
  67. const width = 720;
  68. const zoomFactor = 2;
  69. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  70. this.browser.newPage()
  71. .then(page => {
  72. const startTime = new Date().getTime();
  73. const getTimerTime = () => new Date().getTime() - startTime;
  74. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  75. page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  76. .then(() => page.setViewport({
  77. width: width / zoomFactor,
  78. height: height / zoomFactor,
  79. isMobile: true,
  80. deviceScaleFactor: zoomFactor,
  81. }))
  82. .then(() => page.setBypassCSP(true))
  83. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  84. // hide header, "more options" button, like and retweet count
  85. .then(() => page.addStyleTag({
  86. 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;}',
  87. }))
  88. // remove listeners
  89. .then(() => page.evaluate(() => {
  90. const poll = setInterval(() => {
  91. document.querySelectorAll('div[data-testid="placementTracking"]').forEach(container => {
  92. if (container) {
  93. container.innerHTML = container.innerHTML;
  94. clearInterval(poll);
  95. }
  96. });
  97. }, 250);
  98. }))
  99. .then(() => page.waitForSelector('article', { timeout: getTimeout() }))
  100. .catch((err) => {
  101. if (err.name !== 'TimeoutError')
  102. throw err;
  103. logger.warn(`navigation timed out at ${getTimerTime()} seconds`);
  104. return null;
  105. })
  106. .then(handle => {
  107. if (handle === null)
  108. throw new puppeteer.errors.TimeoutError();
  109. })
  110. .then(() => page.evaluate(() => {
  111. const cardImg = document.querySelector('div[data-testid^="card.layout"][data-testid$=".media"] img');
  112. if (typeof (cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src')) === 'string') {
  113. const match = cardImg === null || cardImg === void 0 ? void 0 : cardImg.getAttribute('src').match(/^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/);
  114. if (match) {
  115. // tslint:disable-next-line: variable-name
  116. const [media_url_https, id_str] = match.slice(1);
  117. return {
  118. media_url: media_url_https.replace(/^https/, 'http'),
  119. media_url_https,
  120. url: '',
  121. display_url: '',
  122. expanded_url: '',
  123. type: 'photo',
  124. id: Number(id_str),
  125. id_str,
  126. sizes: undefined,
  127. };
  128. }
  129. }
  130. }))
  131. .then(cardImg => { if (cardImg)
  132. this.extendEntity(cardImg); })
  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. // remove comment area
  144. // tslint:disable-next-line: no-shadowed-variable
  145. const idx = (x, y) => (this.width * y + x) << 2;
  146. let boundary = null;
  147. let x = zoomFactor * 2;
  148. for (let y = 0; y < this.height; y++) {
  149. if (this.data[idx(x, y)] !== 255 &&
  150. this.data[idx(x, y)] === this.data[idx(x + zoomFactor * 10, y)]) {
  151. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  152. // footer kicks in
  153. boundary = null;
  154. }
  155. else {
  156. boundary = y;
  157. }
  158. break;
  159. }
  160. }
  161. if (boundary !== null) {
  162. logger.info(`found boundary at ${boundary}, cropping image`);
  163. this.data = this.data.slice(0, idx(this.width, boundary));
  164. this.height = boundary;
  165. boundary = null;
  166. x = Math.floor(16 * zoomFactor);
  167. let flag = false;
  168. let cnt = 0;
  169. for (let y = this.height - 1; y >= 0; y--) {
  170. if ((this.data[idx(x, y)] === 255) === flag) {
  171. cnt++;
  172. flag = !flag;
  173. }
  174. else
  175. continue;
  176. // line above the "comment", "retweet", "like", "share" button row
  177. if (cnt === 2) {
  178. boundary = y + 1;
  179. }
  180. // if there are a "retweet" count and "like" count row, this will be the line above it
  181. if (cnt === 4) {
  182. const b = y + 1;
  183. if (this.height - boundary - (boundary - b) <= 1) {
  184. boundary = b;
  185. // }
  186. // }
  187. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  188. // if (cnt === 6) {
  189. // const c = y + 1;
  190. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  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.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 => new Promise(resolve => this.reconnect(error, resolve))
  234. .then(() => this.renderWebshot(url, height, webshotDelay)));
  235. };
  236. this.fetchMedia = (url) => {
  237. const gif = (data) => {
  238. const matchDims = url.match(/\/(\d+)x(\d+)\//);
  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.message}`);
  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: 'video/x-matroska', data: yield gif(data) };
  277. }
  278. catch (err) {
  279. logger.error(err);
  280. throw Error(err);
  281. }
  282. }
  283. }))(((_a = url.match(/\?format=([a-z]+)&/)) !== null && _a !== void 0 ? _a : url.match(/.*\/.*\.([^?]+)/))[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. // tslint:disable-next-line: no-conditional-assignment
  291. if (this.mode = mode) {
  292. onready();
  293. }
  294. else {
  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;
  307. const messageChain = [];
  308. // text processing
  309. const author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  310. let text = originTwi.full_text;
  311. promise = promise.then(() => {
  312. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  313. originTwi.entities.urls.forEach(url => {
  314. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  315. });
  316. }
  317. if (originTwi.extended_entities) {
  318. originTwi.extended_entities.media.forEach(media => {
  319. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  320. });
  321. }
  322. if (this.mode > 0)
  323. messageChain.push(mirai_1.Message.Plain(author + xmlEntities.decode(text)));
  324. });
  325. // invoke webshot
  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. // fetch extra entities
  347. // tslint:disable-next-line: curly
  348. if (1 - this.mode % 2)
  349. promise = promise.then(() => {
  350. if (originTwi.extended_entities) {
  351. return utils_1.chainPromises(originTwi.extended_entities.media.map(media => {
  352. let url;
  353. if (media.type === 'photo') {
  354. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  355. }
  356. else {
  357. url = media.video_info.variants
  358. .filter(variant => variant.bitrate !== undefined)
  359. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  360. .map(variant => variant.url)[0]; // largest video
  361. }
  362. const altMessage = mirai_1.Message.Plain(`\n[失败的${typeInZH[media.type].type}:${url}]`);
  363. return this.fetchMedia(url)
  364. .then(base64url => {
  365. let mediaPromise = Promise.resolve([]);
  366. if (base64url.match(/^data:video.+;/)) {
  367. // demux mkv into gif and pcm16le
  368. const input = () => Buffer.from(base64url.split(',')[1], 'base64');
  369. const imgReturns = child_process_1.spawnSync('ffmpeg', [
  370. '-i', '-',
  371. '-an',
  372. '-f', 'gif',
  373. '-c', 'copy',
  374. '-',
  375. ], { stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input() });
  376. const voiceReturns = child_process_1.spawnSync('ffmpeg', [
  377. '-i', '-',
  378. '-vn',
  379. '-f', 's16le',
  380. '-ac', '1',
  381. '-ar', '24000',
  382. '-',
  383. ], { stdio: 'pipe', maxBuffer: 16 * 1024 * 1024, input: input() });
  384. if (!imgReturns.stdout.byteLength)
  385. throw Error(imgReturns.stderr.toString());
  386. base64url = `data:image/gif;base64,${imgReturns.stdout.toString('base64')}`;
  387. if (voiceReturns.stdout.byteLength) {
  388. logger.info('video has an audio track, trying to convert it to voice...');
  389. temp.track();
  390. const inputFile = temp.openSync();
  391. fs_1.writeSync(inputFile.fd, voiceReturns.stdout);
  392. child_process_1.spawnSync('silk-encoder', [
  393. inputFile.path,
  394. inputFile.path + '.silk',
  395. '-tencent',
  396. ]);
  397. temp.cleanup();
  398. if (fs_1.existsSync(inputFile.path + '.silk')) {
  399. if (fs_1.statSync(inputFile.path + '.silk').size !== 0) {
  400. const audioBase64Url = `data:audio/silk-v3;base64,${fs_1.readFileSync(inputFile.path + '.silk').toString('base64')}`;
  401. mediaPromise = mediaPromise.then(chain => uploader(mirai_1.Message.Voice('', audioBase64Url, `${url} as amr`), () => mirai_1.Message.Plain('\n[失败的语音]'))
  402. .then(msg => [msg, ...chain]));
  403. }
  404. fs_1.unlinkSync(inputFile.path + '.silk');
  405. }
  406. }
  407. }
  408. return mediaPromise.then(chain => uploader(mirai_1.Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage)
  409. .then(msg => [msg, ...chain]));
  410. })
  411. .catch(error => {
  412. logger.error(`unable to fetch media, error: ${error}`);
  413. logger.warn('unable to fetch media, sending plain text instead...');
  414. return [altMessage];
  415. })
  416. .then(msgs => {
  417. messageChain.push(...msgs);
  418. });
  419. }));
  420. }
  421. });
  422. // append URLs, if any
  423. if (this.mode === 0) {
  424. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  425. promise = promise.then(() => {
  426. const urls = originTwi.entities.urls
  427. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  428. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  429. if (urls.length) {
  430. messageChain.push(mirai_1.Message.Plain(urls.join('')));
  431. }
  432. });
  433. }
  434. }
  435. // refer to quoted tweet, if any
  436. if (originTwi.is_quote_status) {
  437. promise = promise.then(() => {
  438. messageChain.push(mirai_1.Message.Plain(`\n回复此命令查看引用的推文:\n/twitterpic_view ${originTwi.quoted_status_id_str}`));
  439. });
  440. }
  441. promise.then(() => {
  442. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  443. logger.info(JSON.stringify(messageChain));
  444. callback(messageChain, xmlEntities.decode(text), author);
  445. });
  446. });
  447. return promise.catch(err => logger.error(`failed to shoot webshot, error: ${JSON.stringify(err)}`));
  448. }
  449. }
  450. exports.default = Webshot;