webshot.js 15 KB

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