webshot.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 xmlEntities = new html_entities_1.XmlEntities();
  23. const chainPromises = (promises) => promises.reduce((p1, p2) => p1.then(() => p2), Promise.resolve());
  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. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  148. // footer kicks in
  149. boundary = null;
  150. }
  151. else {
  152. boundary = y;
  153. }
  154. break;
  155. }
  156. }
  157. if (boundary !== null) {
  158. logger.info(`found boundary at ${boundary}, cropping image`);
  159. this.data = this.data.slice(0, idx(this.width, boundary));
  160. this.height = boundary;
  161. boundary = null;
  162. x = Math.floor(16 * zoomFactor);
  163. let flag = false;
  164. let cnt = 0;
  165. for (let y = this.height - 1; y >= 0; y--) {
  166. if ((this.data[idx(x, y)] === 255) === flag) {
  167. cnt++;
  168. flag = !flag;
  169. }
  170. else
  171. continue;
  172. // line above the "comment", "retweet", "like", "share" button row
  173. if (cnt === 2) {
  174. boundary = y + 1;
  175. }
  176. // if there are a "retweet" count and "like" count row, this will be the line above it
  177. if (cnt === 4) {
  178. const b = y + 1;
  179. if (this.height - boundary - (boundary - b) <= 1) {
  180. boundary = b;
  181. // }
  182. // }
  183. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  184. // if (cnt === 6) {
  185. // const c = y + 1;
  186. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  187. // boundary = c;
  188. break;
  189. }
  190. }
  191. }
  192. if (boundary != null) {
  193. logger.info(`found boundary at ${boundary}, trimming image`);
  194. this.data = this.data.slice(0, idx(this.width, boundary));
  195. this.height = boundary;
  196. }
  197. sharpToBase64(jpeg(this.pack())).then(base64 => {
  198. logger.info(`finished webshot for ${url}`);
  199. resolve({ base64, boundary });
  200. });
  201. }
  202. else if (height >= 8 * 1920) {
  203. logger.warn('too large, consider as a bug, returning');
  204. sharpToBase64(jpeg(this.pack())).then(base64 => {
  205. resolve({ base64, boundary: 0 });
  206. });
  207. }
  208. else {
  209. logger.info('unable to find boundary, try shooting a larger image');
  210. resolve({ base64: '', boundary });
  211. }
  212. }).parse(screenshot);
  213. })
  214. .catch(err => {
  215. if (err.name !== 'TimeoutError')
  216. throw err;
  217. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  218. resolve({ base64: '', boundary: 0 });
  219. })
  220. .finally(() => page.close());
  221. })
  222. .catch(reject);
  223. });
  224. return promise.then(data => {
  225. if (data.boundary === null)
  226. return this.renderWebshot(url, height + 1920, webshotDelay);
  227. else
  228. return data.base64;
  229. }).catch(error => new Promise(resolve => this.reconnect(error, resolve))
  230. .then(() => this.renderWebshot(url, height, webshotDelay)));
  231. };
  232. this.fetchMedia = (url) => {
  233. const gif = (data) => {
  234. const matchDims = url.match(/\/(\d+)x(\d+)\//);
  235. if (matchDims) {
  236. const [width, height] = matchDims.slice(1).map(Number);
  237. const factor = width + height > 1600 ? 0.375 : 0.5;
  238. return gifski_1.default(data, width * factor);
  239. }
  240. return gifski_1.default(data);
  241. };
  242. return new Promise((resolve, reject) => {
  243. logger.info(`fetching ${url}`);
  244. axios_1.default({
  245. method: 'get',
  246. url,
  247. responseType: 'arraybuffer',
  248. }).then(res => {
  249. if (res.status === 200) {
  250. logger.info(`successfully fetched ${url}`);
  251. resolve(res.data);
  252. }
  253. else {
  254. logger.error(`failed to fetch ${url}: ${res.status}`);
  255. reject();
  256. }
  257. }).catch(err => {
  258. logger.error(`failed to fetch ${url}: ${err.message}`);
  259. reject();
  260. });
  261. }).then(data => {
  262. var _a;
  263. return ((ext) => __awaiter(this, void 0, void 0, function* () {
  264. switch (ext) {
  265. case 'jpg':
  266. return { mimetype: 'image/jpeg', data };
  267. case 'png':
  268. return { mimetype: 'image/png', data };
  269. case 'mp4':
  270. try {
  271. return { mimetype: 'image/gif', data: yield gif(data) };
  272. }
  273. catch (err) {
  274. logger.error(err);
  275. throw Error(err);
  276. }
  277. }
  278. }))(((_a = url.match(/\?format=([a-z]+)&/)) !== null && _a !== void 0 ? _a : url.match(/.*\/.*\.([^?]+)/))[1])
  279. .catch(() => {
  280. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  281. throw Error();
  282. });
  283. }).then(typedData => `data:${typedData.mimetype};base64,${Buffer.from(typedData.data).toString('base64')}`);
  284. };
  285. // tslint:disable-next-line: no-conditional-assignment
  286. if (this.mode = mode) {
  287. onready();
  288. }
  289. else {
  290. this.connect(onready);
  291. }
  292. }
  293. webshot(tweets, uploader, callback, webshotDelay) {
  294. let promise = new Promise(resolve => {
  295. resolve();
  296. });
  297. tweets.forEach(twi => {
  298. promise = promise.then(() => {
  299. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  300. });
  301. const originTwi = twi.retweeted_status || twi;
  302. const messageChain = [];
  303. // text processing
  304. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  305. if (twi.retweeted_status)
  306. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  307. let text = originTwi.full_text;
  308. promise = promise.then(() => {
  309. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  310. originTwi.entities.urls.forEach(url => {
  311. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  312. });
  313. }
  314. if (originTwi.extended_entities) {
  315. originTwi.extended_entities.media.forEach(media => {
  316. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  317. });
  318. }
  319. if (this.mode > 0)
  320. messageChain.push(mirai_1.Message.Plain(author + xmlEntities.decode(text)));
  321. });
  322. // invoke webshot
  323. if (this.mode === 0) {
  324. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  325. this.extendEntity = (cardImg) => {
  326. var _a, _b;
  327. originTwi.extended_entities = Object.assign(Object.assign({}, originTwi.extended_entities), { media: [
  328. ...(_b = (_a = originTwi.extended_entities) === null || _a === void 0 ? void 0 : _a.media) !== null && _b !== void 0 ? _b : [],
  329. cardImg,
  330. ] });
  331. };
  332. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  333. .then(base64url => {
  334. if (base64url)
  335. return uploader(mirai_1.Message.Image('', base64url, url), () => mirai_1.Message.Plain(author + text));
  336. return mirai_1.Message.Plain(author + text);
  337. })
  338. .then(msg => {
  339. if (msg)
  340. messageChain.push(msg);
  341. });
  342. }
  343. // fetch extra entities
  344. // tslint:disable-next-line: curly
  345. if (1 - this.mode % 2)
  346. promise = promise.then(() => {
  347. if (originTwi.extended_entities) {
  348. return chainPromises(originTwi.extended_entities.media.map(media => {
  349. let url;
  350. if (media.type === 'photo') {
  351. url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
  352. }
  353. else {
  354. url = media.video_info.variants
  355. .filter(variant => variant.bitrate !== undefined)
  356. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  357. .map(variant => variant.url)[0]; // largest video
  358. }
  359. const altMessage = mirai_1.Message.Plain(`\n[失败的${typeInZH[media.type].type}:${url}]`);
  360. return this.fetchMedia(url)
  361. .then(base64url => uploader(mirai_1.Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage))
  362. .catch(error => {
  363. logger.warn('unable to fetch media, sending plain text instead...');
  364. return altMessage;
  365. })
  366. .then(msg => {
  367. messageChain.push(msg);
  368. });
  369. }));
  370. }
  371. });
  372. // append URLs, if any
  373. if (this.mode === 0) {
  374. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  375. promise = promise.then(() => {
  376. const urls = originTwi.entities.urls
  377. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  378. .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
  379. if (urls.length) {
  380. messageChain.push(mirai_1.Message.Plain(urls.join('')));
  381. }
  382. });
  383. }
  384. }
  385. // refer to quoted tweet, if any
  386. if (originTwi.is_quote_status) {
  387. promise = promise.then(() => {
  388. messageChain.push(mirai_1.Message.Plain(`\n回复此命令查看引用的推文:\n/twitter_view ${originTwi.quoted_status_permalink.expanded}`));
  389. });
  390. }
  391. promise.then(() => {
  392. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  393. logger.info(JSON.stringify(messageChain));
  394. callback(messageChain, xmlEntities.decode(text), author);
  395. });
  396. });
  397. return promise;
  398. }
  399. }
  400. exports.default = Webshot;