'use strict'; const { Controller } = require('egg'); /** 正整数(非法的用默认值) */ function toPositiveInt(value, fallback) { const num = Number(value); return Number.isInteger(num) && num > 0 ? num : fallback; } /** 宽松布尔:true / '1' / 'true' / 'yes' / 'on' */ function toBool(value) { return /^(1|true|yes|on)$/i.test(String(value === undefined ? '' : value)); } /** * 平台管理:文件存储(COS 图片的登记、引用状态、清理) * * 鉴权:`middleware.apiAuth()` + `middleware.platformAdmin()`。 * * - `GET /api/web/admin/files` 分页列表(带引用状态与统计) * - `POST /api/web/admin/files/cleanup` 清理未引用文件(默认 dryRun,只预览) * - `DELETE /api/web/admin/files/:id` 删除单个文件(`?force=1` 可删仍被引用的) * * 「是否被引用」由 `service/fileStorage` 实时计算(用户头像 / 文档正文), * 不是上传时打标记,所以业务数据改了引用状态立刻跟着变。 */ class WebAdminFileController extends Controller { /** GET /api/web/admin/files */ async index() { const { ctx } = this; const query = ctx.query || {}; const referencedRaw = String(query.referenced === undefined ? '' : query.referenced).trim(); const data = await ctx.service.fileStorage.list({ page: toPositiveInt(query.page, 1), pageSize: Math.min(toPositiveInt(query.pageSize, 20), 100), keyword: String(query.keyword || '').trim(), category: String(query.category || '').trim(), referenced: referencedRaw === '' || referencedRaw === 'all' ? '' : toBool(referencedRaw), }); ctx.body = { ok: true, data: { ...data, storage: ctx.service.fileStorage.storageMeta() } }; } /** POST /api/web/admin/files/cleanup —— body: `{ dryRun?, minAgeHours?, limit? }` */ async cleanup() { const { ctx } = this; const body = ctx.request.body || {}; const data = await ctx.service.fileStorage.cleanup({ // 不传就按安全侧处理:只预览,不删除 dryRun: body.dryRun === undefined ? true : toBool(body.dryRun), minAgeHours: body.minAgeHours, limit: body.limit, }); ctx.body = { ok: true, data }; } /** DELETE /api/web/admin/files/:id?force=1 */ async destroy() { const { ctx } = this; const id = toPositiveInt(ctx.params.id, 0); if (!id) ctx.throw(400, 'id 必须是正整数'); const data = await ctx.service.fileStorage.remove(id, { force: toBool(ctx.query.force) }); ctx.body = { ok: true, data }; } } module.exports = WebAdminFileController;