webshot.js 19 KB

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