webshot.js 18 KB

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