webshot.js 16 KB

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