webshot.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 gifski_1 = require("./gifski");
  19. const loggers_1 = require("./loggers");
  20. const mirai_1 = require("./mirai");
  21. const xmlEntities = new html_entities_1.XmlEntities();
  22. const ZHType = (type) => new class extends String {
  23. constructor() {
  24. super(...arguments);
  25. this.type = super.toString();
  26. this.toString = () => `[${super.toString()}]`;
  27. }
  28. }(type);
  29. const typeInZH = {
  30. photo: ZHType('图片'),
  31. video: ZHType('视频'),
  32. animated_gif: ZHType('GIF'),
  33. };
  34. const logger = loggers_1.getLogger('webshot');
  35. class Webshot extends CallableInstance {
  36. constructor(mode, onready) {
  37. super('webshot');
  38. // use local Chromium
  39. this.connect = (onready) => puppeteer.connect({ browserURL: 'http://127.0.0.1:9222' })
  40. .then(browser => this.browser = browser)
  41. .then(() => {
  42. logger.info('launched puppeteer browser');
  43. if (onready)
  44. return onready();
  45. })
  46. .catch(error => this.reconnect(error, onready));
  47. this.reconnect = (error, onready) => {
  48. logger.error(`connection error, reason: ${error}`);
  49. logger.warn('trying to reconnect in 2.5s...');
  50. return new Promise(resolve => setTimeout(resolve, 2500))
  51. .then(() => this.connect(onready));
  52. };
  53. this.renderWebshot = (url, height, webshotDelay) => {
  54. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  55. const sharpToBase64 = (pic) => new Promise(resolve => {
  56. pic.toBuffer().then(buffer => resolve(`data:image/jpeg;base64,${buffer.toString('base64')}`));
  57. });
  58. const promise = new Promise((resolve, reject) => {
  59. const width = 720;
  60. const zoomFactor = 2;
  61. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  62. this.browser.newPage()
  63. .then(page => {
  64. const startTime = new Date().getTime();
  65. const getTimerTime = () => new Date().getTime() - startTime;
  66. const getTimeout = () => Math.max(1000, webshotDelay - getTimerTime());
  67. let idle = false;
  68. const awaitIdle = page.waitForNavigation({ waitUntil: 'networkidle0', timeout: getTimeout() });
  69. const waitUntilIdle = () => {
  70. if (idle)
  71. return Promise.resolve();
  72. return awaitIdle.then(() => { idle = true; });
  73. };
  74. const waitForSelectorUntilIdle = (selector) => Promise.race([
  75. waitUntilIdle().then(() => Promise.reject(new puppeteer.errors.TimeoutError())),
  76. page.waitForSelector(selector, { timeout: getTimeout() }),
  77. ]);
  78. const article = page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  79. .then(() => page.setViewport({
  80. width: width / zoomFactor,
  81. height: height / zoomFactor,
  82. isMobile: true,
  83. deviceScaleFactor: zoomFactor,
  84. }))
  85. .then(() => page.setBypassCSP(true))
  86. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  87. // hide header, "more options" button, like and retweet count
  88. .then(() => page.addStyleTag({
  89. 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;}',
  90. }))
  91. .then(() => waitForSelectorUntilIdle('article'))
  92. .catch((err) => {
  93. if (err.name !== 'TimeoutError')
  94. throw err;
  95. logger.warn(`navigation timed out at ${getTimerTime()} seconds`);
  96. return Promise.resolve(null);
  97. });
  98. const captureLoadedPage = () => page.addScriptTag({
  99. content: 'document.documentElement.scrollTop=0;',
  100. })
  101. .then(() => page.screenshot())
  102. .then(screenshot => {
  103. new pngjs_1.PNG({
  104. filterType: 4,
  105. deflateLevel: 0,
  106. }).on('parsed', function () {
  107. // remove comment area
  108. // tslint:disable-next-line: no-shadowed-variable
  109. const idx = (x, y) => (this.width * y + x) << 2;
  110. let boundary = null;
  111. let x = zoomFactor * 2;
  112. for (let y = 0; y < this.height; y++) {
  113. if (this.data[idx(x, y)] !== 255) {
  114. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  115. // footer kicks in
  116. boundary = null;
  117. }
  118. else {
  119. boundary = y;
  120. }
  121. break;
  122. }
  123. }
  124. if (boundary !== null) {
  125. logger.info(`found boundary at ${boundary}, cropping image`);
  126. this.data = this.data.slice(0, idx(this.width, boundary));
  127. this.height = boundary;
  128. boundary = null;
  129. x = Math.floor(16 * zoomFactor);
  130. let flag = false;
  131. let cnt = 0;
  132. for (let y = this.height - 1; y >= 0; y--) {
  133. if ((this.data[idx(x, y)] === 255) === flag) {
  134. cnt++;
  135. flag = !flag;
  136. }
  137. else
  138. continue;
  139. // line above the "comment", "retweet", "like", "share" button row
  140. if (cnt === 2) {
  141. boundary = y + 1;
  142. }
  143. // if there are a "retweet" count and "like" count row, this will be the line above it
  144. if (cnt === 4) {
  145. const b = y + 1;
  146. if (this.height - boundary - (boundary - b) <= 1) {
  147. boundary = b;
  148. // }
  149. // }
  150. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  151. // if (cnt === 6) {
  152. // const c = y + 1;
  153. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  154. // boundary = c;
  155. break;
  156. }
  157. }
  158. }
  159. if (boundary != null) {
  160. logger.info(`found boundary at ${boundary}, trimming image`);
  161. this.data = this.data.slice(0, idx(this.width, boundary));
  162. this.height = boundary;
  163. }
  164. sharpToBase64(jpeg(this.pack())).then(base64 => {
  165. logger.info(`finished webshot for ${url}`);
  166. resolve({ base64, boundary });
  167. });
  168. }
  169. else if (height >= 8 * 1920) {
  170. logger.warn('too large, consider as a bug, returning');
  171. sharpToBase64(jpeg(this.pack())).then(base64 => {
  172. resolve({ base64, boundary: 0 });
  173. });
  174. }
  175. else {
  176. logger.info('unable to find boundary, try shooting a larger image');
  177. resolve({ base64: '', boundary });
  178. }
  179. }).parse(screenshot);
  180. })
  181. .then(() => page.close());
  182. article.then(elementHandle => {
  183. if (elementHandle === null) {
  184. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  185. page.close();
  186. resolve({ base64: '', boundary: 0 });
  187. }
  188. else {
  189. const coverSelector = page.$x('//article//div[@role="button"]/div/img/..');
  190. const badgeSelector = page.$x('//article//div[@role="button"]/div/img/../../..//span/..');
  191. const getFirst = (arraySelector) => arraySelector.then(candidatesHandle => {
  192. if (candidatesHandle.length) {
  193. return candidatesHandle[0];
  194. }
  195. });
  196. const prepend = (e1, e2) => e1.parentElement.prepend(e2);
  197. waitForSelectorUntilIdle('video')
  198. .then(videoHandle => {
  199. logger.info('found video, replacing it with cover...');
  200. return getFirst(badgeSelector).then(badgeHandle => page.evaluate(prepend, videoHandle, badgeHandle))
  201. .then(() => getFirst(coverSelector).then(coverHandle => page.evaluate(prepend, videoHandle, coverHandle)))
  202. .then(() => page.evaluate((e) => e.remove(), videoHandle));
  203. })
  204. .catch((err) => {
  205. if (err.name !== 'TimeoutError')
  206. throw err;
  207. })
  208. .then(captureLoadedPage);
  209. }
  210. });
  211. })
  212. .catch(reject);
  213. });
  214. return promise.then(data => {
  215. if (data.boundary === null)
  216. return this.renderWebshot(url, height + 1920, webshotDelay);
  217. else
  218. return data.base64;
  219. }).catch(error => new Promise(resolve => this.reconnect(error, resolve))
  220. .then(() => this.renderWebshot(url, height, webshotDelay)));
  221. };
  222. this.fetchMedia = (url) => {
  223. const gif = (data) => {
  224. const matchDims = url.match(/\/(\d+)x(\d+)\//);
  225. if (matchDims) {
  226. const [width, height] = matchDims.slice(1).map(Number);
  227. const factor = width + height > 1600 ? 0.375 : 0.5;
  228. return gifski_1.default(data, width * factor);
  229. }
  230. return gifski_1.default(data);
  231. };
  232. return new Promise((resolve, reject) => {
  233. logger.info(`fetching ${url}`);
  234. axios_1.default({
  235. method: 'get',
  236. url,
  237. responseType: 'arraybuffer',
  238. }).then(res => {
  239. if (res.status === 200) {
  240. logger.info(`successfully fetched ${url}`);
  241. resolve(res.data);
  242. }
  243. else {
  244. logger.error(`failed to fetch ${url}: ${res.status}`);
  245. reject();
  246. }
  247. }).catch(err => {
  248. logger.error(`failed to fetch ${url}: ${err.message}`);
  249. reject();
  250. });
  251. }).then(data => ((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. }))(url.split('/').slice(-1)[0].match(/\.([^:?&]+)/)[1])).then(typedData => `data:${typedData.mimetype};base64,${Buffer.from(typedData.data).toString('base64')}`);
  267. };
  268. // tslint:disable-next-line: no-conditional-assignment
  269. if (this.mode = mode) {
  270. onready();
  271. }
  272. else {
  273. this.connect(onready);
  274. }
  275. }
  276. webshot(tweets, uploader, callback, webshotDelay) {
  277. let promise = new Promise(resolve => {
  278. resolve();
  279. });
  280. tweets.forEach(twi => {
  281. promise = promise.then(() => {
  282. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  283. });
  284. const originTwi = twi.retweeted_status || twi;
  285. const messageChain = [];
  286. // text processing
  287. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  288. if (twi.retweeted_status)
  289. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  290. let text = originTwi.full_text;
  291. promise = promise.then(() => {
  292. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  293. originTwi.entities.urls.forEach(url => {
  294. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  295. });
  296. }
  297. if (originTwi.extended_entities) {
  298. originTwi.extended_entities.media.forEach(media => {
  299. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  300. });
  301. }
  302. if (this.mode > 0)
  303. messageChain.push(mirai_1.Message.Plain(author + xmlEntities.decode(text)));
  304. });
  305. // invoke webshot
  306. if (this.mode === 0) {
  307. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  308. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  309. .then(base64url => {
  310. if (base64url)
  311. return uploader(mirai_1.Message.Image('', base64url, url), () => mirai_1.Message.Plain(author + text));
  312. return mirai_1.Message.Plain(author + text);
  313. })
  314. .then(msg => {
  315. if (msg)
  316. messageChain.push(msg);
  317. });
  318. }
  319. // fetch extra entities
  320. if (1 - this.mode % 2) {
  321. if (originTwi.extended_entities) {
  322. originTwi.extended_entities.media.forEach(media => {
  323. let url;
  324. if (media.type === 'photo') {
  325. url = media.media_url_https + ':orig';
  326. }
  327. else {
  328. url = media.video_info.variants
  329. .filter(variant => variant.bitrate !== undefined)
  330. .sort((var1, var2) => var2.bitrate - var1.bitrate)
  331. .map(variant => variant.url)[0]; // largest video
  332. }
  333. const altMessage = mirai_1.Message.Plain(`[失败的${typeInZH[media.type].type}${url}]`);
  334. promise = promise.then(() => this.fetchMedia(url))
  335. .then(base64url => uploader(mirai_1.Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage))
  336. .catch(error => {
  337. logger.warn('unable to fetch media, sending plain text instead...');
  338. return altMessage;
  339. })
  340. .then(msg => {
  341. messageChain.push(msg);
  342. });
  343. });
  344. }
  345. }
  346. // append URLs, if any
  347. if (this.mode === 0) {
  348. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  349. promise = promise.then(() => {
  350. const urls = originTwi.entities.urls
  351. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  352. .map(urlObj => urlObj.expanded_url);
  353. if (urls.length) {
  354. messageChain.push(mirai_1.Message.Plain(urls.join('\n')));
  355. }
  356. });
  357. }
  358. }
  359. promise.then(() => {
  360. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  361. logger.info(JSON.stringify(messageChain));
  362. callback(messageChain, xmlEntities.decode(text), author);
  363. });
  364. });
  365. return promise;
  366. }
  367. }
  368. exports.default = Webshot;