48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
import { FastifyInstance, FastifyReply } from 'fastify';
|
|
import { proxyRequest, processM3U8Content, streamToReadable } from './proxy.service';
|
|
import { ProxyRequest } from '../../types';
|
|
|
|
async function proxyRoutes(fastify: FastifyInstance) {
|
|
fastify.get('/proxy', async (req: ProxyRequest, reply: FastifyReply) => {
|
|
const { url, referer, origin, userAgent } = req.query;
|
|
|
|
if (!url) {
|
|
return reply.code(400).send({ error: "No URL provided" });
|
|
}
|
|
|
|
try {
|
|
const { response, contentType, isM3U8 } = await proxyRequest(url, {
|
|
referer,
|
|
origin,
|
|
userAgent
|
|
});
|
|
|
|
reply.header('Access-Control-Allow-Origin', '*');
|
|
reply.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
|
|
|
if (contentType) {
|
|
reply.header('Content-Type', contentType);
|
|
}
|
|
|
|
if (isM3U8) {
|
|
const text = await response.text();
|
|
const baseUrl = new URL(response.url);
|
|
const processedContent = processM3U8Content(text, baseUrl, {
|
|
referer,
|
|
origin,
|
|
userAgent
|
|
});
|
|
|
|
return processedContent;
|
|
} else {
|
|
return reply.send(streamToReadable(response.body!));
|
|
}
|
|
|
|
} catch (err) {
|
|
fastify.log.error(err);
|
|
return reply.code(500).send({ error: "Internal Server Error" });
|
|
}
|
|
});
|
|
}
|
|
|
|
export default proxyRoutes; |