init
This commit is contained in:
50
app/controllers/media_controller.js
Normal file
50
app/controllers/media_controller.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import app from '@adonisjs/core/services/app';
|
||||
import { readdirSync, existsSync, statSync } 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);
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=media_controller.js.map
|
||||
Reference in New Issue
Block a user