diff --git a/src/index.js b/src/index.js index 3aacb7a..8247808 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,7 @@ import { nanoid } from "nanoid"; addEventListener("fetch", event => { - event.respondWith(handleRequest(event)); + event.respondWith(handleRequest(event.request)); }); const headersCORS = { @@ -10,36 +10,7 @@ const headersCORS = { 'Access-Control-Allow-Headers': 'Content-Type, x-Custom-Auth-Key', }; -async function recordRequest(request) { - - const analyticsData = { - timestamp: Date.now(), - domain: new URL(request.url).hostname, - method: request.method, - path: new URL(request.url).pathname, - ipcountry: request.cf.country, - } - const ANALYTICS_URL = 'https://analytics.jonasjones.dev/requests/record'; - - const response = await fetch(ANALYTICS_URL, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': ANALYTICS_API_KEY, - }, - body: JSON.stringify(analyticsData) - }); - - if (response.ok) { - console.log('Request recorded successfully'); - } else { - console.error('Failed to record request:', response.status, await response.text()); - } -} - -async function handleRequest(event) { - const request = event.request; - event.waitUntil(recordRequest(request)); +async function handleRequest(request) { const url = new URL(request.url); const { pathname } = url; @@ -57,10 +28,6 @@ async function handleRequest(event) { return handleUpload(request); } - if (request.method === 'POST' && pathname === '/upload-url') { - return handleUrlUpload(request); - } - if (request.method === 'GET' && pathname.startsWith('/download/')) { const filename = pathname.replace('/download/', ''); return handleDownload(filename); @@ -77,106 +44,56 @@ async function handleRequest(event) { if (request.method === 'GET' && pathname === '/') { return new Response(htmlForm, { - headers: { 'content-type': 'text/html;charset=UTF-8', ...headersCORS }, + headers: { 'content-type': 'text/html;charset=UTF-8' , ...headersCORS}, }); } - return new Response('Not Found', { status: 404, headers: headersCORS }); -} - -async function handleUrlUpload(request) { - const { url, authKey, deletionTimestamp } = await request.json(); - if (!url || !authKey) { - return new Response('Bad Request', { status: 400, headers: headersCORS }); - } - - if (authKey !== `Bearer ${AUTH_KEY_SECRET}`) { - return new Response('Unauthorized', { status: 401, headers: headersCORS }); - } - - try { - const fileResponse = await fetch(url); - if (!fileResponse.ok) { - return new Response('Failed to download file', { status: 500, headers: headersCORS }); - } - - const fileBlob = await fileResponse.blob(); - const hash = nanoid(); - const contentType = fileResponse.headers.get('Content-Type') || 'application/octet-stream'; - const originalName = url.split('/').pop(); - - // Use provided deletionTimestamp or default to 24 hours from now - const expiryTimestamp = deletionTimestamp ? parseInt(deletionTimestamp) : Date.now() + 24 * 60 * 60 * 1000; - - await CDN_BUCKET.put(`tempupload/content/${hash}`, fileBlob.stream(), { - httpMetadata: { contentType }, - }); - - const indexData = await CDN_BUCKET.get('tempupload/index.json'); - const index = indexData ? await indexData.json() : []; - - index.push({ - hash, - contentType, - originalName, - deletionTimestamp: expiryTimestamp, - }); - - await CDN_BUCKET.put('tempupload/index.json', JSON.stringify(index), { - httpMetadata: { contentType: 'application/json' }, - }); - - return new Response(JSON.stringify({ downloadLink: `/download/${hash}` }), { - headers: { 'Content-Type': 'application/json', ...headersCORS }, - }); - } catch (error) { - return new Response(`Error: ${error.message}`, { status: 500, headers: headersCORS }); - } + return new Response('Not Found', { status: 404 }, headersCORS); } async function cleanUpExpiredFiles() { - const indexData = await CDN_BUCKET.get('tempupload/index.json'); + const indexData = await CDN_BUCKET.get('/tempupload/index.json'); if (!indexData) { return; } let index = await indexData.json(); + const now = Date.now(); const updatedIndex = []; - for (fileRecord of index) { - if (fileRecord.deletionTimestamp <= Date.now()) { - await CDN_BUCKET.delete(`tempupload/content/${fileRecord.hash}`); + for (const fileRecord of index) { + if (fileRecord.deletionTimestamp <= now) { + await CDN_BUCKET.delete(`/tempupload/content/${fileRecord.hash}`); } else { updatedIndex.push(fileRecord); } } if (updatedIndex.length !== index.length) { - await CDN_BUCKET.put('tempupload/index.json', JSON.stringify(updatedIndex), { + await CDN_BUCKET.put('/tempupload/index.json', JSON.stringify(updatedIndex), { httpMetadata: { contentType: 'application/json' }, }); } } async function handleUpload(request) { + + // Password protection const password = request.headers.get('X-Custom-Auth-Key'); if (password !== `Bearer ${AUTH_KEY_SECRET}`) { - return new Response('Unauthorized', { status: 401, headers: headersCORS }); + return new Response('Unauthorized', { status: 401 }, headersCORS); } const formData = await request.formData(); const file = formData.get('file'); - const deletionTimestamp = formData.get('deletionTimestamp'); - console.log('deletionTimestamp:', deletionTimestamp); if (!file) { - return new Response('Bad Request', { status: 400, headers: headersCORS }); + return new Response('Bad Request', { status: 400 }, headersCORS); } const hash = nanoid(); const contentType = file.type; const originalName = file.name; - - const expiryTimestamp = deletionTimestamp ? parseInt(deletionTimestamp) : Date.now() + 7 * 24 * 60 * 60 * 1000; + const deletionTimestamp = Date.now() + 24 * 60 * 60 * 1000; // 24 hours await CDN_BUCKET.put(`tempupload/content/${hash}`, file.stream(), { httpMetadata: { contentType }, @@ -189,7 +106,7 @@ async function handleUpload(request) { hash, contentType, originalName, - deletionTimestamp: expiryTimestamp, + deletionTimestamp, }); await CDN_BUCKET.put('tempupload/index.json', JSON.stringify(index), { @@ -204,18 +121,18 @@ async function handleUpload(request) { async function handleDownload(hash) { const indexData = await CDN_BUCKET.get('tempupload/index.json'); if (!indexData) { - return new Response('Not Found', { status: 404, headers: headersCORS }); + return new Response('Not Found', { status: 404 }, headersCORS); } const index = await indexData.json(); const fileRecord = index.find(file => file.hash === hash); if (!fileRecord) { - return new Response('Not Found', { status: 404, headers: headersCORS }); + return new Response('Not Found', { status: 404 }, headersCORS); } const file = await CDN_BUCKET.get(`tempupload/content/${hash}`); if (!file) { - return new Response('Not Found', { status: 404, headers: headersCORS }); + return new Response('Not Found', { status: 404 }, headersCORS); } const response = new Response(file.body, { @@ -230,23 +147,32 @@ async function handleDownload(hash) { } async function handleDelete(request) { + + // get pathname const url = new URL(request.url); + const filehash = url.pathname.replace('/delete/', ''); + console.log('filename', filehash) + + // Password protection const password = request.headers.get('X-Custom-Auth-Key'); if (password !== `Bearer ${AUTH_KEY_SECRET}`) { - return new Response('Unauthorized', { status: 401, headers: headersCORS }); + return new Response('Unauthorized', { status: 401 }, headersCORS); } const indexData = await CDN_BUCKET.get('tempupload/index.json'); if (await !indexData) { - return new Response('Not Found', { status: 404, headers: headersCORS }); + console.log('indexData', indexData) + return new Response('Not Found', { status: 404 }, headersCORS); } let index = await indexData.json(); const fileRecord = index.find(file => file.hash === filehash); if (!fileRecord) { - return new Response('Not Found', { status: 404, headers: headersCORS }); + console.log('indexData', indexData) + console.log('fileRecord', fileRecord) + return new Response('Not Found', { status: 404 }, headersCORS); } await CDN_BUCKET.delete(`tempupload/content/${fileRecord.hash}`); @@ -256,9 +182,10 @@ async function handleDelete(request) { httpMetadata: { contentType: 'application/json' }, }); - return new Response('File deleted', { status: 200, headers: headersCORS }); + return new Response('File deleted', { status: 200 }, headersCORS); } + const htmlForm = ` @@ -293,24 +220,10 @@ const htmlForm = `
- - - Set to delete 7 days from now
-

Upload from URL

-
- - - - - Set to delete 7 days from now - -
-
-

Delete a File