Files
discord-storage/src/app/api/upload-part/route.ts

68 lines
2.3 KiB
TypeScript

import { NextResponse } from 'next/server';
import pool from '@/lib/db';
if (!process.env.DISCORD_BOT_TOKEN || !process.env.DISCORD_CHANNEL_ID) {
throw new Error('Please define DISCORD_BOT_TOKEN and DISCORD_CHANNEL_ID in .env.local');
}
const DISCORD_API_URL = `https://discord.com/api/v10/channels/${process.env.DISCORD_CHANNEL_ID}/messages`;
export async function POST(request: Request) {
try {
const formData = await request.formData();
const fileId = formData.get('file_id') as string;
const partIndex = formData.get('part_index') as string;
const chunk = formData.get('encrypted_chunk') as Blob;
if (!fileId || !partIndex || !chunk) {
return NextResponse.json({ error: 'Missing required form fields' }, { status: 400 });
}
// Forward the chunk to Discord via the Bot API
const discordFormData = new FormData();
discordFormData.append('file', chunk, `chunk-${partIndex}.bin`);
const discordRes = await fetch(DISCORD_API_URL, {
method: 'POST',
headers: {
'Authorization': `Bot ${process.env.DISCORD_BOT_TOKEN}`,
},
body: discordFormData,
});
if (!discordRes.ok) {
const errorBody = await discordRes.json();
console.error('Discord API Error:', errorBody);
return NextResponse.json({ error: 'Failed to upload to Discord' }, { status: 500 });
}
const discordData = await discordRes.json();
const attachment = discordData.attachments[0];
if (!attachment) {
return NextResponse.json({ error: 'No attachment found in Discord response' }, { status: 500 });
}
const discordMessageId = discordData.id;
const discordAttachmentUrl = attachment.url; // This URL is temporary
const partSize = attachment.size;
// Save part metadata to the database
const connection = await pool.getConnection();
try {
await connection.query(
'INSERT INTO file_parts (file_id, part_index, discord_message_id, discord_attachment_url, size) VALUES (?, ?, ?, ?, ?)',
[fileId, parseInt(partIndex), discordMessageId, discordAttachmentUrl, partSize]
);
} finally {
connection.release();
}
return NextResponse.json({ success: true, part_index: partIndex });
} catch (error) {
console.error('Error uploading part:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}