webshot.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const axios_1 = require("axios");
  4. const CallableInstance = require("callable-instance");
  5. const html_entities_1 = require("html-entities");
  6. const pngjs_1 = require("pngjs");
  7. const puppeteer = require("puppeteer");
  8. const sharp = require("sharp");
  9. const gifski_1 = require("./gifski");
  10. const loggers_1 = require("./loggers");
  11. const mirai_1 = require("./mirai");
  12. const xmlEntities = new html_entities_1.XmlEntities();
  13. const ZHType = (type) => new class extends String {
  14. constructor() {
  15. super(...arguments);
  16. this.type = super.toString();
  17. this.toString = () => `[${super.toString()}]`;
  18. }
  19. }(type);
  20. const typeInZH = {
  21. photo: ZHType('图片'),
  22. video: ZHType('视频'),
  23. animated_gif: ZHType('GIF'),
  24. };
  25. const logger = loggers_1.getLogger('webshot');
  26. class Webshot extends CallableInstance {
  27. constructor(mode, onready) {
  28. super('webshot');
  29. // use local Chromium
  30. this.connect = (onready) => puppeteer.connect({ browserURL: 'http://127.0.0.1:9222' })
  31. .then(browser => this.browser = browser)
  32. .then(() => {
  33. logger.info('launched puppeteer browser');
  34. if (onready)
  35. return onready();
  36. })
  37. .catch(error => this.reconnect(error, onready));
  38. this.reconnect = (error, onready) => {
  39. logger.error(`connection error, reason: ${error}`);
  40. logger.warn('trying to reconnect in 2.5s...');
  41. return new Promise(resolve => setTimeout(resolve, 2500))
  42. .then(() => this.connect(onready));
  43. };
  44. this.renderWebshot = (url, height, webshotDelay) => {
  45. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  46. const sharpToBase64 = (pic) => new Promise(resolve => {
  47. pic.toBuffer().then(buffer => resolve(`data:image/jpg;base64,${buffer.toString('base64')}`));
  48. });
  49. const promise = new Promise((resolve, reject) => {
  50. const width = 720;
  51. const zoomFactor = 2;
  52. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  53. this.browser.newPage()
  54. .then(page => {
  55. page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36')
  56. .then(() => page.setViewport({
  57. width: width / zoomFactor,
  58. height: height / zoomFactor,
  59. isMobile: true,
  60. deviceScaleFactor: zoomFactor,
  61. }))
  62. .then(() => page.setBypassCSP(true))
  63. .then(() => page.goto(url, { waitUntil: 'load', timeout: 150000 }))
  64. // hide header, "more options" button, like and retweet count
  65. .then(() => page.addStyleTag({
  66. 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;}',
  67. }))
  68. .then(() => page.waitFor(webshotDelay))
  69. .then(() => page.addScriptTag({
  70. content: 'document.documentElement.scrollTop=0;',
  71. }))
  72. .then(() => page.screenshot())
  73. .then(screenshot => {
  74. new pngjs_1.PNG({
  75. filterType: 4,
  76. deflateLevel: 0,
  77. }).on('parsed', function () {
  78. // remove comment area
  79. // tslint:disable-next-line: no-shadowed-variable
  80. const idx = (x, y) => (this.width * y + x) << 2;
  81. let boundary = null;
  82. let x = zoomFactor * 2;
  83. for (let y = 0; y < this.height; y++) {
  84. if (this.data[idx(x, y)] !== 255) {
  85. if (this.data[idx(x, y + 18 * zoomFactor)] !== 255) {
  86. // footer kicks in
  87. boundary = null;
  88. }
  89. else {
  90. boundary = y;
  91. }
  92. break;
  93. }
  94. }
  95. if (boundary !== null) {
  96. logger.info(`found boundary at ${boundary}, cropping image`);
  97. this.data = this.data.slice(0, idx(this.width, boundary));
  98. this.height = boundary;
  99. boundary = null;
  100. x = Math.floor(16 * zoomFactor);
  101. let flag = false;
  102. let cnt = 0;
  103. for (let y = this.height - 1; y >= 0; y--) {
  104. if ((this.data[idx(x, y)] === 255) === flag) {
  105. cnt++;
  106. flag = !flag;
  107. }
  108. else
  109. continue;
  110. // line above the "comment", "retweet", "like", "share" button row
  111. if (cnt === 2) {
  112. boundary = y + 1;
  113. }
  114. // if there are a "retweet" count and "like" count row, this will be the line above it
  115. if (cnt === 4) {
  116. const b = y + 1;
  117. if (this.height - boundary - (boundary - b) <= 1) {
  118. boundary = b;
  119. // }
  120. // }
  121. // // if "retweet" count and "like" count are two rows, this will be the line above the first
  122. // if (cnt === 6) {
  123. // const c = y + 1;
  124. // if (this.height - boundary - 2 * (boundary - c) <= 2) {
  125. // boundary = c;
  126. break;
  127. }
  128. }
  129. }
  130. if (boundary != null) {
  131. logger.info(`found boundary at ${boundary}, trimming image`);
  132. this.data = this.data.slice(0, idx(this.width, boundary));
  133. this.height = boundary;
  134. }
  135. sharpToBase64(jpeg(this.pack())).then(base64 => {
  136. logger.info(`finished webshot for ${url}`);
  137. resolve({ base64, boundary });
  138. });
  139. }
  140. else if (height >= 8 * 1920) {
  141. logger.warn('too large, consider as a bug, returning');
  142. sharpToBase64(jpeg(this.pack())).then(base64 => {
  143. resolve({ base64, boundary: 0 });
  144. });
  145. }
  146. else {
  147. logger.info('unable to find boundary, try shooting a larger image');
  148. resolve({ base64: '', boundary });
  149. }
  150. }).parse(screenshot);
  151. })
  152. .then(() => page.close());
  153. })
  154. .catch(reject);
  155. });
  156. return promise.then(data => {
  157. if (data.boundary === null)
  158. return this.renderWebshot(url, height + 1920, webshotDelay);
  159. else
  160. return data.base64;
  161. }).catch(error => new Promise(resolve => this.reconnect(error, resolve))
  162. .then(() => this.renderWebshot(url, height, webshotDelay)));
  163. };
  164. this.fetchMedia = (url) => new Promise(resolve => {
  165. logger.info(`fetching ${url}`);
  166. axios_1.default({
  167. method: 'get',
  168. url,
  169. responseType: 'arraybuffer',
  170. }).then(res => {
  171. if (res.status === 200) {
  172. logger.info(`successfully fetched ${url}`);
  173. resolve(res.data);
  174. }
  175. else {
  176. logger.error(`failed to fetch ${url}: ${res.status}`);
  177. resolve();
  178. }
  179. }).catch(err => {
  180. logger.error(`failed to fetch ${url}: ${err.message}`);
  181. resolve();
  182. });
  183. }).then(data => {
  184. const mimetype = (ext => {
  185. switch (ext) {
  186. case 'jpg':
  187. return 'image/jpeg';
  188. case 'png':
  189. return 'image/png';
  190. case 'mp4':
  191. data = gifski_1.default(data);
  192. return 'image/gif';
  193. }
  194. })(url.split('/').slice(-1)[0].match(/\.([^:?&]+)/)[1]);
  195. return `data:${mimetype};base64,${Buffer.from(data).toString('base64')}`;
  196. });
  197. // tslint:disable-next-line: no-conditional-assignment
  198. if (this.mode = mode) {
  199. onready();
  200. }
  201. else {
  202. this.connect(onready);
  203. }
  204. }
  205. webshot(tweets, uploader, callback, webshotDelay) {
  206. let promise = new Promise(resolve => {
  207. resolve();
  208. });
  209. tweets.forEach(twi => {
  210. promise = promise.then(() => {
  211. logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
  212. });
  213. const originTwi = twi.retweeted_status || twi;
  214. const messageChain = [];
  215. // text processing
  216. let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
  217. if (twi.retweeted_status)
  218. author += `RT @${twi.retweeted_status.user.screen_name}: `;
  219. let text = originTwi.full_text;
  220. promise = promise.then(() => {
  221. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  222. originTwi.entities.urls.forEach(url => {
  223. text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
  224. });
  225. }
  226. if (originTwi.extended_entities) {
  227. originTwi.extended_entities.media.forEach(media => {
  228. text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
  229. });
  230. }
  231. if (this.mode > 0)
  232. messageChain.push(mirai_1.Message.Plain(author + xmlEntities.decode(text)));
  233. });
  234. // invoke webshot
  235. if (this.mode === 0) {
  236. const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
  237. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  238. .then(base64url => {
  239. if (base64url) {
  240. return uploader(mirai_1.Message.Image('', base64url, url), () => mirai_1.Message.Plain(author + text));
  241. }
  242. })
  243. .then(msg => {
  244. if (msg)
  245. messageChain.push(msg);
  246. });
  247. }
  248. // fetch extra entities
  249. if (1 - this.mode % 2) {
  250. if (originTwi.extended_entities) {
  251. originTwi.extended_entities.media.forEach(media => {
  252. let url;
  253. if (media.type === 'photo') {
  254. url = media.media_url_https + ':orig';
  255. }
  256. else {
  257. url = media.video_info.variants
  258. .filter(variant => variant.bitrate)
  259. .sort((var1, var2) => var1.bitrate - var2.bitrate)
  260. .map(variant => variant.url)[0]; // smallest video
  261. }
  262. const altMessage = mirai_1.Message.Plain(`[失败的${typeInZH[media.type].type}:${url}]`);
  263. promise = promise.then(() => this.fetchMedia(url))
  264. .then(base64url => uploader(mirai_1.Message.Image('', base64url, media.type === 'photo' ? url : `${url} as gif`), () => altMessage))
  265. .catch(error => {
  266. logger.warn('unable to fetch media, sending plain text instead...');
  267. return altMessage;
  268. })
  269. .then(msg => {
  270. messageChain.push(msg);
  271. });
  272. });
  273. }
  274. }
  275. // append URLs, if any
  276. if (this.mode === 0) {
  277. if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
  278. promise = promise.then(() => {
  279. const urls = originTwi.entities.urls
  280. .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
  281. .map(urlObj => urlObj.expanded_url);
  282. if (urls.length) {
  283. messageChain.push(mirai_1.Message.Plain(urls.join('\n')));
  284. }
  285. });
  286. }
  287. }
  288. promise.then(() => {
  289. logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
  290. logger.info(JSON.stringify(messageChain));
  291. callback(messageChain, xmlEntities.decode(text), author);
  292. });
  293. });
  294. return promise;
  295. }
  296. }
  297. exports.default = Webshot;