{"size": 1580, "ext": "js", "max_stars_repo_path": "lib/routes/pixiv/pixiv-got.js", "max_stars_repo_name": "PeterDaveHello/RSSHub", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/routes/pixiv/pixiv-got.js", "max_issues_repo_name": "PeterDaveHello/RSSHub", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/routes/pixiv/pixiv-got.js", "max_forks_repo_name": "PeterDaveHello/RSSHub", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.7441860465, "max_line_length": 106, "alphanum_fraction": 0.4556962025}
const dnsPromises = require('dns').promises;
const ipRegex = require('ip-regex');
const got = require('@/utils/got');
const logger = require('@/utils/logger');
const pixivConfig = require('@/config').value.pixiv;

const pixivGot = got.extend({
    hooks: {
        beforeRequest: [
            async (options) => {
                if (!pixivConfig.bypassCdn) {
                    return;
                }
                let hostname = null;
                const isIP = ipRegex({ exact: true }).test(pixivConfig.bypassCdnHostname);
                if (isIP) {
                    hostname = pixivConfig.bypassCdnHostname;
                } else {
                    try {
                        const addresses = await dnsPromises.resolve4(pixivConfig.bypassCdnHostname);
                        if (addresses.length) {
                            hostname = addresses[Math.floor(addresses.length * Math.random())];
                        } else {
                            logger.warn(`No IPv4 address resolved from ${pixivConfig.bypassCdnHostname}`);
                        }
                    } catch (e) {
                        logger.error(`Failed to resolve ${pixivConfig.bypassCdnHostname}`);
                    }
                }
                if (hostname) {
                    options.headers = {
                        ...options.headers,
                        host: options.url.hostname,
                    };
                    options.url.hostname = hostname;
                }
            },
        ],
    },
});

module.exports = pixivGot;
