webshot.js 16 KB

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