webshot.js 12 KB

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