import fs from 'node:fs/promises'; import { Router } from 'express'; import multer from 'multer'; import { fileTypeFromFile } from 'file-type'; import { z } from 'zod'; import { HttpError, idSchema } from './model.js'; import { audit, pool, stagingDir, transaction, uploadPath } from './storage.js'; const upload = multer({ dest: stagingDir, limits: { fileSize: 100 * 1024 * 1024, files: 1, fields: 0 } }); const formats = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif', 'video/mp4': 'mp4', 'video/webm': 'webm', }; export const library = Router(); library.get('/media', async (_req, res) => { const [files, galleries] = await Promise.all([ pool.query('SELECT id,name,mime,bytes,created_at FROM media WHERE deleted_at IS NULL ORDER BY created_at DESC,name'), pool.query('SELECT id,name,media_ids,created_at FROM galleries WHERE deleted_at IS NULL ORDER BY created_at DESC,name'), ]); res.json({ files: files.rows, galleries: galleries.rows }); }); library.post('/media', upload.single('file'), async (req, res) => { if (!req.file) throw new HttpError(400, 'Wähle eine Datei aus.'); const temp = req.file.path; let saved; try { const fileType = await fileTypeFromFile(temp).catch(() => null); const mime = fileType?.mime; const extension = formats[mime]; if (!extension) throw new HttpError(415, 'Unterstützt werden JPG, PNG, WebP, GIF, AVIF, MP4 und WebM.'); const file = { id: crypto.randomUUID(), extension }; const name = Buffer.from(req.file.originalname, 'latin1').toString('utf8').replace(/[\u0000-\u001f]/g, '').slice(0, 200) || 'Datei'; const finalPath = uploadPath(file); await fs.rename(temp, finalPath); try { saved = await transaction(async (db) => { const result = await db.query('INSERT INTO media (id,name,mime,extension,bytes) VALUES ($1,$2,$3,$4,$5) RETURNING *', [file.id, name, mime, extension, req.file.size]); await audit(db, 'uploaded', `„${name}“ hochgeladen`); return result.rows[0]; }); } finally { if (!saved) await fs.rm(finalPath, { force: true }); } res.status(201).json(saved); } finally { await fs.rm(temp, { force: true }); } }); library.get('/media/:id/file', async (req, res) => { const result = await pool.query('SELECT * FROM media WHERE id=$1 AND deleted_at IS NULL', [idSchema.parse(req.params.id)]); if (!result.rowCount) throw new HttpError(404, 'Datei nicht gefunden.'); res.type(result.rows[0].mime).sendFile(uploadPath(result.rows[0]), { cacheControl: false }); }); const gallerySchema = z.object({ name: z.string().trim().min(1).max(100), mediaIds: z.array(idSchema).min(1).max(12) }); async function saveGallery(req, res) { const id = req.params.id ? idSchema.parse(req.params.id) : crypto.randomUUID(); const gallery = gallerySchema.parse(req.body); const ids = [...new Set(gallery.mediaIds)]; const item = await transaction(async (db) => { const found = await db.query("SELECT id FROM media WHERE id=ANY($1) AND deleted_at IS NULL AND mime LIKE 'image/%'", [ids]); if (found.rowCount !== ids.length) throw new HttpError(422, 'Wähle Bilder aus der Medienbibliothek aus.'); const result = req.params.id ? await db.query('UPDATE galleries SET name=$2,media_ids=$3 WHERE id=$1 AND deleted_at IS NULL RETURNING *', [id, gallery.name, ids]) : await db.query('INSERT INTO galleries (id,name,media_ids) VALUES ($1,$2,$3) RETURNING *', [id, gallery.name, ids]); if (!result.rowCount) throw new HttpError(404, 'Galerie nicht gefunden.'); await audit(db, 'edited', `Galerie „${gallery.name}“ gespeichert`); return result.rows[0]; }); res.status(req.params.id ? 200 : 201).json(item); } library.post('/galleries', saveGallery); library.put('/galleries/:id', saveGallery); for (const [route, table] of [['media', 'media'], ['galleries', 'galleries']]) { library.delete(`/${route}/:id`, async (req, res) => { await transaction(async (db) => { const result = await db.query(`UPDATE ${table} SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL RETURNING name`, [idSchema.parse(req.params.id)]); if (!result.rowCount) throw new HttpError(404, 'Eintrag nicht gefunden.'); await audit(db, 'deleted', `„${result.rows[0].name}“ in den Papierkorb verschoben`); }); res.status(204).end(); }); }