Skip to content

Instantly share code, notes, and snippets.

@iRajatDas
Created April 13, 2024 17:18
Show Gist options
  • Save iRajatDas/eefa6178eab980e22b1266edf9111f8c to your computer and use it in GitHub Desktop.
Save iRajatDas/eefa6178eab980e22b1266edf9111f8c to your computer and use it in GitHub Desktop.
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
function slugify(input) {
if (!input)
return '';
// make lower case and trim
var slug = input.toLowerCase().trim();
// remove accents from charaters
slug = slug.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
// replace invalid chars with spaces
slug = slug.replace(/[^a-z0-9\s-]/g, ' ').trim();
// replace multiple spaces or hyphens with a single hyphen
slug = slug.replace(/[\s-]+/g, '_');
return slug;
}
async function handleRequest(request) {
const root_url = new URL(request.url);
// Extract the query parameters
const url = decodeURIComponent(root_url.searchParams.get("url"));
const mediaType = url.includes("mime=video") ? "mp4": "mp3";
console.log(url?.includes("mime=video"), mediaType)
const filename = slugify(root_url.searchParams.get("filename"));
if (!url) {
return new Response('URL parameter is required', { status: 400 });
}
if (!mediaType) {
return new Response('Media type parameter is required', { status: 400 });
}
if (!filename) {
return new Response('Filename parameter is required', { status: 400 });
}
if (mediaType !== 'mp3' && mediaType !== 'mp4') {
return new Response('Invalid media type', { status: 400 });
}
try {
const response = await fetch(url, {
method: request.method,
headers: request.headers,
});
if (!response.ok) {
throw new Error('Failed to fetch');
}
// Set appropriate headers
const responseHeaders = new Headers(response.headers);
responseHeaders.set('Content-Type', mediaType === 'mp3' ? 'audio/mpeg' : 'video/mp4');
responseHeaders.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}.${mediaType}`);
responseHeaders.set('Access-Control-Allow-Origin', '*');
responseHeaders.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
} catch (error) {
console.error(error);
return new Response('Error proxying the request', { status: 500 });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment