Add Api for song upload

This commit is contained in:
Esa Kataja
2024-10-12 16:21:06 +03:00
parent 6bf57ff672
commit d47631abe9
6 changed files with 315 additions and 8 deletions
+39
View File
@@ -0,0 +1,39 @@
import { json } from '@sveltejs/kit';
import { parseBuffer } from 'music-metadata';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { unlink } from 'fs/promises';
export const config = {
api: {
bodyParser: false
}
};
export async function POST({ request }) {
try {
const formData = await request.formData();
const file = formData.get('upload');
if (!file) {
return json({ error: 'No file uploaded' }, { status: 400 });
}
// Save the file temporarily
const buffer = await file.arrayBuffer();
const tempPath = join('/tmp', `upload_${Date.now()}_${file.name}`);
await writeFile(tempPath, Buffer.from(buffer));
// Parse metadata
const metadata = await parseBuffer(Buffer.from(buffer));
// Clean up the temporary file
// You might want to handle this asynchronously or use a try-finally block
await unlink(tempPath);
return json({ metadata });
} catch (error) {
console.error('Error processing file:', error);
return json({ error: 'Failed to process file' }, { status: 500 });
}
}
+37
View File
@@ -0,0 +1,37 @@
export async function POST({ request }) {
console.log('ytUpload API endpoint hit');
const body = await request.json();
const ytId = body.id;
if (!ytId) {
return {
status: 400,
body: { error: 'No id provided' }
};
}
try {
console.log('Fetching YouTube metadata...');
const response = await fetch(
`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${ytId}&format=json`
);
const data = await response.json();
console.log('Response from YouTube:', data);
if (data.error) {
return Response.json({
status: 400,
body: { error: data.error.message }
});
}
return Response.json({
status: 200,
body: { metadata: data }
});
} catch (error) {
console.error('Error fetching YouTube metadata:', error);
return Response.json({
status: 500,
body: { error: 'Internal Server Error' }
});
}
}