liufumingren bde5dc7bad feat(backend): 图片上传接入腾讯云 COS,新增存储管理与未引用清理
- 头像 / 文档图片改由后端校验并转发到 COS,密钥只留在服务端
- 新增 file_records 登记表(迁移 20261123170000),记录对象键、大小、上传者等
- 引用关系实时计算(用户头像 / 文档正文),改删业务数据后状态自动同步
- 新增平台管理「存储管理」页:引用状态与明细、单删、两步清理未引用
- 新增接口 GET /api/web/admin/files、POST /api/web/admin/files/cleanup、
  DELETE /api/web/admin/files/:id(仍被引用默认 409,force 才删)
- COS 目录前缀(COS_DIR_AVATAR / COS_DIR_DOC)、大小上限、清理保护期改为可配置

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 16:39:47 +08:00

71 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;