123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262 |
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- const fs_1 = require("fs");
- const util_1 = require("util");
- const axios_1 = require("axios");
- const CallableInstance = require("callable-instance");
- const html_entities_1 = require("html-entities");
- const pngjs_1 = require("pngjs");
- const puppeteer = require("playwright");
- const sharp = require("sharp");
- const temp = require("temp");
- const loggers_1 = require("./loggers");
- const koishi_1 = require("./koishi");
- const utils_1 = require("./utils");
- const twitter_1 = require("./twitter");
- const xmlEntities = new html_entities_1.XmlEntities();
- const ZHType = (type) => new class extends String {
- constructor() {
- super(...arguments);
- this.type = super.toString();
- this.toString = () => `[${super.toString()}]`;
- }
- }(type);
- const typeInZH = {
- photo: ZHType('图片'),
- video: ZHType('视频'),
- };
- const logger = (0, loggers_1.getLogger)('webshot');
- class Webshot extends CallableInstance {
- constructor(wsUrl, mode, getCookies, onready) {
- super('webshot');
- this.connect = (onready) => axios_1.default.get(this.wsUrl)
- .then(res => {
- logger.info(`received websocket endpoint: ${JSON.stringify(res.data)}`);
- const browserType = Object.keys(res.data)[0];
- return puppeteer[browserType]
- .connect({ wsEndpoint: res.data[browserType] });
- })
- .then(browser => this.browser = browser)
- .then(() => {
- logger.info('launched puppeteer browser');
- if (onready)
- return onready();
- })
- .catch(error => this.reconnect(error, onready));
- this.reconnect = (error, onready) => {
- logger.error(`connection error, reason: ${error}`);
- logger.warn('trying to reconnect in 2.5s...');
- return (0, util_1.promisify)(setTimeout)(2500)
- .then(() => this.connect(onready));
- };
- this.performOnNewPage = (action, zoomFactor = 2, reconnectOnError = true) => this.browser.newPage({
- bypassCSP: true,
- deviceScaleFactor: zoomFactor,
- locale: 'ja-JP',
- timezoneId: 'Asia/Tokyo',
- userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
- }).then(action)
- .catch(error => {
- if (reconnectOnError) {
- return this.reconnect(error)
- .then(() => this.performOnNewPage(action, zoomFactor, reconnectOnError));
- }
- throw error;
- });
- this.renderWebshot = (url, height, webshotDelay, ...morePostProcessings) => {
- temp.track();
- const jpeg = (data) => data.pipe(sharp()).jpeg({ quality: 90, trellisQuantisation: true });
- const sharpToFile = (pic) => new Promise(resolve => {
- const webshotTempFilePath = temp.path({ suffix: '.jpg' });
- pic.toFile(webshotTempFilePath).then(() => resolve(`file://${webshotTempFilePath}`));
- });
- const promise = new Promise((resolve, reject) => {
- const width = 720;
- const zoomFactor = 2;
- logger.info(`shooting ${width}*${height} webshot for ${url}`);
- this.performOnNewPage(page => {
- let startTime;
- let gotoUrl = () => {
- startTime = new Date().getTime();
- return page.goto(url, { waitUntil: 'load', timeout: getTimeout() });
- };
- const getTimerTime = () => new Date().getTime() - startTime;
- const getTimeout = () => twitter_1.WebshotHelpers.isWaitingForLogin ? 0 : Math.max(500, webshotDelay - getTimerTime());
- page.setViewportSize({
- width: width / zoomFactor,
- height: height / zoomFactor,
- }).then(() => page.context().addCookies(this.getCookies()))
- .then(gotoUrl)
- .then(() => twitter_1.WebshotHelpers.handleCookieConsent(page))
- .then(() => ((next) => Promise.race([
- twitter_1.WebshotHelpers.handleLogin(page).then(gotoUrl).then(next),
- (0, util_1.promisify)(setTimeout)(2000).then(next),
- ]))(() => page.waitForSelector('article', { timeout: getTimeout() })))
- .catch((err) => {
- if (err.name !== 'TimeoutError')
- throw err;
- logger.warn(`navigation timed out at ${getTimerTime()} ms`);
- })
- .then(() => page.addStyleTag({ content: 'nav,footer,main>*>*+*,header div>[class$=" "]>[class]+div,main button,canvas,main section,main section+div>ul>:not(div),' +
- 'main section+div>ul>div [role="button"],section+div h2,article>*>:first-child+*>*>:first-child+*{display:none!important} ' +
- 'section+div{overflow:hidden} section+*>*{position:relative!important} main>div{margin-bottom:0!important}' +
- 'main section+div>ul{width:auto!important;padding:16px 0!important} main section+div>ul>div>li{padding:6px 2px 12px!important}',
- }))
- .then(() => page.addStyleTag({ content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
- '*{-webkit-font-smoothing:antialiased!important}',
- }))
- .then(() => page.evaluate(() => {
- let time = document.querySelector('div>div>time');
- if (time)
- time.parentElement.parentElement.style.display = 'none';
- const a = document.querySelector(`main section~div a[href="${new URL(location.href).pathname}"]`);
- if (a) {
- time = a.querySelector('time');
- time.innerHTML = time.title + ' ' + new Date(time.dateTime).toLocaleTimeString().slice(0, -3);
- a.parentElement.parentElement.style.margin = '-24px 2px 12px';
- const element = a.parentElement.parentElement.nextElementSibling;
- if (element)
- element.style.display = 'none';
- }
- }))
- .then(() => (0, utils_1.chainPromises)(morePostProcessings.map(func => () => func(page))))
- .then(() => (0, util_1.promisify)(setTimeout)(getTimeout()))
- .then(() => page.$('article').then(article => article.screenshot()))
- .then(screenshot => {
- new pngjs_1.PNG({
- filterType: 4,
- deflateLevel: 0,
- }).on('parsed', function () {
- sharpToFile(jpeg(this.pack())).then(path => {
- logger.info(`finished webshot for ${url}`);
- resolve({ path, boundary: this.height });
- });
- }).parse(screenshot);
- })
- .catch(err => {
- if (err instanceof Error && err.name !== 'TimeoutError')
- throw err;
- logger.error(`error shooting webshot for ${url}, could not load web page of post`);
- resolve({ path: '', boundary: 0 });
- })
- .finally(() => { page.close(); });
- }, zoomFactor, false)
- .catch(reject);
- });
- return promise.then(data => {
- if (data.boundary === null) {
- return this.renderWebshot(url, height + 1920, webshotDelay, ...morePostProcessings);
- }
- else
- return data.path;
- }).catch(error => this.reconnect(error)
- .then(() => this.renderWebshot(url, height, webshotDelay, ...morePostProcessings)));
- };
- this.fetchMedia = (url) => new Promise((resolve, reject) => {
- logger.info(`fetching ${url}`);
- (0, axios_1.default)({
- method: 'get',
- url,
- responseType: 'arraybuffer',
- timeout: 150000,
- }).then(res => {
- if (res.status === 200) {
- logger.info(`successfully fetched ${url}`);
- resolve(res.data);
- }
- else {
- logger.error(`failed to fetch ${url}: ${res.status}`);
- reject();
- }
- }).catch(err => {
- logger.error(`failed to fetch ${url}: ${err instanceof Error ? err.message : err}`);
- reject();
- });
- }).then(data => (ext => {
- const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
- (0, fs_1.writeFileSync)(mediaTempFilePath, Buffer.from(data));
- const path = `file://${mediaTempFilePath}`;
- switch (ext) {
- case 'jpg':
- case 'png':
- return koishi_1.Message.Image(path);
- case 'mp4':
- return koishi_1.Message.Video(path);
- }
- logger.warn('unable to find MIME type of fetched media, failing this fetch');
- throw Error();
- })(/\/.+\.(?:.*?(?<=[?&])stp=dst-(jpg)|(.+?)\?)/.exec(url).filter(g => g)[1]));
- if (this.mode = mode) {
- if (onready)
- onready();
- }
- else {
- this.getCookies = getCookies;
- this.wsUrl = wsUrl;
- this.connect(() => onready && onready(this.performOnNewPage));
- }
- }
- webshot(lazyMediaItems, callback, webshotDelay) {
- let grandPromise = Promise.resolve();
- lazyMediaItems.forEach(lazyItem => grandPromise = grandPromise.then(lazyItem.item).then(item => {
- var _a;
- let promise = Promise.resolve();
- promise = promise.then(() => {
- logger.info(`working on ${item.user.username}/${item.code}`);
- });
- let messageChain = '';
- const author = `${item.user.full_name} (@${item.user.username}):\n`;
- const text = ((_a = item.caption) === null || _a === void 0 ? void 0 : _a.text) || '';
- if (this.mode > 0)
- messageChain += (author + xmlEntities.decode(text));
- if (this.mode === 0) {
- const url = (0, twitter_1.linkBuilder)({ postUrlSegment: item.code });
- 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}' +
- `header>div>div+div::before{content:"${item.user.full_name}"; color:#8e8e8e; font-weight:bold}`,
- })))
- .then(fileurl => {
- if (fileurl)
- return koishi_1.Message.Image(fileurl);
- return author + text;
- })
- .then(msg => {
- if (msg)
- messageChain += msg;
- });
- }
- const type = (mediaItem) => mediaItem.video_versions ? 'video' : 'photo';
- const fetchBestCandidate = (candidates, mediaType) => {
- const url = candidates
- .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))
- .map(variant => variant.url)[0];
- const altMessage = `\n[失败的${typeInZH[mediaType].type}:${url}]`;
- return this.fetchMedia(url)
- .catch(error => {
- logger.warn('unable to fetch media, sending plain text instead...');
- return altMessage;
- })
- .then(msg => { messageChain += msg; });
- };
- if (1 - this.mode % 2)
- promise = promise.then(() => {
- if (item.carousel_media) {
- return (0, utils_1.chainPromises)(item.carousel_media.map(carouselItem => () => fetchBestCandidate(carouselItem.video_versions ||
- carouselItem.image_versions2.candidates, type(carouselItem))));
- }
- else if (item.video_versions) {
- return fetchBestCandidate(item.video_versions, type(item));
- }
- else if (item.image_versions2) {
- return fetchBestCandidate(item.image_versions2.candidates, type(item));
- }
- });
- return promise.then(() => {
- logger.info(`done working on ${item.user.username}/${item.code}, message chain:`);
- logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
- callback(messageChain, xmlEntities.decode(text), author);
- });
- }));
- return grandPromise;
- }
- }
- exports.default = Webshot;
|