Skip to content

一分钟搭建影视站,支持Docker等部署方式

增加内置代理相关的functions函数文件

CTZZG5f60f2afa96b
diff --git a/api/proxy/[...path].mjs b/api/proxy/[...path].mjs
new file mode 100644
index 0000000..047a125
--- /dev/null
+++ b/api/proxy/[...path].mjs
@@ -0,0 +1,451 @@
+// /api/proxy/[...path].mjs - Vercel Serverless Function (ES Module)
+
+import fetch from 'node-fetch';
+import { URL } from 'url'; // 使用 Node.js 内置 URL 处理
+
+// --- 配置 (从环境变量读取) ---
+const DEBUG_ENABLED = process.env.DEBUG === 'true';
+const CACHE_TTL = parseInt(process.env.CACHE_TTL || '86400', 10); // 默认 24 小时
+const MAX_RECURSION = parseInt(process.env.MAX_RECURSION || '5', 10); // 默认 5 层
+
+// --- User Agent 处理 ---
+// 默认 User Agent 列表
+let USER_AGENTS = [
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
+];
+// 尝试从环境变量读取并解析 USER_AGENTS_JSON
+try {
+ const agentsJsonString = process.env.USER_AGENTS_JSON;
+ if (agentsJsonString) {
+ const parsedAgents = JSON.parse(agentsJsonString);
+ // 检查解析结果是否为非空数组
+ if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
+ USER_AGENTS = parsedAgents; // 使用环境变量中的数组
+ console.log(`[代理日志] 已从环境变量加载 ${USER_AGENTS.length} 个 User Agent。`);
+ } else {
+ console.warn("[代理日志] 环境变量 USER_AGENTS_JSON 不是有效的非空数组,使用默认值。");
+ }
+ } else {
+ console.log("[代理日志] 未设置环境变量 USER_AGENTS_JSON,使用默认 User Agent。");
+ }
+} catch (e) {
+ // 如果 JSON 解析失败,记录错误并使用默认值
+ console.error(`[代理日志] 解析环境变量 USER_AGENTS_JSON 出错: ${e.message}。使用默认 User Agent。`);
+}
+
+// 广告过滤在代理中禁用,由播放器处理
+const FILTER_DISCONTINUITY = false;
+
+
+// --- 辅助函数 ---
+
+function logDebug(message) {
+ if (DEBUG_ENABLED) {
+ console.log(`[代理日志] ${message}`);
+ }
+}
+
+/**
+ * 从代理请求路径中提取编码后的目标 URL。
+ * @param {string} encodedPath - URL 编码后的路径部分 (例如 "https%3A%2F%2F...")
+ * @returns {string|null} 解码后的目标 URL,如果无效则返回 null。
+ */
+function getTargetUrlFromPath(encodedPath) {
+ if (!encodedPath) {
+ logDebug("getTargetUrlFromPath 收到空路径。");
+ return null;
+ }
+ try {
+ const decodedUrl = decodeURIComponent(encodedPath);
+ // 基础检查,看是否像一个 HTTP/HTTPS URL
+ if (decodedUrl.match(/^https?:\/\/.+/i)) {
+ return decodedUrl;
+ } else {
+ logDebug(`无效的解码 URL 格式: ${decodedUrl}`);
+ // 备选检查:原始路径是否未编码但看起来像 URL?
+ if (encodedPath.match(/^https?:\/\/.+/i)) {
+ logDebug(`警告: 路径未编码但看起来像 URL: ${encodedPath}`);
+ return encodedPath;
+ }
+ return null;
+ }
+ } catch (e) {
+ // 捕获解码错误 (例如格式错误的 URI)
+ logDebug(`解码目标 URL 出错: ${encodedPath} - ${e.message}`);
+ return null;
+ }
+}
+
+function getBaseUrl(urlStr) {
+ if (!urlStr) return '';
+ try {
+ const parsedUrl = new URL(urlStr);
+ // 处理根目录或只有文件名的情况
+ const pathSegments = parsedUrl.pathname.split('/').filter(Boolean); // 移除空字符串
+ if (pathSegments.length <= 1) {
+ return `${parsedUrl.origin}/`;
+ }
+ pathSegments.pop(); // 移除最后一段
+ return `${parsedUrl.origin}/${pathSegments.join('/')}/`;
+ } catch (e) {
+ logDebug(`获取 BaseUrl 失败: "${urlStr}": ${e.message}`);
+ // 备用方法:查找最后一个斜杠
+ const lastSlashIndex = urlStr.lastIndexOf('/');
+ if (lastSlashIndex > urlStr.indexOf('://') + 2) { // 确保不是协议部分的斜杠
+ return urlStr.substring(0, lastSlashIndex + 1);
+ }
+ return urlStr + '/'; // 如果没有路径,添加斜杠
+ }
+}
+
+function resolveUrl(baseUrl, relativeUrl) {
+ if (!relativeUrl) return ''; // 处理空的 relativeUrl
+ if (relativeUrl.match(/^https?:\/\/.+/i)) {
+ return relativeUrl; // 已经是绝对 URL
+ }
+ if (!baseUrl) return relativeUrl; // 没有基础 URL 无法解析
+
+ try {
+ // 使用 Node.js 的 URL 构造函数处理相对路径
+ return new URL(relativeUrl, baseUrl).toString();
+ } catch (e) {
+ logDebug(`URL 解析失败: base="${baseUrl}", relative="${relativeUrl}". 错误: ${e.message}`);
+ // 简单的备用逻辑
+ if (relativeUrl.startsWith('/')) {
+ try {
+ const baseOrigin = new URL(baseUrl).origin;
+ return `${baseOrigin}${relativeUrl}`;
+ } catch { return relativeUrl; } // 如果 baseUrl 也无效,返回原始相对路径
+ } else {
+ // 假设相对于包含基础 URL 资源的目录
+ return `${baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1)}${relativeUrl}`;
+ }
+ }
+}
+
+// ** 已修正:确保生成 /proxy/ 前缀的链接 **
+function rewriteUrlToProxy(targetUrl) {
+ if (!targetUrl || typeof targetUrl !== 'string') return '';
+ // 返回与 vercel.json 的 "source" 和前端 PROXY_URL 一致的路径
+ return `/proxy/${encodeURIComponent(targetUrl)}`;
+}
+
+function getRandomUserAgent() {
+ return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
+}
+
+async function fetchContentWithType(targetUrl, requestHeaders) {
+ // 准备请求头
+ const headers = {
+ 'User-Agent': getRandomUserAgent(),
+ 'Accept': requestHeaders['accept'] || '*/*', // 传递原始 Accept 头(如果有)
+ 'Accept-Language': requestHeaders['accept-language'] || 'zh-CN,zh;q=0.9,en;q=0.8',
+ // 尝试设置一个合理的 Referer
+ 'Referer': requestHeaders['referer'] || new URL(targetUrl).origin,
+ };
+ // 清理空值的头
+ Object.keys(headers).forEach(key => headers[key] === undefined || headers[key] === null || headers[key] === '' ? delete headers[key] : {});
+
+ logDebug(`准备请求目标: ${targetUrl},请求头: ${JSON.stringify(headers)}`);
+
+ try {
+ // 发起 fetch 请求
+ const response = await fetch(targetUrl, { headers, redirect: 'follow' });
+
+ // 检查响应是否成功
+ if (!response.ok) {
+ const errorBody = await response.text().catch(() => ''); // 尝试获取错误响应体
+ logDebug(`请求失败: ${response.status} ${response.statusText} - ${targetUrl}`);
+ // 创建一个包含状态码的错误对象
+ const err = new Error(`HTTP 错误 ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 200)}`);
+ err.status = response.status; // 将状态码附加到错误对象
+ throw err; // 抛出错误
+ }
+
+ // 读取响应内容
+ const content = await response.text();
+ const contentType = response.headers.get('content-type') || '';
+ logDebug(`请求成功: ${targetUrl}, Content-Type: ${contentType}, 内容长度: ${content.length}`);
+ // 返回结果
+ return { content, contentType, responseHeaders: response.headers };
+
+ } catch (error) {
+ // 捕获 fetch 本身的错误(网络、超时等)或上面抛出的 HTTP 错误
+ logDebug(`请求异常 ${targetUrl}: ${error.message}`);
+ // 重新抛出,确保包含原始错误信息
+ throw new Error(`请求目标 URL 失败 ${targetUrl}: ${error.message}`);
+ }
+}
+
+function isM3u8Content(content, contentType) {
+ if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) {
+ return true;
+ }
+ return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
+}
+
+function processKeyLine(line, baseUrl) {
+ return line.replace(/URI="([^"]+)"/, (match, uri) => {
+ const absoluteUri = resolveUrl(baseUrl, uri);
+ logDebug(`处理 KEY URI: 原始='${uri}', 绝对='${absoluteUri}'`);
+ return `URI="${rewriteUrlToProxy(absoluteUri)}"`;
+ });
+}
+
+function processMapLine(line, baseUrl) {
+ return line.replace(/URI="([^"]+)"/, (match, uri) => {
+ const absoluteUri = resolveUrl(baseUrl, uri);
+ logDebug(`处理 MAP URI: 原始='${uri}', 绝对='${absoluteUri}'`);
+ return `URI="${rewriteUrlToProxy(absoluteUri)}"`;
+ });
+ }
+
+function processMediaPlaylist(url, content) {
+ const baseUrl = getBaseUrl(url);
+ if (!baseUrl) {
+ logDebug(`无法确定媒体列表的 Base URL: ${url},相对路径可能无法处理。`);
+ }
+ const lines = content.split('\n');
+ const output = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ // 保留最后一个空行
+ if (!line && i === lines.length - 1) { output.push(line); continue; }
+ if (!line) continue; // 跳过中间空行
+ // 广告过滤已禁用
+ if (line.startsWith('#EXT-X-KEY')) { output.push(processKeyLine(line, baseUrl)); continue; }
+ if (line.startsWith('#EXT-X-MAP')) { output.push(processMapLine(line, baseUrl)); continue; }
+ if (line.startsWith('#EXTINF')) { output.push(line); continue; }
+ // 处理 URL 行
+ if (!line.startsWith('#')) {
+ const absoluteUrl = resolveUrl(baseUrl, line);
+ logDebug(`重写媒体片段: 原始='${line}', 解析后='${absoluteUrl}'`);
+ output.push(rewriteUrlToProxy(absoluteUrl)); continue;
+ }
+ // 保留其他 M3U8 标签
+ output.push(line);
+ }
+ return output.join('\n');
+}
+
+async function processM3u8Content(targetUrl, content, recursionDepth = 0) {
+ // 判断是主列表还是媒体列表
+ if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) {
+ logDebug(`检测到主播放列表: ${targetUrl} (深度: ${recursionDepth})`);
+ return await processMasterPlaylist(targetUrl, content, recursionDepth);
+ }
+ logDebug(`检测到媒体播放列表: ${targetUrl} (深度: ${recursionDepth})`);
+ return processMediaPlaylist(targetUrl, content);
+}
+
+async function processMasterPlaylist(url, content, recursionDepth) {
+ // 检查递归深度
+ if (recursionDepth > MAX_RECURSION) {
+ throw new Error(`处理主播放列表时,递归深度超过最大限制 (${MAX_RECURSION}): ${url}`);
+ }
+ const baseUrl = getBaseUrl(url);
+ const lines = content.split('\n');
+ let highestBandwidth = -1;
+ let bestVariantUrl = '';
+
+ // 查找最高带宽的流
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].startsWith('#EXT-X-STREAM-INF')) {
+ const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/);
+ const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0;
+ let variantUriLine = '';
+ // 找到下一行的 URI
+ for (let j = i + 1; j < lines.length; j++) {
+ const line = lines[j].trim();
+ if (line && !line.startsWith('#')) { variantUriLine = line; i = j; break; }
+ }
+ if (variantUriLine && currentBandwidth >= highestBandwidth) {
+ highestBandwidth = currentBandwidth;
+ bestVariantUrl = resolveUrl(baseUrl, variantUriLine);
+ }
+ }
+ }
+ // 如果没有找到带宽信息,尝试查找第一个 .m3u8 链接
+ if (!bestVariantUrl) {
+ logDebug(`主播放列表中未找到 BANDWIDTH 信息,尝试查找第一个 URI: ${url}`);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ // 更可靠地匹配 .m3u8 链接
+ if (line && !line.startsWith('#') && line.match(/\.m3u8($|\?.*)/i)) {
+ bestVariantUrl = resolveUrl(baseUrl, line);
+ logDebug(`备选方案: 找到第一个子播放列表 URI: ${bestVariantUrl}`);
+ break;
+ }
+ }
+ }
+ // 如果仍然没有找到子列表 URL
+ if (!bestVariantUrl) {
+ logDebug(`在主播放列表 ${url} 中未找到有效的子列表 URI,将其作为媒体列表处理。`);
+ return processMediaPlaylist(url, content);
+ }
+
+ logDebug(`选择的子播放列表 (带宽: ${highestBandwidth}): ${bestVariantUrl}`);
+ // 请求选定的子播放列表内容 (注意:这里传递 {} 作为请求头,不传递客户端的原始请求头)
+ const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl, {});
+
+ // 检查获取的内容是否是 M3U8
+ if (!isM3u8Content(variantContent, variantContentType)) {
+ logDebug(`获取的子播放列表 ${bestVariantUrl} 不是 M3U8 (类型: ${variantContentType}),将其作为媒体列表处理。`);
+ return processMediaPlaylist(bestVariantUrl, variantContent);
+ }
+
+ // 递归处理获取到的子 M3U8 内容
+ return await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1);
+}
+
+
+// --- Vercel Handler 函数 ---
+export default async function handler(req, res) {
+ // --- 记录请求开始 ---
+ console.info('--- Vercel 代理请求开始 ---');
+ console.info('时间:', new Date().toISOString());
+ console.info('方法:', req.method);
+ console.info('URL:', req.url); // 原始请求 URL (例如 /proxy/...)
+ console.info('查询参数:', JSON.stringify(req.query)); // Vercel 解析的查询参数
+
+ // --- 提前设置 CORS 头 ---
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', '*'); // 允许所有请求头
+
+ // --- 处理 OPTIONS 预检请求 ---
+ if (req.method === 'OPTIONS') {
+ console.info("处理 OPTIONS 预检请求");
+ res.status(204).setHeader('Access-Control-Max-Age', '86400').end(); // 缓存预检结果 24 小时
+ return;
+ }
+
+ let targetUrl = null; // 初始化目标 URL
+
+ try { // ---- 开始主处理逻辑的 try 块 ----
+
+ // --- 提取目标 URL (主要依赖 req.query["...path"]) ---
+ // Vercel 将 :path* 捕获的内容(可能包含斜杠)放入 req.query["...path"] 数组
+ const pathData = req.query["...path"]; // 使用正确的键名
+ let encodedUrlPath = '';
+
+ if (pathData) {
+ if (Array.isArray(pathData)) {
+ encodedUrlPath = pathData.join('/'); // 重新组合
+ console.info(`从 req.query["...path"] (数组) 组合的编码路径: ${encodedUrlPath}`);
+ } else if (typeof pathData === 'string') {
+ encodedUrlPath = pathData; // 也处理 Vercel 可能只返回字符串的情况
+ console.info(`从 req.query["...path"] (字符串) 获取的编码路径: ${encodedUrlPath}`);
+ } else {
+ console.warn(`[代理警告] req.query["...path"] 类型未知: ${typeof pathData}`);
+ }
+ } else {
+ console.warn(`[代理警告] req.query["...path"] 为空或未定义。`);
+ // 备选:尝试从 req.url 提取(如果需要)
+ if (req.url && req.url.startsWith('/proxy/')) {
+ encodedUrlPath = req.url.substring('/proxy/'.length);
+ console.info(`使用备选方法从 req.url 提取的编码路径: ${encodedUrlPath}`);
+ }
+ }
+
+ // 如果仍然为空,则无法继续
+ if (!encodedUrlPath) {
+ throw new Error("无法从请求中确定编码后的目标路径。");
+ }
+
+ // 解析目标 URL
+ targetUrl = getTargetUrlFromPath(encodedUrlPath);
+ console.info(`解析出的目标 URL: ${targetUrl || 'null'}`); // 记录解析结果
+
+ // 检查目标 URL 是否有效
+ if (!targetUrl) {
+ // 抛出包含更多上下文的错误
+ throw new Error(`无效的代理请求路径。无法从组合路径 "${encodedUrlPath}" 中提取有效的目标 URL。`);
+ }
+
+ console.info(`开始处理目标 URL 的代理请求: ${targetUrl}`);
+
+ // --- 获取并处理目标内容 ---
+ const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl, req.headers);
+
+ // --- 如果是 M3U8,处理并返回 ---
+ if (isM3u8Content(content, contentType)) {
+ console.info(`正在处理 M3U8 内容: ${targetUrl}`);
+ const processedM3u8 = await processM3u8Content(targetUrl, content);
+
+ console.info(`成功处理 M3U8: ${targetUrl}`);
+ // 发送处理后的 M3U8 响应
+ res.status(200)
+ .setHeader('Content-Type', 'application/vnd.apple.mpegurl;charset=utf-8')
+ .setHeader('Cache-Control', `public, max-age=${CACHE_TTL}`)
+ // 移除可能导致问题的原始响应头
+ .removeHeader('content-encoding') // 很重要!node-fetch 已解压
+ .removeHeader('content-length') // 长度已改变
+ .send(processedM3u8); // 发送 M3U8 文本
+
+ } else {
+ // --- 如果不是 M3U8,直接返回原始内容 ---
+ console.info(`直接返回非 M3U8 内容: ${targetUrl}, 类型: ${contentType}`);
+
+ // 设置原始响应头,但排除有问题的头和 CORS 头(已设置)
+ responseHeaders.forEach((value, key) => {
+ const lowerKey = key.toLowerCase();
+ if (!lowerKey.startsWith('access-control-') &&
+ lowerKey !== 'content-encoding' && // 很重要!
+ lowerKey !== 'content-length') { // 很重要!
+ res.setHeader(key, value); // 设置其他原始头
+ }
+ });
+ // 设置我们自己的缓存策略
+ res.setHeader('Cache-Control', `public, max-age=${CACHE_TTL}`);
+
+ // 发送原始(已解压)内容
+ res.status(200).send(content);
+ }
+
+ // ---- 结束主处理逻辑的 try 块 ----
+ } catch (error) { // ---- 捕获处理过程中的任何错误 ----
+ // **检查这个错误是否是 "Assignment to constant variable"**
+ console.error(`[代理错误处理 V3] 捕获错误!目标: ${targetUrl || '解析失败'} | 错误类型: ${error.constructor.name} | 错误消息: ${error.message}`);
+ console.error(`[代理错误堆栈 V3] ${error.stack}`); // 记录完整的错误堆栈信息
+
+ // 特别标记 "Assignment to constant variable" 错误
+ if (error instanceof TypeError && error.message.includes("Assignment to constant variable")) {
+ console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+ console.error("捕获到 'Assignment to constant variable' 错误!");
+ console.error("请再次检查函数代码及所有辅助函数中,是否有 const 声明的变量被重新赋值。");
+ console.error("错误堆栈指向:", error.stack);
+ console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+ }
+
+ // 尝试从错误对象获取状态码,否则默认为 500
+ const statusCode = error.status || 500;
+
+ // 确保在发送错误响应前没有发送过响应头
+ if (!res.headersSent) {
+ res.setHeader('Content-Type', 'application/json');
+ // CORS 头应该已经在前面设置好了
+ res.status(statusCode).json({
+ success: false,
+ error: `代理处理错误: ${error.message}`, // 返回错误消息给前端
+ targetUrl: targetUrl // 包含目标 URL 以便调试
+ });
+ } else {
+ // 如果响应头已发送,无法再发送 JSON 错误
+ console.error("[代理错误处理 V3] 响应头已发送,无法发送 JSON 错误响应。");
+ // 尝试结束响应
+ if (!res.writableEnded) {
+ res.end();
+ }
+ }
+ } finally {
+ // 记录请求处理结束
+ console.info('--- Vercel 代理请求结束 ---');
+ }
+}
+
+// --- [确保所有辅助函数定义都在这里] ---
+// getTargetUrlFromPath, getBaseUrl, resolveUrl, rewriteUrlToProxy, getRandomUserAgent,
+// fetchContentWithType, isM3u8Content, processKeyLine, processMapLine,
+// processMediaPlaylist, processM3u8Content, processMasterPlaylist
diff --git a/functions/proxy/[[path]].js b/functions/proxy/[[path]].js
new file mode 100644
index 0000000..bc4e886
--- /dev/null
+++ b/functions/proxy/[[path]].js
@@ -0,0 +1,519 @@
+// functions/proxy/[[path]].js
+
+// --- 配置 (现在从 Cloudflare 环境变量读取) ---
+// 在 Cloudflare Pages 设置 -> 函数 -> 环境变量绑定 中设置以下变量:
+// CACHE_TTL (例如 86400)
+// MAX_RECURSION (例如 5)
+// FILTER_DISCONTINUITY (不再需要,设为 false 或移除)
+// USER_AGENTS_JSON (例如 ["UA1", "UA2"]) - JSON 字符串数组
+// DEBUG (例如 false 或 true)
+// --- 配置结束 ---
+
+// --- 常量 (之前在 config.js 中,现在移到这里,因为它们与代理逻辑相关) ---
+const MEDIA_FILE_EXTENSIONS = [
+ '.mp4', '.webm', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.f4v', '.m4v', '.3gp', '.3g2', '.ts', '.mts', '.m2ts',
+ '.mp3', '.wav', '.ogg', '.aac', '.m4a', '.flac', '.wma', '.alac', '.aiff', '.opus',
+ '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.svg', '.avif', '.heic'
+];
+const MEDIA_CONTENT_TYPES = ['video/', 'audio/', 'image/'];
+// --- 常量结束 ---
+
+
+/**
+ * 主要的 Pages Function 处理函数
+ * 拦截发往 /proxy/* 的请求
+ */
+export async function onRequest(context) {
+ const { request, env, next, waitUntil } = context; // next 和 waitUntil 可能需要
+ const url = new URL(request.url);
+
+ // --- 从环境变量读取配置 ---
+ const DEBUG_ENABLED = (env.DEBUG === 'true');
+ const CACHE_TTL = parseInt(env.CACHE_TTL || '86400'); // 默认 24 小时
+ const MAX_RECURSION = parseInt(env.MAX_RECURSION || '5'); // 默认 5 层
+ // 广告过滤已移至播放器处理,代理不再执行
+ let USER_AGENTS = [ // 提供一个基础的默认值
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
+ ];
+ try {
+ // 尝试从环境变量解析 USER_AGENTS_JSON
+ const agentsJson = env.USER_AGENTS_JSON;
+ if (agentsJson) {
+ const parsedAgents = JSON.parse(agentsJson);
+ if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
+ USER_AGENTS = parsedAgents;
+ } else {
+ logDebug("环境变量 USER_AGENTS_JSON 格式无效或为空,使用默认值");
+ }
+ }
+ } catch (e) {
+ logDebug(`解析环境变量 USER_AGENTS_JSON 失败: ${e.message},使用默认值`);
+ }
+ // --- 配置读取结束 ---
+
+
+ // --- 辅助函数 ---
+
+ // 输出调试日志 (需要设置 DEBUG: true 环境变量)
+ function logDebug(message) {
+ if (DEBUG_ENABLED) {
+ console.log(`[Proxy Func] ${message}`);
+ }
+ }
+
+ // 从请求路径中提取目标 URL
+ function getTargetUrlFromPath(pathname) {
+ // 路径格式: /proxy/经过编码的URL
+ // 例如: /proxy/https%3A%2F%2Fexample.com%2Fplaylist.m3u8
+ const encodedUrl = pathname.replace(/^\/proxy\//, '');
+ if (!encodedUrl) return null;
+ try {
+ // 解码
+ let decodedUrl = decodeURIComponent(encodedUrl);
+
+ // 简单检查解码后是否是有效的 http/https URL
+ if (!decodedUrl.match(/^https?:\/\//i)) {
+ // 也许原始路径就没有编码?如果看起来像URL就直接用
+ if (encodedUrl.match(/^https?:\/\//i)) {
+ decodedUrl = encodedUrl;
+ logDebug(`Warning: Path was not encoded but looks like URL: ${decodedUrl}`);
+ } else {
+ logDebug(`无效的目标URL格式 (解码后): ${decodedUrl}`);
+ return null;
+ }
+ }
+ return decodedUrl;
+
+ } catch (e) {
+ logDebug(`解码目标URL时出错: ${encodedUrl} - ${e.message}`);
+ return null;
+ }
+ }
+
+ // 创建标准化的响应
+ function createResponse(body, status = 200, headers = {}) {
+ const responseHeaders = new Headers(headers);
+ // 关键:添加 CORS 跨域头,允许前端 JS 访问代理后的响应
+ responseHeaders.set("Access-Control-Allow-Origin", "*"); // 允许任何来源访问
+ responseHeaders.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); // 允许的方法
+ responseHeaders.set("Access-Control-Allow-Headers", "*"); // 允许所有请求头
+
+ // 处理 CORS 预检请求 (OPTIONS) - 放在这里确保所有响应都处理
+ if (request.method === "OPTIONS") {
+ // 使用下面的 onOptions 函数可以更规范,但在这里处理也可以
+ return new Response(null, {
+ status: 204, // No Content
+ headers: responseHeaders // 包含上面设置的 CORS 头
+ });
+ }
+
+ return new Response(body, { status, headers: responseHeaders });
+ }
+
+ // 创建 M3U8 类型的响应
+ function createM3u8Response(content) {
+ return createResponse(content, 200, {
+ "Content-Type": "application/vnd.apple.mpegurl", // M3U8 的标准 MIME 类型
+ "Cache-Control": `public, max-age=${CACHE_TTL}` // 允许浏览器和CDN缓存
+ });
+ }
+
+ // 获取随机 User-Agent
+ function getRandomUserAgent() {
+ return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
+ }
+
+ // 获取 URL 的基础路径 (用于解析相对路径)
+ function getBaseUrl(urlStr) {
+ try {
+ const parsedUrl = new URL(urlStr);
+ // 如果路径是根目录,或者没有斜杠,直接返回 origin + /
+ if (!parsedUrl.pathname || parsedUrl.pathname === '/') {
+ return `${parsedUrl.origin}/`;
+ }
+ const pathParts = parsedUrl.pathname.split('/');
+ pathParts.pop(); // 移除文件名或最后一个路径段
+ return `${parsedUrl.origin}${pathParts.join('/')}/`;
+ } catch (e) {
+ logDebug(`获取 BaseUrl 时出错: ${urlStr} - ${e.message}`);
+ // 备用方法:找到最后一个斜杠
+ const lastSlashIndex = urlStr.lastIndexOf('/');
+ // 确保不是协议部分的斜杠 (http://)
+ return lastSlashIndex > urlStr.indexOf('://') + 2 ? urlStr.substring(0, lastSlashIndex + 1) : urlStr + '/';
+ }
+ }
+
+
+ // 将相对 URL 转换为绝对 URL
+ function resolveUrl(baseUrl, relativeUrl) {
+ // 如果已经是绝对 URL,直接返回
+ if (relativeUrl.match(/^https?:\/\//i)) {
+ return relativeUrl;
+ }
+ try {
+ // 使用 URL 对象来处理相对路径
+ return new URL(relativeUrl, baseUrl).toString();
+ } catch (e) {
+ logDebug(`解析 URL 失败: baseUrl=${baseUrl}, relativeUrl=${relativeUrl}, error=${e.message}`);
+ // 简单的备用方法
+ if (relativeUrl.startsWith('/')) {
+ // 处理根路径相对 URL
+ const urlObj = new URL(baseUrl);
+ return `${urlObj.origin}${relativeUrl}`;
+ }
+ // 处理同级目录相对 URL
+ return `${baseUrl.replace(/\/[^/]*$/, '/')}${relativeUrl}`; // 确保baseUrl以 / 结尾
+ }
+ }
+
+ // 将目标 URL 重写为内部代理路径 (/proxy/...)
+ function rewriteUrlToProxy(targetUrl) {
+ // 确保目标URL被正确编码,以便作为路径的一部分
+ return `/proxy/${encodeURIComponent(targetUrl)}`;
+ }
+
+ // 获取远程内容及其类型
+ async function fetchContentWithType(targetUrl) {
+ const headers = new Headers({
+ 'User-Agent': getRandomUserAgent(),
+ 'Accept': '*/*',
+ // 尝试传递一些原始请求的头信息
+ 'Accept-Language': request.headers.get('Accept-Language') || 'zh-CN,zh;q=0.9,en;q=0.8',
+ // 尝试设置 Referer 为目标网站的域名,或者传递原始 Referer
+ 'Referer': request.headers.get('Referer') || new URL(targetUrl).origin
+ });
+
+ try {
+ // 直接请求目标 URL
+ logDebug(`开始直接请求: ${targetUrl}`);
+ // Cloudflare Functions 的 fetch 默认支持重定向
+ const response = await fetch(targetUrl, { headers, redirect: 'follow' });
+
+ if (!response.ok) {
+ const errorBody = await response.text().catch(() => '');
+ logDebug(`请求失败: ${response.status} ${response.statusText} - ${targetUrl}`);
+ throw new Error(`HTTP error ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 150)}`);
+ }
+
+ // 读取响应内容为文本
+ const content = await response.text();
+ const contentType = response.headers.get('Content-Type') || '';
+ logDebug(`请求成功: ${targetUrl}, Content-Type: ${contentType}, 内容长度: ${content.length}`);
+ return { content, contentType, responseHeaders: response.headers }; // 同时返回原始响应头
+
+ } catch (error) {
+ logDebug(`请求彻底失败: ${targetUrl}: ${error.message}`);
+ // 抛出更详细的错误
+ throw new Error(`请求目标URL失败 ${targetUrl}: ${error.message}`);
+ }
+ }
+
+ // 判断是否是 M3U8 内容
+ function isM3u8Content(content, contentType) {
+ // 检查 Content-Type
+ if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) {
+ return true;
+ }
+ // 检查内容本身是否以 #EXTM3U 开头
+ return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
+ }
+
+ // 判断是否是媒体文件 (根据扩展名和 Content-Type) - 这部分在此代理中似乎未使用,但保留
+ function isMediaFile(url, contentType) {
+ if (contentType) {
+ for (const mediaType of MEDIA_CONTENT_TYPES) {
+ if (contentType.toLowerCase().startsWith(mediaType)) {
+ return true;
+ }
+ }
+ }
+ const urlLower = url.toLowerCase();
+ for (const ext of MEDIA_FILE_EXTENSIONS) {
+ if (urlLower.endsWith(ext) || urlLower.includes(`${ext}?`)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // 处理 M3U8 中的 #EXT-X-KEY 行 (加密密钥)
+ function processKeyLine(line, baseUrl) {
+ return line.replace(/URI="([^"]+)"/, (match, uri) => {
+ const absoluteUri = resolveUrl(baseUrl, uri);
+ logDebug(`处理 KEY URI: 原始='${uri}', 绝对='${absoluteUri}'`);
+ return `URI="${rewriteUrlToProxy(absoluteUri)}"`; // 重写为代理路径
+ });
+ }
+
+ // 处理 M3U8 中的 #EXT-X-MAP 行 (初始化片段)
+ function processMapLine(line, baseUrl) {
+ return line.replace(/URI="([^"]+)"/, (match, uri) => {
+ const absoluteUri = resolveUrl(baseUrl, uri);
+ logDebug(`处理 MAP URI: 原始='${uri}', 绝对='${absoluteUri}'`);
+ return `URI="${rewriteUrlToProxy(absoluteUri)}"`; // 重写为代理路径
+ });
+ }
+
+ // 处理媒体 M3U8 播放列表 (包含视频/音频片段)
+ function processMediaPlaylist(url, content) {
+ const baseUrl = getBaseUrl(url);
+ const lines = content.split('\n');
+ const output = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ // 保留最后的空行
+ if (!line && i === lines.length - 1) {
+ output.push(line);
+ continue;
+ }
+ if (!line) continue; // 跳过中间的空行
+
+ if (line.startsWith('#EXT-X-KEY')) {
+ output.push(processKeyLine(line, baseUrl));
+ continue;
+ }
+ if (line.startsWith('#EXT-X-MAP')) {
+ output.push(processMapLine(line, baseUrl));
+ continue;
+ }
+ if (line.startsWith('#EXTINF')) {
+ output.push(line);
+ continue;
+ }
+ if (!line.startsWith('#')) {
+ const absoluteUrl = resolveUrl(baseUrl, line);
+ logDebug(`重写媒体片段: 原始='${line}', 绝对='${absoluteUrl}'`);
+ output.push(rewriteUrlToProxy(absoluteUrl));
+ continue;
+ }
+ // 其他 M3U8 标签直接添加
+ output.push(line);
+ }
+ return output.join('\n');
+ }
+
+ // 递归处理 M3U8 内容
+ async function processM3u8Content(targetUrl, content, recursionDepth = 0, env) {
+ if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) {
+ logDebug(`检测到主播放列表: ${targetUrl}`);
+ return await processMasterPlaylist(targetUrl, content, recursionDepth, env);
+ }
+ logDebug(`检测到媒体播放列表: ${targetUrl}`);
+ return processMediaPlaylist(targetUrl, content);
+ }
+
+ // 处理主 M3U8 播放列表
+ async function processMasterPlaylist(url, content, recursionDepth, env) {
+ if (recursionDepth > MAX_RECURSION) {
+ throw new Error(`处理主列表时递归层数过多 (${MAX_RECURSION}): ${url}`);
+ }
+
+ const baseUrl = getBaseUrl(url);
+ const lines = content.split('\n');
+ let highestBandwidth = -1;
+ let bestVariantUrl = '';
+
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].startsWith('#EXT-X-STREAM-INF')) {
+ const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/);
+ const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0;
+
+ let variantUriLine = '';
+ for (let j = i + 1; j < lines.length; j++) {
+ const line = lines[j].trim();
+ if (line && !line.startsWith('#')) {
+ variantUriLine = line;
+ i = j;
+ break;
+ }
+ }
+
+ if (variantUriLine && currentBandwidth >= highestBandwidth) {
+ highestBandwidth = currentBandwidth;
+ bestVariantUrl = resolveUrl(baseUrl, variantUriLine);
+ }
+ }
+ }
+
+ if (!bestVariantUrl) {
+ logDebug(`主列表中未找到 BANDWIDTH 或 STREAM-INF,尝试查找第一个子列表引用: ${url}`);
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (line && !line.startsWith('#') && (line.endsWith('.m3u8') || line.includes('.m3u8?'))) { // 修复:检查是否包含 .m3u8?
+ bestVariantUrl = resolveUrl(baseUrl, line);
+ logDebug(`备选方案:找到第一个子列表引用: ${bestVariantUrl}`);
+ break;
+ }
+ }
+ }
+
+ if (!bestVariantUrl) {
+ logDebug(`在主列表 ${url} 中未找到任何有效的子播放列表 URL。可能格式有问题或仅包含音频/字幕。将尝试按媒体列表处理原始内容。`);
+ return processMediaPlaylist(url, content);
+ }
+
+ // --- 获取并处理选中的子 M3U8 ---
+
+ const cacheKey = `m3u8_processed:${bestVariantUrl}`; // 使用处理后的缓存键
+
+ let kvNamespace = null;
+ try {
+ kvNamespace = env.LIBRETV_PROXY_KV; // 从环境获取 KV 命名空间 (变量名在 Cloudflare 设置)
+ if (!kvNamespace) throw new Error("KV 命名空间未绑定");
+ } catch (e) {
+ logDebug(`KV 命名空间 'LIBRETV_PROXY_KV' 访问出错或未绑定: ${e.message}`);
+ kvNamespace = null; // 确保设为 null
+ }
+
+ if (kvNamespace) {
+ try {
+ const cachedContent = await kvNamespace.get(cacheKey);
+ if (cachedContent) {
+ logDebug(`[缓存命中] 主列表的子列表: ${bestVariantUrl}`);
+ return cachedContent;
+ } else {
+ logDebug(`[缓存未命中] 主列表的子列表: ${bestVariantUrl}`);
+ }
+ } catch (kvError) {
+ logDebug(`从 KV 读取缓存失败 (${cacheKey}): ${kvError.message}`);
+ // 出错则继续执行,不影响功能
+ }
+ }
+
+ logDebug(`选择的子列表 (带宽: ${highestBandwidth}): ${bestVariantUrl}`);
+ const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl);
+
+ if (!isM3u8Content(variantContent, variantContentType)) {
+ logDebug(`获取到的子列表 ${bestVariantUrl} 不是 M3U8 内容 (类型: ${variantContentType})。可能直接是媒体文件,返回原始内容。`);
+ // 如果不是M3U8,但看起来像媒体内容,直接返回代理后的内容
+ // 注意:这里可能需要决定是否直接代理这个非 M3U8 的 URL
+ // 为了简化,我们假设如果不是 M3U8,则流程中断或按原样处理
+ // 或者,尝试将其作为媒体列表处理?(当前行为)
+ // return createResponse(variantContent, 200, { 'Content-Type': variantContentType || 'application/octet-stream' });
+ // 尝试按媒体列表处理,以防万一
+ return processMediaPlaylist(bestVariantUrl, variantContent);
+
+ }
+
+ const processedVariant = await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1, env);
+
+ if (kvNamespace) {
+ try {
+ // 使用 waitUntil 异步写入缓存,不阻塞响应返回
+ // 注意 KV 的写入限制 (免费版每天 1000 次)
+ waitUntil(kvNamespace.put(cacheKey, processedVariant, { expirationTtl: CACHE_TTL }));
+ logDebug(`已将处理后的子列表写入缓存: ${bestVariantUrl}`);
+ } catch (kvError) {
+ logDebug(`向 KV 写入缓存失败 (${cacheKey}): ${kvError.message}`);
+ // 写入失败不影响返回结果
+ }
+ }
+
+ return processedVariant;
+ }
+
+ // --- 主要请求处理逻辑 ---
+
+ try {
+ const targetUrl = getTargetUrlFromPath(url.pathname);
+
+ if (!targetUrl) {
+ logDebug(`无效的代理请求路径: ${url.pathname}`);
+ return createResponse("无效的代理请求。路径应为 /proxy/<经过编码的URL>", 400);
+ }
+
+ logDebug(`收到代理请求: ${targetUrl}`);
+
+ // --- 缓存检查 (KV) ---
+ const cacheKey = `proxy_raw:${targetUrl}`; // 使用原始内容的缓存键
+ let kvNamespace = null;
+ try {
+ kvNamespace = env.LIBRETV_PROXY_KV;
+ if (!kvNamespace) throw new Error("KV 命名空间未绑定");
+ } catch (e) {
+ logDebug(`KV 命名空间 'LIBRETV_PROXY_KV' 访问出错或未绑定: ${e.message}`);
+ kvNamespace = null;
+ }
+
+ if (kvNamespace) {
+ try {
+ const cachedDataJson = await kvNamespace.get(cacheKey); // 直接获取字符串
+ if (cachedDataJson) {
+ logDebug(`[缓存命中] 原始内容: ${targetUrl}`);
+ const cachedData = JSON.parse(cachedDataJson); // 解析 JSON
+ const content = cachedData.body;
+ let headers = {};
+ try { headers = JSON.parse(cachedData.headers); } catch(e){} // 解析头部
+ const contentType = headers['content-type'] || headers['Content-Type'] || '';
+
+ if (isM3u8Content(content, contentType)) {
+ logDebug(`缓存内容是 M3U8,重新处理: ${targetUrl}`);
+ const processedM3u8 = await processM3u8Content(targetUrl, content, 0, env);
+ return createM3u8Response(processedM3u8);
+ } else {
+ logDebug(`从缓存返回非 M3U8 内容: ${targetUrl}`);
+ return createResponse(content, 200, new Headers(headers));
+ }
+ } else {
+ logDebug(`[缓存未命中] 原始内容: ${targetUrl}`);
+ }
+ } catch (kvError) {
+ logDebug(`从 KV 读取或解析缓存失败 (${cacheKey}): ${kvError.message}`);
+ // 出错则继续执行,不影响功能
+ }
+ }
+
+ // --- 实际请求 ---
+ const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl);
+
+ // --- 写入缓存 (KV) ---
+ if (kvNamespace) {
+ try {
+ const headersToCache = {};
+ responseHeaders.forEach((value, key) => { headersToCache[key.toLowerCase()] = value; });
+ const cacheValue = { body: content, headers: JSON.stringify(headersToCache) };
+ // 注意 KV 写入限制
+ waitUntil(kvNamespace.put(cacheKey, JSON.stringify(cacheValue), { expirationTtl: CACHE_TTL }));
+ logDebug(`已将原始内容写入缓存: ${targetUrl}`);
+ } catch (kvError) {
+ logDebug(`向 KV 写入缓存失败 (${cacheKey}): ${kvError.message}`);
+ // 写入失败不影响返回结果
+ }
+ }
+
+ // --- 处理响应 ---
+ if (isM3u8Content(content, contentType)) {
+ logDebug(`内容是 M3U8,开始处理: ${targetUrl}`);
+ const processedM3u8 = await processM3u8Content(targetUrl, content, 0, env);
+ return createM3u8Response(processedM3u8);
+ } else {
+ logDebug(`内容不是 M3U8 (类型: ${contentType}),直接返回: ${targetUrl}`);
+ const finalHeaders = new Headers(responseHeaders);
+ finalHeaders.set('Cache-Control', `public, max-age=${CACHE_TTL}`);
+ // 添加 CORS 头,确保非 M3U8 内容也能跨域访问(例如图片、字幕文件等)
+ finalHeaders.set("Access-Control-Allow-Origin", "*");
+ finalHeaders.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS");
+ finalHeaders.set("Access-Control-Allow-Headers", "*");
+ return createResponse(content, 200, finalHeaders);
+ }
+
+ } catch (error) {
+ logDebug(`处理代理请求时发生严重错误: ${error.message} \n ${error.stack}`);
+ return createResponse(`代理处理错误: ${error.message}`, 500);
+ }
+}
+
+// 处理 OPTIONS 预检请求的函数
+export async function onOptions(context) {
+ // 直接返回允许跨域的头信息
+ return new Response(null, {
+ status: 204, // No Content
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "*", // 允许所有请求头
+ "Access-Control-Max-Age": "86400", // 预检请求结果缓存一天
+ },
+ });
+}
diff --git a/netlify.toml b/netlify.toml
new file mode 100644
index 0000000..4085f26
--- /dev/null
+++ b/netlify.toml
@@ -0,0 +1,19 @@
+# netlify.toml
+
+[build]
+ # 如果你的项目不需要构建步骤 (纯静态 + functions),可以省略 publish
+ # publish = "." # 假设你的 HTML/CSS/JS 文件在根目录
+ functions = "netlify/functions" # 指定 Netlify 函数目录
+
+# 配置重写规则,将 /proxy/* 的请求路由到 proxy 函数
+# 这样前端的 PROXY_URL 仍然可以是 '/proxy/'
+[[redirects]]
+ from = "/proxy/*"
+ to = "/.netlify/functions/proxy/:splat" # 将路径参数传递给函数
+ status = 200 # 重要:这是代理,不是重定向
+
+# (可选)为其他静态文件设置缓存头等
+# [[headers]]
+# for = "/*"
+# [headers.values]
+# # Add any global headers here
diff --git a/netlify/functions/proxy.mjs b/netlify/functions/proxy.mjs
new file mode 100644
index 0000000..6d1e146
--- /dev/null
+++ b/netlify/functions/proxy.mjs
@@ -0,0 +1,274 @@
+// /netlify/functions/proxy.mjs - Netlify Function (ES Module)
+
+import fetch from 'node-fetch';
+import { URL } from 'url'; // Use Node.js built-in URL
+
+// --- Configuration (Read from Environment Variables) ---
+const DEBUG_ENABLED = process.env.DEBUG === 'true';
+const CACHE_TTL = parseInt(process.env.CACHE_TTL || '86400', 10); // Default 24 hours
+const MAX_RECURSION = parseInt(process.env.MAX_RECURSION || '5', 10); // Default 5 levels
+
+// --- User Agent Handling ---
+let USER_AGENTS = [
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
+];
+try {
+ const agentsJsonString = process.env.USER_AGENTS_JSON;
+ if (agentsJsonString) {
+ const parsedAgents = JSON.parse(agentsJsonString);
+ if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
+ USER_AGENTS = parsedAgents;
+ console.log(`[Proxy Log Netlify] Loaded ${USER_AGENTS.length} user agents from environment variable.`);
+ } else {
+ console.warn("[Proxy Log Netlify] USER_AGENTS_JSON environment variable is not a valid non-empty array, using default.");
+ }
+ } else {
+ console.log("[Proxy Log Netlify] USER_AGENTS_JSON environment variable not set, using default user agents.");
+ }
+} catch (e) {
+ console.error(`[Proxy Log Netlify] Error parsing USER_AGENTS_JSON environment variable: ${e.message}. Using default user agents.`);
+}
+const FILTER_DISCONTINUITY = false; // Ad filtering disabled
+
+// --- Helper Functions (Same as Vercel version, except rewriteUrlToProxy) ---
+
+function logDebug(message) {
+ if (DEBUG_ENABLED) {
+ console.log(`[Proxy Log Netlify] ${message}`);
+ }
+}
+
+function getTargetUrlFromPath(encodedPath) {
+ if (!encodedPath) { logDebug("getTargetUrlFromPath received empty path."); return null; }
+ try {
+ const decodedUrl = decodeURIComponent(encodedPath);
+ if (decodedUrl.match(/^https?:\/\/.+/i)) { return decodedUrl; }
+ else {
+ logDebug(`Invalid decoded URL format: ${decodedUrl}`);
+ if (encodedPath.match(/^https?:\/\/.+/i)) { logDebug(`Warning: Path was not encoded but looks like URL: ${encodedPath}`); return encodedPath; }
+ return null;
+ }
+ } catch (e) { logDebug(`Error decoding target URL: ${encodedPath} - ${e.message}`); return null; }
+}
+
+function getBaseUrl(urlStr) {
+ if (!urlStr) return '';
+ try {
+ const parsedUrl = new URL(urlStr);
+ const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
+ if (pathSegments.length <= 1) { return `${parsedUrl.origin}/`; }
+ pathSegments.pop(); return `${parsedUrl.origin}/${pathSegments.join('/')}/`;
+ } catch (e) {
+ logDebug(`Getting BaseUrl failed for "${urlStr}": ${e.message}`);
+ const lastSlashIndex = urlStr.lastIndexOf('/');
+ if (lastSlashIndex > urlStr.indexOf('://') + 2) { return urlStr.substring(0, lastSlashIndex + 1); }
+ return urlStr + '/';
+ }
+}
+
+function resolveUrl(baseUrl, relativeUrl) {
+ if (!relativeUrl) return ''; if (relativeUrl.match(/^https?:\/\/.+/i)) { return relativeUrl; } if (!baseUrl) return relativeUrl;
+ try { return new URL(relativeUrl, baseUrl).toString(); }
+ catch (e) {
+ logDebug(`URL resolution failed: base="${baseUrl}", relative="${relativeUrl}". Error: ${e.message}`);
+ if (relativeUrl.startsWith('/')) { try { const baseOrigin = new URL(baseUrl).origin; return `${baseOrigin}${relativeUrl}`; } catch { return relativeUrl; } }
+ else { return `${baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1)}${relativeUrl}`; }
+ }
+}
+
+// ** MODIFIED for Netlify redirect **
+function rewriteUrlToProxy(targetUrl) {
+ if (!targetUrl || typeof targetUrl !== 'string') return '';
+ // Use the path defined in netlify.toml 'from' field
+ return `/proxy/${encodeURIComponent(targetUrl)}`;
+}
+
+function getRandomUserAgent() { return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)]; }
+
+async function fetchContentWithType(targetUrl, requestHeaders) {
+ const headers = {
+ 'User-Agent': getRandomUserAgent(),
+ 'Accept': requestHeaders['accept'] || '*/*',
+ 'Accept-Language': requestHeaders['accept-language'] || 'zh-CN,zh;q=0.9,en;q=0.8',
+ 'Referer': requestHeaders['referer'] || new URL(targetUrl).origin,
+ };
+ Object.keys(headers).forEach(key => headers[key] === undefined || headers[key] === null || headers[key] === '' ? delete headers[key] : {});
+ logDebug(`Fetching target: ${targetUrl} with headers: ${JSON.stringify(headers)}`);
+ try {
+ const response = await fetch(targetUrl, { headers, redirect: 'follow' });
+ if (!response.ok) {
+ const errorBody = await response.text().catch(() => '');
+ logDebug(`Fetch failed: ${response.status} ${response.statusText} - ${targetUrl}`);
+ const err = new Error(`HTTP error ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 200)}`);
+ err.status = response.status; throw err;
+ }
+ const content = await response.text();
+ const contentType = response.headers.get('content-type') || '';
+ logDebug(`Fetch success: ${targetUrl}, Content-Type: ${contentType}, Length: ${content.length}`);
+ return { content, contentType, responseHeaders: response.headers };
+ } catch (error) {
+ logDebug(`Fetch exception for ${targetUrl}: ${error.message}`);
+ throw new Error(`Failed to fetch target URL ${targetUrl}: ${error.message}`);
+ }
+}
+
+function isM3u8Content(content, contentType) {
+ if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) { return true; }
+ return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
+}
+
+function processKeyLine(line, baseUrl) { return line.replace(/URI="([^"]+)"/, (match, uri) => { const absoluteUri = resolveUrl(baseUrl, uri); logDebug(`Processing KEY URI: Original='${uri}', Absolute='${absoluteUri}'`); return `URI="${rewriteUrlToProxy(absoluteUri)}"`; }); }
+function processMapLine(line, baseUrl) { return line.replace(/URI="([^"]+)"/, (match, uri) => { const absoluteUri = resolveUrl(baseUrl, uri); logDebug(`Processing MAP URI: Original='${uri}', Absolute='${absoluteUri}'`); return `URI="${rewriteUrlToProxy(absoluteUri)}"`; }); }
+function processMediaPlaylist(url, content) {
+ const baseUrl = getBaseUrl(url); if (!baseUrl) { logDebug(`Could not determine base URL for media playlist: ${url}. Cannot process relative paths.`); }
+ const lines = content.split('\n'); const output = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim(); if (!line && i === lines.length - 1) { output.push(line); continue; } if (!line) continue;
+ if (line.startsWith('#EXT-X-KEY')) { output.push(processKeyLine(line, baseUrl)); continue; }
+ if (line.startsWith('#EXT-X-MAP')) { output.push(processMapLine(line, baseUrl)); continue; }
+ if (line.startsWith('#EXTINF')) { output.push(line); continue; }
+ if (!line.startsWith('#')) { const absoluteUrl = resolveUrl(baseUrl, line); logDebug(`Rewriting media segment: Original='${line}', Resolved='${absoluteUrl}'`); output.push(rewriteUrlToProxy(absoluteUrl)); continue; }
+ output.push(line);
+ } return output.join('\n');
+}
+async function processM3u8Content(targetUrl, content, recursionDepth = 0) {
+ if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) { logDebug(`Detected master playlist: ${targetUrl} (Depth: ${recursionDepth})`); return await processMasterPlaylist(targetUrl, content, recursionDepth); }
+ logDebug(`Detected media playlist: ${targetUrl} (Depth: ${recursionDepth})`); return processMediaPlaylist(targetUrl, content);
+}
+async function processMasterPlaylist(url, content, recursionDepth) {
+ if (recursionDepth > MAX_RECURSION) { throw new Error(`Max recursion depth (${MAX_RECURSION}) exceeded for master playlist: ${url}`); }
+ const baseUrl = getBaseUrl(url); const lines = content.split('\n'); let highestBandwidth = -1; let bestVariantUrl = '';
+ for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith('#EXT-X-STREAM-INF')) { const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/); const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0; let variantUriLine = ''; for (let j = i + 1; j < lines.length; j++) { const line = lines[j].trim(); if (line && !line.startsWith('#')) { variantUriLine = line; i = j; break; } } if (variantUriLine && currentBandwidth >= highestBandwidth) { highestBandwidth = currentBandwidth; bestVariantUrl = resolveUrl(baseUrl, variantUriLine); } } }
+ if (!bestVariantUrl) { logDebug(`No BANDWIDTH found, trying first URI in: ${url}`); for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line && !line.startsWith('#') && line.match(/\.m3u8($|\?.*)/i)) { bestVariantUrl = resolveUrl(baseUrl, line); logDebug(`Fallback: Found first sub-playlist URI: ${bestVariantUrl}`); break; } } }
+ if (!bestVariantUrl) { logDebug(`No valid sub-playlist URI found in master: ${url}. Processing as media playlist.`); return processMediaPlaylist(url, content); }
+ logDebug(`Selected sub-playlist (Bandwidth: ${highestBandwidth}): ${bestVariantUrl}`);
+ const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl, {});
+ if (!isM3u8Content(variantContent, variantContentType)) { logDebug(`Fetched sub-playlist ${bestVariantUrl} is not M3U8 (Type: ${variantContentType}). Treating as media playlist.`); return processMediaPlaylist(bestVariantUrl, variantContent); }
+ return await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1);
+}
+
+
+// --- Netlify Handler ---
+export const handler = async (event, context) => {
+ console.log('--- Netlify Proxy Request ---');
+ console.log('Time:', new Date().toISOString());
+ console.log('Method:', event.httpMethod);
+ console.log('Path:', event.path);
+ // Note: event.queryStringParameters contains query params if any
+ // Note: event.headers contains incoming headers
+
+ // --- CORS Headers (for all responses) ---
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
+ 'Access-Control-Allow-Headers': '*', // Allow all headers client might send
+ };
+
+ // --- Handle OPTIONS Preflight Request ---
+ if (event.httpMethod === 'OPTIONS') {
+ logDebug("Handling OPTIONS request");
+ return {
+ statusCode: 204,
+ headers: {
+ ...corsHeaders,
+ 'Access-Control-Max-Age': '86400', // Cache preflight for 24 hours
+ },
+ body: '',
+ };
+ }
+
+ // --- Extract Target URL ---
+ // Based on netlify.toml rewrite: from = "/proxy/*" to = "/.netlify/functions/proxy/:splat"
+ // The :splat part should be available in event.path after the base path
+ let encodedUrlPath = '';
+ const proxyPrefix = '/proxy/'; // Match the 'from' path in netlify.toml
+ if (event.path && event.path.startsWith(proxyPrefix)) {
+ encodedUrlPath = event.path.substring(proxyPrefix.length);
+ logDebug(`Extracted encoded path from event.path: ${encodedUrlPath}`);
+ } else {
+ logDebug(`Could not extract encoded path from event.path: ${event.path}`);
+ // Potentially handle direct calls too? Less likely needed.
+ // const functionPath = '/.netlify/functions/proxy/';
+ // if (event.path && event.path.startsWith(functionPath)) {
+ // encodedUrlPath = event.path.substring(functionPath.length);
+ // }
+ }
+
+ const targetUrl = getTargetUrlFromPath(encodedUrlPath);
+ logDebug(`Resolved target URL: ${targetUrl || 'null'}`);
+
+ if (!targetUrl) {
+ logDebug('Error: Invalid proxy request path.');
+ return {
+ statusCode: 400,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ success: false, error: "Invalid proxy request path. Could not extract target URL." }),
+ };
+ }
+
+ logDebug(`Processing proxy request for target: ${targetUrl}`);
+
+ try {
+ // Fetch Original Content (Pass Netlify event headers)
+ const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl, event.headers);
+
+ // --- Process if M3U8 ---
+ if (isM3u8Content(content, contentType)) {
+ logDebug(`Processing M3U8 content: ${targetUrl}`);
+ const processedM3u8 = await processM3u8Content(targetUrl, content);
+
+ logDebug(`Successfully processed M3U8 for ${targetUrl}`);
+ return {
+ statusCode: 200,
+ headers: {
+ ...corsHeaders, // Include CORS headers
+ 'Content-Type': 'application/vnd.apple.mpegurl;charset=utf-8',
+ 'Cache-Control': `public, max-age=${CACHE_TTL}`,
+ // Note: Do NOT include content-encoding or content-length from original response
+ // as node-fetch likely decompressed it and length changed.
+ },
+ body: processedM3u8, // Netlify expects body as string
+ };
+ } else {
+ // --- Return Original Content (Non-M3U8) ---
+ logDebug(`Returning non-M3U8 content directly: ${targetUrl}, Type: ${contentType}`);
+
+ // Prepare headers for Netlify response object
+ const netlifyHeaders = { ...corsHeaders };
+ responseHeaders.forEach((value, key) => {
+ const lowerKey = key.toLowerCase();
+ // Exclude problematic headers and CORS headers (already added)
+ if (!lowerKey.startsWith('access-control-') &&
+ lowerKey !== 'content-encoding' &&
+ lowerKey !== 'content-length') {
+ netlifyHeaders[key] = value; // Add other original headers
+ }
+ });
+ netlifyHeaders['Cache-Control'] = `public, max-age=${CACHE_TTL}`; // Set our cache policy
+
+ return {
+ statusCode: 200,
+ headers: netlifyHeaders,
+ body: content, // Body as string
+ // isBase64Encoded: false, // Set true only if returning binary data as base64
+ };
+ }
+
+ } catch (error) {
+ logDebug(`ERROR in proxy processing for ${targetUrl}: ${error.message}`);
+ console.error(`[Proxy Error Stack Netlify] ${error.stack}`); // Log full stack
+
+ const statusCode = error.status || 500; // Get status from error if available
+
+ return {
+ statusCode: statusCode,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ success: false,
+ error: `Proxy processing error: ${error.message}`,
+ targetUrl: targetUrl
+ }),
+ };
+ }
+};
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..11383d1
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,106 @@
+{
+ "name": "libretv",
+ "version": "1.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "libretv",
+ "version": "1.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "node-fetch": "^3.3.2"
+ }
+ },
+ "node_modules/data-uri-to-buffer": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/fetch-blob": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
+ "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "node-domexception": "^1.0.0",
+ "web-streams-polyfill": "^3.0.3"
+ },
+ "engines": {
+ "node": "^12.20 || >= 14.13"
+ }
+ },
+ "node_modules/formdata-polyfill": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
+ "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
+ "license": "MIT",
+ "dependencies": {
+ "fetch-blob": "^3.1.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/node-domexception": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "github",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.5.0"
+ }
+ },
+ "node_modules/node-fetch": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
+ "license": "MIT",
+ "dependencies": {
+ "data-uri-to-buffer": "^4.0.0",
+ "fetch-blob": "^3.1.4",
+ "formdata-polyfill": "^4.0.10"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/node-fetch"
+ }
+ },
+ "node_modules/web-streams-polyfill": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..1cb6cf7
--- /dev/null
+++ b/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "libretv",
+ "version": "1.1.0",
+ "description": "免费在线视频搜索与观看平台",
+ "private": true,
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "dependencies": {
+ "node-fetch": "^3.3.2"
+ },
+ "author": "bestZwei",
+ "license": "MIT"
+}
\ No newline at end of file
diff --git a/vercel.json b/vercel.json
new file mode 100644
index 0000000..2337aa2
--- /dev/null
+++ b/vercel.json
@@ -0,0 +1,8 @@
+{
+ "rewrites": [
+ {
+ "source": "/proxy/:path*",
+ "destination": "/api/proxy/:path*"
+ }
+ ]
+}