webshot.js 11 KB

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