webshot.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 = (0, 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 (0, util_1.promisify)(setTimeout)(2500)
  50. .then(() => this.connect(onready));
  51. };
  52. this.performOnNewPage = (action, zoomFactor = 2, reconnectOnError = true) => this.browser.newPage({
  53. bypassCSP: true,
  54. deviceScaleFactor: zoomFactor,
  55. locale: 'ja-JP',
  56. timezoneId: 'Asia/Tokyo',
  57. userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  58. }).then(action)
  59. .catch(error => {
  60. if (reconnectOnError) {
  61. return this.reconnect(error)
  62. .then(() => this.performOnNewPage(action, zoomFactor, reconnectOnError));
  63. }
  64. throw error;
  65. });
  66. this.renderWebshot = (url, height, webshotDelay, ...morePostProcessings) => {
  67. temp.track();
  68. const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
  69. const sharpToFile = (pic) => new Promise(resolve => {
  70. const webshotTempFilePath = temp.path({ suffix: '.jpg' });
  71. pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
  72. });
  73. const promise = new Promise((resolve, reject) => {
  74. const width = 720;
  75. const zoomFactor = 2;
  76. logger.info(`shooting ${width}*${height} webshot for ${url}`);
  77. this.performOnNewPage(page => {
  78. let startTime;
  79. let gotoUrl = () => {
  80. startTime = new Date().getTime();
  81. return page.goto(url, { waitUntil: 'load', timeout: getTimeout() });
  82. };
  83. const getTimerTime = () => new Date().getTime() - startTime;
  84. const getTimeout = () => twitter_1.WebshotHelpers.isWaitingForLogin ? 0 : Math.max(500, webshotDelay - getTimerTime());
  85. page.setViewportSize({
  86. width: width / zoomFactor,
  87. height: height / zoomFactor,
  88. }).then(() => page.context().addCookies(this.getCookies()))
  89. .then(gotoUrl)
  90. .then(() => twitter_1.WebshotHelpers.handleCookieConsent(page))
  91. .then(() => ((next) => Promise.race([
  92. twitter_1.WebshotHelpers.handleLogin(page).then(gotoUrl).then(next),
  93. (0, util_1.promisify)(setTimeout)(2000).then(next),
  94. ]))(() => page.waitForSelector('article', { timeout: getTimeout() })))
  95. .catch((err) => {
  96. if (err.name !== 'TimeoutError')
  97. throw err;
  98. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  99. })
  100. .then(() => page.addStyleTag({ content: 'nav,footer,main>*>*+*,header div>[class$=" "]>[class]+div,main button,canvas,main section,main section+div>ul>:not(div),' +
  101. 'main section+div>ul>div [role="button"],section+div h2,article>*>:first-child+*>*>:first-child+*{display:none!important} ' +
  102. 'section+div{overflow:hidden} section+*>*{position:relative!important} main>div{margin-bottom:0!important}' +
  103. 'main section+div>ul{width:auto!important;padding:16px 0!important} main section+div>ul>div>li{padding:6px 2px 12px!important}',
  104. }))
  105. .then(() => page.addStyleTag({ content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
  106. '*{-webkit-font-smoothing:antialiased!important}',
  107. }))
  108. .then(() => page.evaluate(() => {
  109. let time = document.querySelector('div>div>time');
  110. if (time)
  111. time.parentElement.parentElement.style.display = 'none';
  112. const a = document.querySelector(`main section~div a[href="${new URL(location.href).pathname}"]`);
  113. if (a) {
  114. time = a.querySelector('time');
  115. time.innerHTML = time.title + ' ' + new Date(time.dateTime).toLocaleTimeString().slice(0, -3);
  116. a.parentElement.parentElement.style.margin = '-24px 2px 12px';
  117. const element = a.parentElement.parentElement.nextElementSibling;
  118. if (element)
  119. element.style.display = 'none';
  120. }
  121. }))
  122. .then(() => (0, utils_1.chainPromises)(morePostProcessings.map(func => () => func(page))))
  123. .then(() => (0, util_1.promisify)(setTimeout)(getTimeout()))
  124. .then(() => page.$('article').then(article => article.screenshot()))
  125. .then(screenshot => {
  126. new pngjs_1.PNG({
  127. filterType: 4,
  128. deflateLevel: 0,
  129. }).on('parsed', function () {
  130. sharpToFile(jpeg(this.pack())).then(path => {
  131. logger.info(`finished webshot for ${url}`);
  132. resolve({ path, boundary: this.height });
  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 post`);
  140. resolve({ path: '', boundary: 0 });
  141. })
  142. .finally(() => { page.close(); });
  143. }, zoomFactor, false)
  144. .catch(reject);
  145. });
  146. return promise.then(data => {
  147. if (data.boundary === null) {
  148. return this.renderWebshot(url, height + 1920, webshotDelay, ...morePostProcessings);
  149. }
  150. else
  151. return data.path;
  152. }).catch(error => this.reconnect(error)
  153. .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings)));
  154. };
  155. this.fetchMedia = (url) => new Promise((resolve, reject) => {
  156. logger.info(`fetching ${url}`);
  157. (0, axios_1.default)({
  158. method: 'get',
  159. url,
  160. responseType: 'arraybuffer',
  161. timeout: 150000,
  162. }).then(res => {
  163. if (res.status === 200) {
  164. logger.info(`successfully fetched ${url}`);
  165. resolve(res.data);
  166. }
  167. else {
  168. logger.error(`failed to fetch ${url}: ${res.status}`);
  169. reject();
  170. }
  171. }).catch(err => {
  172. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  173. reject();
  174. });
  175. }).then(data => (ext => {
  176. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  177. (0, fs_1.writeFileSync)(mediaTempFilePath, Buffer.from(data));
  178. const path = `file://${mediaTempFilePath}`;
  179. switch (ext) {
  180. case 'jpg':
  181. case 'png':
  182. return koishi_1.Message.Image(path);
  183. case 'mp4':
  184. return koishi_1.Message.Video(path);
  185. }
  186. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  187. throw Error();
  188. })(/\/.+\.(?:.*?(?<=[?&])stp=dst-(jpg)|(.+?)\?)/.exec(url).filter(g => g)[1]));
  189. if (this.mode = mode) {
  190. if (onready)
  191. onready();
  192. }
  193. else {
  194. this.getCookies = getCookies;
  195. this.wsUrl = wsUrl;
  196. this.connect(() => onready && onready(this.performOnNewPage));
  197. }
  198. }
  199. webshot(lazyMediaItems, callback, webshotDelay) {
  200. let grandPromise = Promise.resolve();
  201. lazyMediaItems.forEach(lazyItem => grandPromise = grandPromise.then(lazyItem.item).then(item => {
  202. var _a;
  203. let promise = Promise.resolve();
  204. promise = promise.then(() => {
  205. logger.info(`working on ${item.user.username}/${item.code}`);
  206. });
  207. let messageChain = '';
  208. const author = `${item.user.full_name} (@${item.user.username}):\n`;
  209. const text = ((_a = item.caption) === null || _a === void 0 ? void 0 : _a.text) || '';
  210. if (this.mode > 0)
  211. messageChain += (author + xmlEntities.decode(text));
  212. if (this.mode === 0) {
  213. const url = (0, twitter_1.linkBuilder)({ postUrlSegment: item.code });
  214. promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay, page => page.addStyleTag({ content: 'header>div>div+div{font-size:12px; line-height:15px; padding-top:0!important}' +
  215. `header>div>div+div::before{content:"${item.user.full_name}"; color:#8e8e8e; font-weight:bold}`,
  216. })))
  217. .then(fileurl => {
  218. if (fileurl)
  219. return koishi_1.Message.Image(fileurl);
  220. return author + text;
  221. })
  222. .then(msg => {
  223. if (msg)
  224. messageChain += msg;
  225. });
  226. }
  227. const type = (mediaItem) => mediaItem.video_versions ? 'video' : 'photo';
  228. const fetchBestCandidate = (candidates, mediaType) => {
  229. const url = candidates
  230. .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))
  231. .map(variant => variant.url)[0];
  232. const altMessage = `\n[失败的${typeInZH[mediaType].type}:${url}]`;
  233. return this.fetchMedia(url)
  234. .catch(error => {
  235. logger.warn('unable to fetch media, sending plain text instead...');
  236. return altMessage;
  237. })
  238. .then(msg => { messageChain += msg; });
  239. };
  240. if (1 - this.mode % 2)
  241. promise = promise.then(() => {
  242. if (item.carousel_media) {
  243. return (0, utils_1.chainPromises)(item.carousel_media.map(carouselItem => () => fetchBestCandidate(carouselItem.video_versions ||
  244. carouselItem.image_versions2.candidates, type(carouselItem))));
  245. }
  246. else if (item.video_versions) {
  247. return fetchBestCandidate(item.video_versions, type(item));
  248. }
  249. else if (item.image_versions2) {
  250. return fetchBestCandidate(item.image_versions2.candidates, type(item));
  251. }
  252. });
  253. return promise.then(() => {
  254. logger.info(`done working on ${item.user.username}/${item.code}, message chain:`);
  255. logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
  256. callback(messageChain, xmlEntities.decode(text), author);
  257. });
  258. }));
  259. return grandPromise;
  260. }
  261. }
  262. exports.default = Webshot;