This commit is contained in:
Shisuys 2025-02-01 19:18:59 -03:00 committed by GitHub
parent 260fc46963
commit fe2a23b345
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,39 +1,57 @@
import axios, { AxiosResponse } from "axios"; import fetch from "node-fetch";
import { JSDOM } from "jsdom";
export class MediafireApi { export class MediafireApi {
private static readonly session = axios.create(); private static readonly corsProxy = "https://corsproxy.io/?";
private static readonly validMediafireIdentifierDL = /^[a-zA-Z0-9]+$/m;
private static readonly validMediafirePreDL =
/(?<=['"])(https?:)?(\/\/)?(www\.)?mediafire\.com\/(file|view|download)\/[^'"?]+\?dkey=[^'"]+(?=['"])/;
private static readonly validDynamicDL =
/(?<=['"])https?:\/\/download[0-9]+\.mediafire\.com\/[^'"]+(?=['"])/;
private static readonly checkHTTP = /^https?:\/\//m;
public static async getDownloadUrl(mediafireUrl: string): Promise<string> { public static async getDownloadUrl(mediafireUrl: string): Promise<string> {
const response: AxiosResponse<string> = await this.session.get( try {
mediafireUrl, const processedUrl = this.processUrl(mediafireUrl);
{ const response = await fetch(
headers: { `${this.corsProxy}${encodeURIComponent(processedUrl)}`
"User-Agent": );
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
},
maxRedirects: 0,
validateStatus: (status: number) => status === 200 || status === 302,
}
);
if (response.status === 302) { if (!response.ok) throw new Error("Failed to fetch Mediafire page");
const location = response.headers["location"];
if (!location) { const html = await response.text();
throw new Error("Missing location header in 302 redirect response"); return this.extractDirectUrl(html, processedUrl);
} } catch (error) {
return location; throw new Error(`Failed to get download URL: ${error.message}`);
}
}
private static processUrl(url: string): string {
let processed = url.replace("http://", "https://");
if (this.validMediafireIdentifierDL.test(processed)) {
processed = `https://mediafire.com/?${processed}`;
} }
const dom = new JSDOM(response.data); if (!this.checkHTTP.test(processed)) {
const downloadButton = dom.window.document.querySelector( processed = processed.startsWith("//")
"a#downloadButton" ? `https:${processed}`
) as HTMLAnchorElement; : `https://${processed}`;
if (!downloadButton?.href) {
throw new Error("Download button URL not found in page content");
} }
return downloadButton.href; return processed;
}
private static extractDirectUrl(html: string, _originalUrl: string): string {
const preUrls = html.match(this.validMediafirePreDL);
if (preUrls && preUrls[0]) {
return preUrls[0];
}
const dlUrls = html.match(this.validDynamicDL);
if (dlUrls && dlUrls[0]) {
return dlUrls[0];
}
throw new Error("No valid download links found");
} }
} }