import { AppError, attachUser, currentUser, requireAuth, type App, type Db, } from "../lib/index.js"; /** * Galerie : liste des fichiers accompagnes de leur nature (image, video, * document...), filtree par les memes droits que l'explorateur. Le dossier * public et les permissions nominatives sont pris en compte, sans exception. */ const KINDS = ["image", "video", "audio", "document", "archive", "other"] as const; export const registerMediaRoutes = (app: App, db: Db): void => { app.use("/api/cloud/media", attachUser(db)); app.get("/api/cloud/media", requireAuth, async (context) => { const user = currentUser(context); const kind = context.req.query("kind") ?? ""; if (kind !== "" && !(KINDS as readonly string[]).includes(kind)) { throw AppError.badRequest("Type de media inconnu."); } const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 60)); const offset = Math.max(0, Number(context.req.query("offset")) || 0); const rows = await db.query<{ id: string; folder_id: string | null; name: string; mime_type: string | null; size_bytes: number; owner_id: string | null; is_starred: number; kind: string | null; width: number | null; height: number | null; created_at: string; has_thumbnail: number; }>( `SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.owner_id, fi.is_starred, mm.kind, mm.width, mm.height, fi.created_at, EXISTS ( SELECT 1 FROM file_variants fv WHERE fv.file_id = fi.id AND fv.purpose = 'thumbnail' ) AS has_thumbnail FROM files fi LEFT JOIN media_metadata mm ON mm.file_id = fi.id WHERE fi.deleted_at IS NULL AND ( ? = '' OR mm.kind = ? ) AND ( ? = 1 OR fi.owner_id = ? OR ( fi.folder_id IS NOT NULL AND EXISTS ( SELECT 1 FROM folders f WHERE f.id = fi.folder_id AND f.access_type = 'public' ) ) OR ( fi.folder_id IS NOT NULL AND EXISTS ( SELECT 1 FROM folder_permissions fp WHERE fp.folder_id = fi.folder_id AND fp.user_id = ? AND fp.level IN ('read', 'write', 'admin') AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) ) ORDER BY fi.created_at DESC LIMIT ${limit} OFFSET ${offset}`, [kind, kind, 0, user.id, user.id], ); return context.json({ kind: kind || null, items: rows.map((row) => ({ id: row.id, folder_id: row.folder_id, name: row.name, mime_type: row.mime_type, size_bytes: row.size_bytes, owner_id: row.owner_id, is_starred: row.is_starred === 1, kind: row.kind, width: row.width, height: row.height, created_at: row.created_at, has_thumbnail: row.has_thumbnail === 1, })), }); }); };