webshot.js 21 KB

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