2026-01-12 03:56:47 +08:00

123 lines
2.4 KiB
JavaScript

import Router from 'koa-router';
import multer from '@koa/multer';
import path from 'path';
import fs from 'fs';
const router = new Router({
prefix: '/api/files'
});
const uploadDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + '-' + file.originalname);
}
});
const upload = multer({ storage });
const fileTransfers = new Map();
router.get('/info', async (ctx) => {
ctx.body = {
message: 'File API endpoint'
};
});
router.post('/metadata', async (ctx) => {
const { fileId, name, size, type, senderId, receiverId } = ctx.request.body;
fileTransfers.set(fileId, {
fileId,
name,
size,
type,
senderId,
receiverId,
progress: 0,
status: 'pending',
createdAt: new Date()
});
ctx.body = {
success: true,
fileId,
message: 'File metadata registered'
};
});
router.get('/metadata/:fileId', async (ctx) => {
const { fileId } = ctx.params;
const fileData = fileTransfers.get(fileId);
if (!fileData) {
ctx.status = 404;
ctx.body = {
error: 'File not found'
};
return;
}
ctx.body = fileData;
});
router.put('/progress/:fileId', async (ctx) => {
const { fileId } = ctx.params;
const { progress, status } = ctx.request.body;
const fileData = fileTransfers.get(fileId);
if (fileData) {
fileData.progress = progress;
if (status) {
fileData.status = status;
}
ctx.io?.to(fileData.senderId).emit('file-progress', {
fileId,
progress,
status
});
ctx.io?.to(fileData.receiverId).emit('file-progress', {
fileId,
progress,
status
});
}
ctx.body = {
success: true,
fileId,
progress
};
});
router.delete('/:fileId', async (ctx) => {
const { fileId } = ctx.params;
fileTransfers.delete(fileId);
ctx.body = {
success: true,
message: 'File transfer cancelled'
};
});
router.get('/transfers', async (ctx) => {
const { userId } = ctx.query;
const transfers = Array.from(fileTransfers.values()).filter(
transfer => transfer.senderId === userId || transfer.receiverId === userId
);
ctx.body = transfers;
});
export default router;