webshot.js 19 KB

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