Make API route accept all music files
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
apatil 2025-05-07 21:12:08 +01:00
parent ecdeced95e
commit 042a6ae021
4 changed files with 16 additions and 11 deletions

View File

@ -1,14 +1,9 @@
import { checkIfMusicFile } from '@/lib/music';
import fs from 'fs'; import fs from 'fs';
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
const MUSIC_DIR = '/app/music'; const MUSIC_DIR = '/app/music';
export async function GET() { export async function GET() {
const files = fs const files = fs.readdirSync(MUSIC_DIR).filter((f) => checkIfMusicFile(f));
.readdirSync(MUSIC_DIR)
.filter((f) =>
['.mp3', '.m4a', 'audio/mpeg', 'audio/mp4', 'audio/x-m4a'].some((suffix) =>
f.endsWith(suffix),
),
);
return NextResponse.json(files); return NextResponse.json(files);
} }

View File

@ -1,14 +1,18 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
import { checkIfMusicFile } from '@/lib/music';
const MUSIC_DIR = '/app/music'; const MUSIC_DIR = '/app/music';
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const formData = await req.formData(); const formData = await req.formData();
const file = formData.get('file') as File; const file = formData.get('file') as File;
if (!file || !file.name.endsWith('.mp3')) { if (checkIfMusicFile(file.name)) {
return NextResponse.json({ error: 'Only .mp3 files are allowed.' }, { status: 400 }); return NextResponse.json(
{ error: 'Only music files are allowed to be uploaded' },
{ status: 400 },
);
} }
const arrayBuffer = await file.arrayBuffer(); const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer); const buffer = Buffer.from(arrayBuffer);

View File

@ -34,6 +34,8 @@ export default function Home() {
setUploading(false); setUploading(false);
if (res.ok) { if (res.ok) {
fetchTracks(); fetchTracks();
} else {
console.error(res.status, res.text())
} }
}; };
@ -43,9 +45,9 @@ export default function Home() {
Music Player Music Player
</Typography> </Typography>
<Box textAlign="center" mb={3}> <Box textAlign="center" mb={3}>
<label htmlFor="upload-mp3"> <label htmlFor="upload">
<Input <Input
id="upload-mp3" id="upload"
type="file" type="file"
sx={{ display: 'none' }} sx={{ display: 'none' }}
inputProps={{ accept: '.mp3, .m4a, audio/mpeg, audio/mp4, audio/x-m4a' }} inputProps={{ accept: '.mp3, .m4a, audio/mpeg, audio/mp4, audio/x-m4a' }}

4
src/lib/music.ts Normal file
View File

@ -0,0 +1,4 @@
export const checkIfMusicFile = (name: string) =>
['.mp3', '.m4a', 'audio/mpeg', 'audio/mp4', 'audio/x-m4a'].some((suffix) =>
name.endsWith(suffix),
);