webshot.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const fs_1 = require("fs");
  4. const util_1 = require("util");
  5. const axios_1 = require("axios");
  6. const CallableInstance = require("callable-instance");
  7. const html_entities_1 = require("html-entities");
  8. const pngjs_1 = require("pngjs");
  9. const puppeteer = require("playwright");
  10. const sharp = require("sharp");
  11. const temp = require("temp");
  12. const loggers_1 = require("./loggers");
  13. const koishi_1 = require("./koishi");
  14. const utils_1 = require("./utils");
  15. const twitter_1 = require("./twitter");
  16. const xmlEntities = new html_entities_1.XmlEntities();
  17. const ZHType = (type) => new class extends String {
  18. constructor() {
  19. super(...arguments);
  20. this.type = super.toString();
  21. this.toString = () => `[${super.toString()}]`;
  22. }
  23. }(type);
  24. const typeInZH = {
  25. photo: ZHType('图片'),
  26. video: ZHType('视频'),
  27. };
  28. const logger = loggers_1.getLogger('webshot');
  29. class Webshot extends CallableInstance {
  30. constructor(wsUrl, mode, getCookies, onready) {
  31. super('webshot');
  32. this.connect = (onready) => axios_1.default.get(this.wsUrl)
  33. .then(res => {
  34. logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
  35. const browserType = Object.keys(res.data)[0];
  36. return puppeteer[browserType]
  37. .connect({ wsEndpoint: res.data[browserType] });
  38. })
  39. .then(browser => this.browser = browser)
  40. .then(() => {
  41. logger.info('launched puppeteer browser');
  42. if (onready)
  43. return onready();
  44. })
  45. .catch(error => this.reconnect(error, onready));
  46. this.reconnect = (error, onready) => {
  47. logger.error(`connection error, reason: ${error}`);
  48. logger.warn('trying to reconnect in 2.5s...');
  49. return util_1.promisify(setTimeout)(2500)
  50. .then(() => this.connect(onready));
  51. };
  52. this.renderWebshot = (url, height, webshotDelay) => {
  53. temp.track();
  54. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  55. const sharpToFile = (pic) => new Promise(resolve => {
  56. const webshotTempFilePath = temp.path({ suffix: '.jpg' });
  57. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  58. });
  59. const promise = new Promise((resolve, reject) => {
  60. const width = 720;
  61. const zoomFactor = 2;
  62. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  63. this.browser.newPage({
  64. bypassCSP: true,
  65. deviceScaleFactor: zoomFactor,
  66. locale: 'ja-JP',
  67. timezoneId: 'Asia/Tokyo',
  68. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  69. })
  70. .then(page => {
  71. const startTime = new Date().getTime();
  72. const getTimerTime = () => new Date().getTime() - startTime;
  73. const getTimeout = () => Math.max(500, webshotDelay - getTimerTime());
  74. page.setViewportSize({
  75. width: width / zoomFactor,
  76. height: height / zoomFactor,
  77. }).then(() => page.context().addCookies(this.getCookies()))
  78. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  79. .then(() => ((next) => Promise.race([
  80. page.click('button:has-text("すべて許可")').then(() => twitter_1.browserLogin(page))
  81. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  82. .then(() => next),
  83. page.click('button:has-text("すべて許可")').then(() => next),
  84. next,
  85. ]))(page.waitForSelector('article', { timeout: getTimeout() })))
  86. .catch((err) => {
  87. if (err.name !== 'TimeoutError')
  88. throw err;
  89. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  90. return null;
  91. })
  92. .then(() => page.addStyleTag({ content: 'nav,footer,header+div,header+div+div>div>div+div,header div div div+div,' +
  93. 'article section,article section+div>ul>:not(div),article section+div~div,article button,canvas{display:none!important} ' +
  94. 'section+div{overflow:hidden} section+*>*{position:relative!important} article{border-bottom:1px solid!important}',
  95. }))
  96. .then(() => page.addStyleTag({
  97. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  98. }))
  99. .then(() => page.screenshot())
  100. .then(screenshot => {
  101. new pngjs_1.PNG({
  102. filterType: 4,
  103. deflateLevel: 0,
  104. }).on('parsed', function () {
  105. const idx = (x, y) => (this.width * y + x) << 2;
  106. let boundary = null;
  107. for (let y = this.height - 1; y > this.height - 1920; y -= zoomFactor) {
  108. if (this.data[idx(zoomFactor, y)] <= 38 &&
  109. this.data[idx(zoomFactor, y)] === this.data[idx(this.width - zoomFactor, y)] &&
  110. this.data[idx(zoomFactor, y + zoomFactor)] === this.data[idx(zoomFactor, y - 2 * zoomFactor)]) {
  111. boundary = y;
  112. break;
  113. }
  114. }
  115. if (boundary !== null) {
  116. logger.info(`found boundary at ${boundary}, cropping image`);
  117. this.data = this.data.slice(0, idx(this.width, boundary));
  118. this.height = boundary;
  119. sharpToFile(jpeg(this.pack())).then(path => {
  120. logger.info(`finished webshot for ${url}`);
  121. resolve({ path, boundary });
  122. });
  123. }
  124. else if (height >= 8 * 1920) {
  125. logger.warn('too large, consider as a bug, returning');
  126. sharpToFile(jpeg(this.pack())).then(path => {
  127. resolve({ path, boundary: 0 });
  128. });
  129. }
  130. else {
  131. logger.info('unable to find boundary, try shooting a larger image');
  132. resolve({ path: '', boundary });
  133. }
  134. }).parse(screenshot);
  135. })
  136. .catch(err => {
  137. if (err instanceof Error && err.name !== 'TimeoutError')
  138. throw err;
  139. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  140. resolve({ path: '', boundary: 0 });
  141. })
  142. .finally(() => { page.close(); });
  143. })
  144. .catch(reject);
  145. });
  146. return promise.then(data => {
  147. if (data.boundary === null)
  148. return this.renderWebshot(url, height + 1920, webshotDelay);
  149. else
  150. return data.path;
  151. }).catch(error => this.reconnect(error)
  152. .then(() => this.renderWebshot(url, height, webshotDelay)));
  153. };
  154. this.fetchMedia = (url) => new Promise((resolve, reject) => {
  155. logger.info(`fetching ${url}`);
  156. axios_1.default({
  157. method: 'get',
  158. url,
  159. responseType: 'arraybuffer',
  160. timeout: 150000,
  161. }).then(res => {
  162. if (res.status === 200) {
  163. logger.info(`successfully fetched ${url}`);
  164. resolve(res.data);
  165. }
  166. else {
  167. logger.error(`failed to fetch ${url}: ${res.status}`);
  168. reject();
  169. }
  170. }).catch(err => {
  171. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  172. reject();
  173. });
  174. }).then(data => (ext => {
  175. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  176. fs_1.writeFileSync(mediaTempFilePath, Buffer.from(data));
  177. const path = `file://${mediaTempFilePath}`;
  178. switch (ext) {
  179. case 'jpg':
  180. case 'png':
  181. return koishi_1.Message.Image(path);
  182. case 'mp4':
  183. return koishi_1.Message.Video(path);
  184. }
  185. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  186. throw Error();
  187. })(/\/.*\.(.+?)\?/.exec(url)[1]));
  188. if (this.mode = mode) {
  189. onready();
  190. }
  191. else {
  192. this.getCookies = getCookies;
  193. this.wsUrl = wsUrl;
  194. this.connect(onready);
  195. }
  196. }
  197. webshot(mediaItems, callback, webshotDelay) {
  198. let promise = new Promise(resolve => {
  199. resolve();
  200. });
  201. mediaItems.forEach(item => {
  202. promise = promise.then(() => {
  203. logger.info(`working on ${item.user.username}/${item.code}`);
  204. });
  205. let messageChain = '';
  206. const author = `${item.user.full_name} (@${item.user.username}):\n`;
  207. const text = item.caption.text;
  208. if (this.mode > 0)
  209. messageChain += (author + xmlEntities.decode(text));
  210. if (this.mode === 0) {
  211. const url = twitter_1.linkBuilder({ postUrlSegment: item.code });
  212. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
  213. .then(fileurl => {
  214. if (fileurl)
  215. return koishi_1.Message.Image(fileurl);
  216. return author + text;
  217. })
  218. .then(msg => {
  219. if (msg)
  220. messageChain += msg;
  221. });
  222. }
  223. const type = (mediaItem) => mediaItem.video_versions ? 'video' : 'photo';
  224. const fetchBestCandidate = (candidates, mediaType) => {
  225. const url = candidates
  226. .sort((var1, var2) => var2.width + ((var2 === null || var2 === void 0 ? void 0 : var2.type) || 0) - var1.width - ((var1 === null || var1 === void 0 ? void 0 : var1.type) || 0))
  227. .map(variant => variant.url)[0];
  228. const altMessage = `\n[失败的${typeInZH[mediaType].type}:${url}]`;
  229. return this.fetchMedia(url)
  230. .catch(error => {
  231. logger.warn('unable to fetch media, sending plain text instead...');
  232. return altMessage;
  233. })
  234. .then(msg => { messageChain += msg; });
  235. };
  236. if (1 - this.mode % 2)
  237. promise = promise.then(() => {
  238. if (item.carousel_media) {
  239. return utils_1.chainPromises(item.carousel_media.map(carouselItem => fetchBestCandidate(carouselItem.video_versions ||
  240. carouselItem.image_versions2.candidates, type(carouselItem))));
  241. }
  242. else if (item.video_versions) {
  243. return fetchBestCandidate(item.video_versions, type(item));
  244. }
  245. else if (item.image_versions2) {
  246. return fetchBestCandidate(item.image_versions2.candidates, type(item));
  247. }
  248. });
  249. promise.then(() => {
  250. logger.info(`done working on ${item.user.username}/${item.code}, message chain:`);
  251. logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
  252. callback(messageChain, xmlEntities.decode(text), author);
  253. });
  254. });
  255. return promise;
  256. }
  257. }
  258. exports.default = Webshot;