webshot.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. const startTime = new Date().getTime();
  79. const getTimerTime = () => new Date().getTime() - startTime;
  80. const getTimeout = () => twitter_1.WebshotHelpers.isWaitingForLogin ? 0 : Math.max(500, webshotDelay - getTimerTime());
  81. page.setViewportSize({
  82. width: width / zoomFactor,
  83. height: height / zoomFactor,
  84. }).then(() => page.context().addCookies(this.getCookies()))
  85. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  86. .then(() => twitter_1.WebshotHelpers.handleCookieConsent(page))
  87. .then(() => ((next) => Promise.race([
  88. twitter_1.WebshotHelpers.handleLogin(page)
  89. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  90. .then(next),
  91. next(),
  92. ]))(() => (0, util_1.promisify)(setTimeout)(2000).then(() => page.waitForSelector('article', { timeout: getTimeout() }))))
  93. .catch((err) => {
  94. if (err.name !== 'TimeoutError')
  95. throw err;
  96. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  97. return null;
  98. })
  99. .then(() => page.addStyleTag({ content: 'nav,footer,main>*>*+*,header div>[class$=" "]>[class]+div,main button,canvas,main section,main section+div>ul>:not(div),' +
  100. 'main section+div>ul>div [role="button"],section+div h2,article>*>:first-child+*>*>:first-child+*{display:none!important} ' +
  101. 'section+div{overflow:hidden} section+*>*{position:relative!important} article{border-bottom:1px solid!important} ' +
  102. 'main section+div>ul{width:auto!important;padding:16px 0!important} main section+div>ul>div>li{padding:6px 2px 12px!important}',
  103. }))
  104. .then(() => page.addStyleTag({
  105. content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}',
  106. }))
  107. .then(() => page.evaluate(() => {
  108. let time = document.querySelector('div>div>time');
  109. if (time)
  110. time.parentElement.parentElement.style.display = 'none';
  111. const a = document.querySelector(`main section~div a[href="${new URL(location.href).pathname}"]`);
  112. if (a) {
  113. time = a.querySelector('time');
  114. time.innerHTML = time.title + ' ' + new Date(time.dateTime).toLocaleTimeString().slice(0, -3);
  115. a.parentElement.parentElement.style.margin = '-24px 2px 12px';
  116. const element = a.parentElement.parentElement.nextElementSibling;
  117. if (element)
  118. element.style.display = 'none';
  119. }
  120. }))
  121. .then(() => (0, utils_1.chainPromises)(morePostProcessings.map(func => () => func(page))))
  122. .then(() => (0, util_1.promisify)(setTimeout)(getTimeout()))
  123. .then(() => page.screenshot())
  124. .then(screenshot => {
  125. new pngjs_1.PNG({
  126. filterType: 4,
  127. deflateLevel: 0,
  128. }).on('parsed', function () {
  129. const idx = (x, y) => (this.width * y + x) << 2;
  130. let boundary = null;
  131. for (let y = this.height - 1; y > this.height - 3840; y -= zoomFactor) {
  132. if (this.data[idx(zoomFactor, y)] <= 38 &&
  133. this.data[idx(zoomFactor, y)] === this.data[idx(this.width - zoomFactor, y)] &&
  134. this.data[idx(zoomFactor, y + zoomFactor)] === this.data[idx(zoomFactor, y - 2 * zoomFactor)]) {
  135. boundary = y - 1;
  136. break;
  137. }
  138. }
  139. if (boundary !== null) {
  140. logger.info(`found boundary at ${boundary}, cropping image`);
  141. this.data = this.data.slice(0, idx(this.width, boundary));
  142. this.height = boundary;
  143. sharpToFile(jpeg(this.pack())).then(path => {
  144. logger.info(`finished webshot for ${url}`);
  145. resolve({ path, boundary });
  146. });
  147. }
  148. else if (height >= 8 * 1920) {
  149. logger.warn('too large, consider as a bug, returning');
  150. sharpToFile(jpeg(this.pack())).then(path => {
  151. resolve({ path, boundary: 0 });
  152. });
  153. }
  154. else {
  155. logger.info('unable to find boundary, try shooting a larger image');
  156. resolve({ path: '', boundary });
  157. }
  158. }).parse(screenshot);
  159. })
  160. .catch(err => {
  161. if (err instanceof Error && err.name !== 'TimeoutError')
  162. throw err;
  163. logger.error(`error shooting webshot for ${url}, could not load web page of tweet`);
  164. resolve({ path: '', boundary: 0 });
  165. })
  166. .finally(() => { page.close(); });
  167. }, zoomFactor, false)
  168. .catch(reject);
  169. });
  170. return promise.then(data => {
  171. if (data.boundary === null) {
  172. return this.renderWebshot(url, height + 3840, webshotDelay, ...morePostProcessings);
  173. }
  174. else
  175. return data.path;
  176. }).catch(error => this.reconnect(error)
  177. .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings)));
  178. };
  179. this.fetchMedia = (url) => new Promise((resolve, reject) => {
  180. logger.info(`fetching ${url}`);
  181. (0, axios_1.default)({
  182. method: 'get',
  183. url,
  184. responseType: 'arraybuffer',
  185. timeout: 150000,
  186. }).then(res => {
  187. if (res.status === 200) {
  188. logger.info(`successfully fetched ${url}`);
  189. resolve(res.data);
  190. }
  191. else {
  192. logger.error(`failed to fetch ${url}: ${res.status}`);
  193. reject();
  194. }
  195. }).catch(err => {
  196. logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
  197. reject();
  198. });
  199. }).then(data => (ext => {
  200. const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
  201. (0, fs_1.writeFileSync)(mediaTempFilePath, Buffer.from(data));
  202. const path = `file://${mediaTempFilePath}`;
  203. switch (ext) {
  204. case 'jpg':
  205. case 'png':
  206. return koishi_1.Message.Image(path);
  207. case 'mp4':
  208. return koishi_1.Message.Video(path);
  209. }
  210. logger.warn('unable to find MIME type of fetched media, failing this fetch');
  211. throw Error();
  212. })(/\/.+\.(?:.*?(?<=[?&])stp=dst-(jpg)|(.+?)\?)/.exec(url).filter(g => g)[1]));
  213. if (this.mode = mode) {
  214. if (onready)
  215. onready();
  216. }
  217. else {
  218. this.getCookies = getCookies;
  219. this.wsUrl = wsUrl;
  220. this.connect(() => onready && onready(this.performOnNewPage));
  221. }
  222. }
  223. webshot(lazyMediaItems, callback, webshotDelay) {
  224. let grandPromise = Promise.resolve();
  225. lazyMediaItems.forEach(lazyItem => grandPromise = grandPromise.then(lazyItem.item).then(item => {
  226. var _a;
  227. let promise = Promise.resolve();
  228. promise = promise.then(() => {
  229. logger.info(`working on ${item.user.username}/${item.code}`);
  230. });
  231. let messageChain = '';
  232. const author = `${item.user.full_name} (@${item.user.username}):\n`;
  233. const text = ((_a = item.caption) === null || _a === void 0 ? void 0 : _a.text) || '';
  234. if (this.mode > 0)
  235. messageChain += (author + xmlEntities.decode(text));
  236. if (this.mode === 0) {
  237. const url = (0, twitter_1.linkBuilder)({ postUrlSegment: item.code });
  238. promise = promise.then(() => this.renderWebshot(url, 3840, webshotDelay, page => page.addStyleTag({ content: 'header>div>div+div{font-size:12px; line-height:15px; padding-top:0!important}' +
  239. `header>div>div+div::before{content:"${item.user.full_name}"; color:#8e8e8e; font-weight:bold}`,
  240. })))
  241. .then(fileurl => {
  242. if (fileurl)
  243. return koishi_1.Message.Image(fileurl);
  244. return author + text;
  245. })
  246. .then(msg => {
  247. if (msg)
  248. messageChain += msg;
  249. });
  250. }
  251. const type = (mediaItem) => mediaItem.video_versions ? 'video' : 'photo';
  252. const fetchBestCandidate = (candidates, mediaType) => {
  253. const url = candidates
  254. .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))
  255. .map(variant => variant.url)[0];
  256. const altMessage = `\n[失败的${typeInZH[mediaType].type}:${url}]`;
  257. return this.fetchMedia(url)
  258. .catch(error => {
  259. logger.warn('unable to fetch media, sending plain text instead...');
  260. return altMessage;
  261. })
  262. .then(msg => { messageChain += msg; });
  263. };
  264. if (1 - this.mode % 2)
  265. promise = promise.then(() => {
  266. if (item.carousel_media) {
  267. return (0, utils_1.chainPromises)(item.carousel_media.map(carouselItem => () => fetchBestCandidate(carouselItem.video_versions ||
  268. carouselItem.image_versions2.candidates, type(carouselItem))));
  269. }
  270. else if (item.video_versions) {
  271. return fetchBestCandidate(item.video_versions, type(item));
  272. }
  273. else if (item.image_versions2) {
  274. return fetchBestCandidate(item.image_versions2.candidates, type(item));
  275. }
  276. });
  277. return promise.then(() => {
  278. logger.info(`done working on ${item.user.username}/${item.code}, message chain:`);
  279. logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
  280. callback(messageChain, xmlEntities.decode(text), author);
  281. });
  282. }));
  283. return grandPromise;
  284. }
  285. }
  286. exports.default = Webshot;