webshot.js 11 KB

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