62 lines
2.4 KiB
JavaScript
62 lines
2.4 KiB
JavaScript
import app from '@adonisjs/core/services/app';
|
|
import { readdirSync, existsSync, statSync, unlinkSync } from 'node:fs';
|
|
import { extname, join } from 'node:path';
|
|
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp']);
|
|
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.avi', '.webm']);
|
|
function getMediaType(filename) {
|
|
const ext = extname(filename).toLowerCase();
|
|
if (IMAGE_EXTENSIONS.has(ext))
|
|
return 'image';
|
|
if (VIDEO_EXTENSIONS.has(ext))
|
|
return 'video';
|
|
return 'unknown';
|
|
}
|
|
export default class MediaController {
|
|
async index({ view }) {
|
|
const uploadsDir = app.publicPath('uploads');
|
|
let files = [];
|
|
try {
|
|
const entries = readdirSync(uploadsDir, { withFileTypes: true });
|
|
files = entries
|
|
.filter((entry) => entry.isFile())
|
|
.map((entry) => {
|
|
const stat = statSync(join(uploadsDir, entry.name));
|
|
return {
|
|
filename: entry.name,
|
|
url: `/uploads/${entry.name}`,
|
|
type: getMediaType(entry.name),
|
|
size: stat.size,
|
|
};
|
|
})
|
|
.sort((a, b) => b.filename.localeCompare(a.filename));
|
|
}
|
|
catch {
|
|
files = [];
|
|
}
|
|
return view.render('dashboard', { files });
|
|
}
|
|
async serve({ params, response }) {
|
|
const { filename } = params;
|
|
if (!/^[\w\-. ]+$/.test(filename)) {
|
|
return response.status(400).json({ error: 'Invalid filename.' });
|
|
}
|
|
const filePath = join(app.publicPath('uploads'), filename);
|
|
if (!existsSync(filePath)) {
|
|
return response.status(404).json({ error: 'Media not found', filename });
|
|
}
|
|
return response.download(filePath);
|
|
}
|
|
async destroy({ params, response }) {
|
|
const { filename } = params;
|
|
if (!/^[\w\-. ]+$/.test(filename)) {
|
|
return response.status(400).json({ success: false, message: 'Invalid filename.' });
|
|
}
|
|
const filePath = join(app.publicPath('uploads'), filename);
|
|
if (!existsSync(filePath)) {
|
|
return response.status(404).json({ success: false, message: 'File not found.' });
|
|
}
|
|
unlinkSync(filePath);
|
|
return response.ok({ success: true });
|
|
}
|
|
}
|
|
//# sourceMappingURL=media_controller.js.map
|