diff --git a/src/routes/m3u8-proxy.ts b/src/routes/m3u8-proxy.ts index 9a0233d..3a7fb0b 100644 --- a/src/routes/m3u8-proxy.ts +++ b/src/routes/m3u8-proxy.ts @@ -4,6 +4,9 @@ */ import { setResponseHeaders } from 'h3'; +import { IncomingMessage } from 'http'; +import https from 'node:https'; +import http from 'node:http'; // Helper function to parse URLs function parseURL(req_url: string, baseUrl?: string) { @@ -42,6 +45,56 @@ function parseURL(req_url: string, baseUrl?: string) { } } +// Helper function to perform HTTP/HTTPS request +function makeRequest(url: string, headers: any): Promise<{ data: string, statusCode: number }> { + return new Promise((resolve, reject) => { + const parsed = new URL(url); + const isHttps = parsed.protocol === 'https:'; + const options = { + hostname: parsed.hostname, + port: parsed.port || (isHttps ? 443 : 80), + path: parsed.pathname + parsed.search, + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + ...headers + } + }; + + console.log('Making request to:', url); + console.log('With headers:', JSON.stringify(options.headers)); + + const requestLib = isHttps ? https : http; + const req = requestLib.request(options, (res: IncomingMessage) => { + console.log('Status code:', res.statusCode); + console.log('Response headers:', JSON.stringify(res.headers)); + + let data = ''; + + res.on('data', (chunk) => { + data += chunk; + }); + + res.on('end', () => { + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { + resolve({ data, statusCode: res.statusCode }); + } else { + reject(new Error(`HTTP Error: ${res.statusCode} ${res.statusMessage}`)); + } + }); + }); + + req.on('error', (error) => { + console.error('Request error:', error); + reject(error); + }); + + req.end(); + }); +} + /** * Proxies m3u8 files and replaces the content to point to the proxy */ @@ -60,23 +113,20 @@ async function proxyM3U8(event: any) { try { headers = headersParam ? JSON.parse(headersParam) : {}; } catch (e) { + console.error('Error parsing headers JSON:', e, 'Raw headers:', headersParam); return sendError(event, createError({ statusCode: 400, statusMessage: 'Invalid headers format' })); } + + console.log('Processing m3u8 request for URL:', url); + console.log('With headers:', JSON.stringify(headers)); try { - // Use native fetch instead of axios - const response = await fetch(url, { - headers: headers as HeadersInit - }); - - if (!response.ok) { - throw new Error(`Failed to fetch M3U8: ${response.status} ${response.statusText}`); - } - - const m3u8Content = await response.text(); + // Use Node's http/https modules instead of fetch + const response = await makeRequest(url, headers); + const m3u8Content = response.data; // Get the base URL for the host const host = getRequestHost(event); diff --git a/src/routes/ts-proxy.ts b/src/routes/ts-proxy.ts index bbe4e0b..abd4039 100644 --- a/src/routes/ts-proxy.ts +++ b/src/routes/ts-proxy.ts @@ -4,6 +4,9 @@ */ import { setResponseHeaders } from 'h3'; +import https from 'node:https'; +import http from 'node:http'; +import { IncomingMessage } from 'http'; /** * Proxies TS (transport stream) files @@ -26,26 +29,21 @@ export default defineEventHandler(async (event) => { try { headers = headersParam ? JSON.parse(headersParam) : {}; } catch (e) { + console.error('Error parsing headers JSON:', e, 'Raw headers:', headersParam); return sendError(event, createError({ statusCode: 400, statusMessage: 'Invalid headers format' })); } + + console.log('Processing TS request for URL:', url); + console.log('With headers:', JSON.stringify(headers)); try { - const response = await fetch(url, { - method: 'GET', - headers: { - ...headers as HeadersInit, - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', - } - }); + const parsed = new URL(url); + const isHttps = parsed.protocol === 'https:'; - if (!response.ok) { - throw new Error(`Failed to fetch TS file: ${response.status} ${response.statusText}`); - } - - // Set appropriate headers for each video segment + // Set appropriate headers for video content first, before starting the stream setResponseHeaders(event, { 'Content-Type': 'video/mp2t', 'Access-Control-Allow-Origin': '*', @@ -54,8 +52,54 @@ export default defineEventHandler(async (event) => { 'Cache-Control': 'public, max-age=3600' // Allow caching of TS segments }); - // Return the binary data directly - Nitro should handle this properly - return new Uint8Array(await response.arrayBuffer()); + // Create a promise that will download and stream the TS file + return await new Promise((resolve, reject) => { + const options = { + hostname: parsed.hostname, + port: parsed.port || (isHttps ? 443 : 80), + path: parsed.pathname + parsed.search, + method: 'GET', + headers: { + 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', + 'Accept': '*/*', + 'Accept-Language': 'en-US,en;q=0.9', + ...headers + } + }; + + console.log('Making TS request to:', url); + console.log('With headers:', JSON.stringify(options.headers)); + + const requestLib = isHttps ? https : http; + const req = requestLib.request(options, (res: IncomingMessage) => { + if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) { + reject(new Error(`HTTP Error: ${res.statusCode} ${res.statusMessage}`)); + return; + } + + console.log('TS response status:', res.statusCode); + + // Create an array to collect chunks + const chunks: Buffer[] = []; + + res.on('data', (chunk) => { + chunks.push(Buffer.from(chunk)); + }); + + res.on('end', () => { + // Combine all chunks into a single buffer + const buffer = Buffer.concat(chunks); + resolve(buffer); + }); + }); + + req.on('error', (error) => { + console.error('TS request error:', error); + reject(error); + }); + + req.end(); + }); } catch (error: any) { console.error('Error proxying TS file:', error); return sendError(event, createError({