forked from Gratenes/m3u8CloudflareWorkerProxy
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.ts
61 lines (56 loc) · 2.12 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
addEventListener("fetch", (event) => {
event.respondWith(respondfetch(event.request));
});
async function respondfetch(request) {
try {
const url = new URL(request.url);
const refererUrl = decodeURIComponent(url.searchParams.get("referer") || "");
const targetUrl = decodeURIComponent(url.searchParams.get("url") || "");
const originUrl = decodeURIComponent(url.searchParams.get("origin") || "");
const proxyAll = decodeURIComponent(url.searchParams.get("all") || "");
if (!targetUrl) {
return new Response("Invalid URL", { status: 400 });
}
const response = await fetch(targetUrl, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
Referer: refererUrl || "",
Origin: originUrl || "",
},
});
let modifiedM3u8;
if (targetUrl.includes(".m3u8")) {
modifiedM3u8 = await response.text();
const targetUrlTrimmed = `${encodeURIComponent(
targetUrl.replace(/([^/]+\.m3u8)$/, "").trim()
)}`;
const encodedUrl = encodeURIComponent(refererUrl);
const encodedOrigin = encodeURIComponent(originUrl);
modifiedM3u8 = modifiedM3u8.split("\n").map((line) => {
if (line.startsWith("#") || line.trim() == '') {
return line;
}
else if(proxyAll == 'yes' && line.startsWith('http')){ //https://yourproxy.com/?url=https://somevideo.m3u8&all=yes
return `${url.origin}?url=${line}`;
}
return `?url=${targetUrlTrimmed}${line}${originUrl ? `&origin=${encodedOrigin}` : ""
}${refererUrl ? `&referer=${encodedUrl}` : ""
}`;
}).join("\n");
}
return new Response(modifiedM3u8 || response.body, {
status: response.status,
statusText: response.statusText,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type":
response.headers?.get("Content-Type") ||
"application/vnd.apple.mpegurl",
},
});
} catch (e) {
return new Response(e.message, { status: 500 });
}
}