webshot.js 17 KB

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