webshot.js 13 KB

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