el.xwx.moe/lib/shared/fetchTitleAndHeaders.ts

57 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-12-31 09:46:09 -06:00
import fetch from "node-fetch";
import https from "https";
import { SocksProxyAgent } from "socks-proxy-agent";
2024-06-29 16:18:38 -05:00
export default async function fetchTitleAndHeaders(url: string) {
2023-06-26 18:35:12 -05:00
try {
2023-12-31 09:46:09 -06:00
const httpsAgent = new https.Agent({
rejectUnauthorized:
process.env.IGNORE_UNAUTHORIZED_CA === "true" ? false : true,
});
// fetchOpts allows a proxy to be defined
let fetchOpts = {
2023-12-31 09:46:09 -06:00
agent: httpsAgent,
};
2024-02-19 14:38:36 -06:00
if (process.env.PROXY) {
// parse proxy url
2024-02-19 14:38:36 -06:00
let proxy = new URL(process.env.PROXY);
// if authentication set, apply to proxy URL
2024-02-19 14:38:36 -06:00
if (process.env.PROXY_USERNAME) {
proxy.username = process.env.PROXY_USERNAME;
proxy.password = process.env.PROXY_PASSWORD || "";
}
// add socks5 proxy to fetchOpts
fetchOpts = { agent: new SocksProxyAgent(proxy.toString()) }; //TODO: add support for http/https proxies
}
2024-04-17 17:02:54 -05:00
const responsePromise = fetch(url, fetchOpts);
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error("Fetch title timeout"));
}, 10 * 1000); // Stop after 10 seconds
});
const response = await Promise.race([responsePromise, timeoutPromise]);
2024-04-17 17:02:54 -05:00
if ((response as any)?.status) {
const text = await (response as any).text();
2024-04-17 17:02:54 -05:00
// regular expression to find the <title> tag
let match = text.match(/<title.*>([^<]*)<\/title>/);
2024-06-29 16:18:38 -05:00
const title = match[1] || "";
const headers = (response as Response)?.headers || null;
return { title, headers };
2024-04-17 17:02:54 -05:00
} else {
2024-06-29 16:18:38 -05:00
return { title: "", headers: null };
2024-04-17 17:02:54 -05:00
}
2023-06-26 18:35:12 -05:00
} catch (err) {
console.log(err);
2024-06-29 16:18:38 -05:00
return { title: "", headers: null };
2023-06-26 18:35:12 -05:00
}
}