webshot.js 14 KB

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