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>
This commit is contained in:
parent
e9a08e7daa
commit
bde5dc7bad
@ -455,6 +455,12 @@ npm run cov
|
|||||||
| `SMTP_SECURE` | `true` | 是否用 TLS(465 用 true,587 用 false) |
|
| `SMTP_SECURE` | `true` | 是否用 TLS(465 用 true,587 用 false) |
|
||||||
| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号 / 密码(QQ 邮箱填「授权码」,不是登录密码;放 `shared-config/env.prod.sh` 或环境变量) |
|
| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号 / 密码(QQ 邮箱填「授权码」,不是登录密码;放 `shared-config/env.prod.sh` 或环境变量) |
|
||||||
| `SMTP_FROM` | `云仓视频溯源系统 <no-reply@...>` | 发件人(默认取 `SITE_NAME` 作显示名) |
|
| `SMTP_FROM` | `云仓视频溯源系统 <no-reply@...>` | 发件人(默认取 `SITE_NAME` 作显示名) |
|
||||||
|
| `COS_SECRET_ID` / `COS_SECRET_KEY` | 空 | 腾讯云 CAM 密钥(只在服务端使用);未配置时头像 / 文档图片上传返回 503 |
|
||||||
|
| `COS_BUCKET` / `COS_REGION` | 空 | COS 存储桶名称(含 APPID)/ 地域,如 `ap-guangzhou` |
|
||||||
|
| `COS_CDN_URL` / `COS_PUBLIC_URL` | 空 | 图片访问域名;都未设置时按 COS 默认桶域名拼接 |
|
||||||
|
| `COS_DIR_AVATAR` / `COS_DIR_DOC` | `images/avatars` / `images/docs` | 对象键前缀(存储路径),见「文件存储」一节 |
|
||||||
|
| `COS_MAX_FILE_SIZE` | `5242880` | 单张图片上限(字节),默认 5 MB |
|
||||||
|
| `COS_CLEANUP_MIN_AGE_HOURS` | `24` | 清理未引用文件时的最小存活小时数(防止刚上传还没保存的内容被误删) |
|
||||||
| `EMAIL_CODE_TTL` | `600` | 邮箱验证码有效期(秒) |
|
| `EMAIL_CODE_TTL` | `600` | 邮箱验证码有效期(秒) |
|
||||||
| `EMAIL_CODE_RESEND` | `60` | 同一邮箱重发验证码的间隔(秒) |
|
| `EMAIL_CODE_RESEND` | `60` | 同一邮箱重发验证码的间隔(秒) |
|
||||||
| `EMAIL_CODE_ATTEMPTS` | `5` | 同一个验证码最多校验几次(超过则作废) |
|
| `EMAIL_CODE_ATTEMPTS` | `5` | 同一个验证码最多校验几次(超过则作废) |
|
||||||
@ -648,6 +654,27 @@ node scripts/backfill-snapshot.js --dry-run
|
|||||||
`Rows_examined` ≈ 33 万,冷缓存 9.9 s / 热缓存 0.45 s;补完是纯索引扫描,0.09 s(迁移 `20261116200000`);
|
`Rows_examined` ≈ 33 万,冷缓存 9.9 s / 热缓存 0.45 s;补完是纯索引扫描,0.09 s(迁移 `20261116200000`);
|
||||||
- `(scanner_id, channel_id, scan_time)`:散单要取同通道「上一条 / 下一条」的扫码时间。
|
- `(scanner_id, channel_id, scan_time)`:散单要取同通道「上一条 / 下一条」的扫码时间。
|
||||||
|
|
||||||
|
### file_records 上传文件登记表(2026-11-23)
|
||||||
|
|
||||||
|
每张上传成功的 COS 图片一行,用于「存储管理」页面与清理接口。
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| id | bigint unsigned | 主键 |
|
||||||
|
| object_key | varchar(512) | COS 对象键(`images/avatars/<userId>/<uuid>.png`),**唯一** |
|
||||||
|
| url | varchar(512) | 对外访问地址(CDN / COS 域名 + 对象键) |
|
||||||
|
| file_name | varchar(255) | 上传时的原始文件名 |
|
||||||
|
| size | bigint unsigned | 字节数 |
|
||||||
|
| mime_type | varchar(100) | MIME 类型 |
|
||||||
|
| hash | varchar(64) | 内容 SHA256(排查重复 / 校验) |
|
||||||
|
| category | varchar(32) | `avatar` 头像 / `doc` 文档图片 |
|
||||||
|
| uploader_id / uploader_name | bigint / varchar(64) | 上传者 id 与姓名快照 |
|
||||||
|
| created_at / updated_at / deleted_at | datetime | 时间戳与软删除 |
|
||||||
|
|
||||||
|
索引:`object_key` 唯一;`(category, created_at)` 供列表按分类 + 时间筛选;`uploader_id` 供按人排查。
|
||||||
|
|
||||||
|
> **引用关系不落库**:查询时用 `EXISTS` 实时判断(头像 / 文档正文),详见「文件存储(COS 图片)」一节。
|
||||||
|
|
||||||
## 页面(在前端项目里)
|
## 页面(在前端项目里)
|
||||||
|
|
||||||
⚠️ **后端不再渲染页面**:`app/view/`、nunjucks、session、CSRF 都已移除,`app/controller/page/` 也删掉了。
|
⚠️ **后端不再渲染页面**:`app/view/`、nunjucks、session、CSRF 都已移除,`app/controller/page/` 也删掉了。
|
||||||
@ -1089,6 +1116,7 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
|
|||||||
| POST | `/api/web/admin/doc/articles` | 新增内容页 `{ sectionId, title, slug?, summary?, content?, sort?, status? }`;`slug` 留空自动 `a1`、`a2`… |
|
| POST | `/api/web/admin/doc/articles` | 新增内容页 `{ sectionId, title, slug?, summary?, content?, sort?, status? }`;`slug` 留空自动 `a1`、`a2`… |
|
||||||
| PUT | `/api/web/admin/doc/articles/:id` | 修改内容页(`slug` 创建后不可改;传 `sectionId` 可换栏目;`status=0` 作草稿,不生成页面) |
|
| PUT | `/api/web/admin/doc/articles/:id` | 修改内容页(`slug` 创建后不可改;传 `sectionId` 可换栏目;`status=0` 作草稿,不生成页面) |
|
||||||
| DELETE | `/api/web/admin/doc/articles/:id` | 删除内容页 |
|
| DELETE | `/api/web/admin/doc/articles/:id` | 删除内容页 |
|
||||||
|
| POST | `/api/web/admin/doc/upload-image` | 上传文档图片到 COS(multipart `file`),返回 `{ key, url }`,编辑器插入 Markdown |
|
||||||
| POST | `/api/web/admin/doc/rebuild` | 手动整站重生成(排查用,返回页面数与 sitemap 条数) |
|
| POST | `/api/web/admin/doc/rebuild` | 手动整站重生成(排查用,返回页面数与 sitemap 条数) |
|
||||||
|
|
||||||
公开读取(无令牌):`GET /doc/**`、`GET /sitemap.txt`。
|
公开读取(无令牌):`GET /doc/**`、`GET /sitemap.txt`。
|
||||||
@ -1105,11 +1133,69 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
|
|||||||
| 管理员 | `/admin/members` | `views/AdminMembersView.vue` | 平台管理员列表 + 添加(按账号)+ 移除 |
|
| 管理员 | `/admin/members` | `views/AdminMembersView.vue` | 平台管理员列表 + 添加(按账号)+ 移除 |
|
||||||
| 插件配置 | `/admin/extension` | `views/AdminExtensionView.vue` | Chrome 插件的单号前缀 / 生效站点 / 跳转模板 |
|
| 插件配置 | `/admin/extension` | `views/AdminExtensionView.vue` | Chrome 插件的单号前缀 / 生效站点 / 跳转模板 |
|
||||||
| 文档管理 | `/admin/doc` | `views/AdminDocView.vue` | 文档站 CMS:栏目 → 内容页(Markdown)两级,保存即重生成静态页面 |
|
| 文档管理 | `/admin/doc` | `views/AdminDocView.vue` | 文档站 CMS:栏目 → 内容页(Markdown)两级,保存即重生成静态页面 |
|
||||||
|
| 存储管理 | `/admin/files` | `views/AdminFilesView.vue` | COS 图片登记列表:引用状态 / 引用明细 / 单删 / 清理未引用(见下一节) |
|
||||||
|
|
||||||
- 是否显示这组菜单靠 `GET /api/web/admin/me`(`composables/usePlatformAdmin.ts`;非管理员 403 静默当 false);
|
- 是否显示这组菜单靠 `GET /api/web/admin/me`(`composables/usePlatformAdmin.ts`;非管理员 403 静默当 false);
|
||||||
- 路由带 `meta.platformAdmin`,不是平台管理员会被守卫踢回首页(`?denied=1`);
|
- 路由带 `meta.platformAdmin`,不是平台管理员会被守卫踢回首页(`?denied=1`);
|
||||||
- 这些页面 `allowNoSubject: true` —— 平台管理员可能一个主体都没有,不能因为「没主体」被挡走。
|
- 这些页面 `allowNoSubject: true` —— 平台管理员可能一个主体都没有,不能因为「没主体」被挡走。
|
||||||
|
|
||||||
|
## 文件存储(COS 图片,2026-11-23)
|
||||||
|
|
||||||
|
用户头像、文档图片都存腾讯云 COS。**密钥只在服务端**(`COS_SECRET_ID` / `COS_SECRET_KEY`),
|
||||||
|
浏览器的上传请求发给后端,后端校验后再 `putObject`,不会把临时密钥下发给前端。
|
||||||
|
|
||||||
|
### 目录(对象键前缀)配置
|
||||||
|
|
||||||
|
| 配置 | 环境变量 | 默认值 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `config.cos.dirs.avatar` | `COS_DIR_AVATAR` | `images/avatars` | 头像目录;实际上传再按用户分子目录(`images/avatars/<userId>/<uuid>.png`) |
|
||||||
|
| `config.cos.dirs.doc` | `COS_DIR_DOC` | `images/docs` | 文档图片目录 |
|
||||||
|
| `config.cos.maxFileSize` | `COS_MAX_FILE_SIZE` | `5242880`(5 MB) | 单张上限;multipart 的限制跟着换算 |
|
||||||
|
| `config.cos.cleanupMinAgeHours` | `COS_CLEANUP_MIN_AGE_HOURS` | `24` | 清理未引用文件时的保护期(小时) |
|
||||||
|
|
||||||
|
对象键统一是 `<目录>/<uuid><扩展名>`;访问地址 = `config.cos.publicUrl`(`COS_CDN_URL` 或 `COS_PUBLIC_URL`,
|
||||||
|
都没配就用 COS 默认桶域名)+ 对象键。
|
||||||
|
|
||||||
|
### 上传接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 鉴权 | 说明 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| POST | `/api/web/me/avatar` | 用户令牌 | multipart `file`;头像按 `images/avatars/<userId>/` 存;只返回 `{ key, url }`,前端保存资料时写入 `avatar` |
|
||||||
|
| POST | `/api/web/admin/doc/upload-image` | 平台管理员 | multipart `file`;文档图片存 `images/docs/` |
|
||||||
|
|
||||||
|
校验:扩展名与 MIME 必须一致(BMP / GIF / JPEG / PNG / WebP),并校验文件头,防止伪造后缀;超过上限返回 413。
|
||||||
|
|
||||||
|
### 登记与「是否被引用」
|
||||||
|
|
||||||
|
上传成功会写一行 **`file_records`**(对象键、访问地址、大小、MIME、SHA256、分类、上传者快照)。
|
||||||
|
|
||||||
|
引用关系**不单独存表,实时计算**(`service/fileStorage` 的 `REFERENCE_SOURCES`):
|
||||||
|
|
||||||
|
1. `users.avatar` 等于该文件 URL(或包含对象键,兼容换 CDN 域名);
|
||||||
|
2. `doc_articles.content` 里包含该对象键(文档正文的 Markdown 图片)。
|
||||||
|
|
||||||
|
好处:改头像、删文档、改正文后引用状态**立刻**变化,不会出现「引用行还在、业务数据已删」的脏数据。
|
||||||
|
新增业务模块(例如工单附件)时,在 `REFERENCE_SOURCES` 里加一条 `EXISTS (...)` 片段即可。
|
||||||
|
|
||||||
|
### 管理接口(平台管理员)
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | `/api/web/admin/files` | 分页列表:`page` / `pageSize`(≤100)/ `keyword`(对象键、文件名)/ `category`(avatar、doc)/ `referenced`(`1` 已引用、`0` 未引用、不传全部);返回 `list`、`total`、`stats`(数量与容量)、`storage`(桶/地域/目录配置,**不含密钥**)|
|
||||||
|
| POST | `/api/web/admin/files/cleanup` | 清理未引用文件:`{ dryRun?, minAgeHours?, limit? }`。**`dryRun` 默认 true(只返回清单)**,显式 `false` 才删除;只处理上传超过 `minAgeHours`(默认 24h)且无任何引用的文件;单个失败不影响其余,返回 `failed[]` |
|
||||||
|
| DELETE | `/api/web/admin/files/:id` | 删除单个文件(COS 对象 + 登记行)。仍被引用时返回 **409**;确实要删可带 `?force=1`(引用处图片会失效) |
|
||||||
|
|
||||||
|
清理流程建议:页面「清理未引用」先 `dryRun: true` 拿数量与容量,用户确认后再 `dryRun: false`。
|
||||||
|
|
||||||
|
### 前端
|
||||||
|
|
||||||
|
平台管理 → **存储管理**(`/admin/files`,`views/AdminFilesView.vue`):
|
||||||
|
|
||||||
|
- 顶部统计:文件总数 / 已引用 / 未引用(数量 + 容量)、当前桶与地域;
|
||||||
|
- 列表:缩略图、文件名与对象键、大小、分类、上传者、上传时间、引用状态与引用明细(`头像:张三 · 文档:快速开始`);
|
||||||
|
- 可按关键字、分类、引用状态过滤;仍被引用的文件删除时需二次确认(走 `force`);
|
||||||
|
- 「清理未引用」两步确认(预览 → 执行),执行后自动刷新统计。
|
||||||
|
|
||||||
## 主体(租户)体系(2026-10-18)
|
## 主体(租户)体系(2026-10-18)
|
||||||
|
|
||||||
业务数据(设备 / NVR / 摄像头 / 工作台 / 扫码记录 / 扫码通道)全部挂在**主体**下,接口按主体隔离。
|
业务数据(设备 / NVR / 摄像头 / 工作台 / 扫码记录 / 扫码通道)全部挂在**主体**下,接口按主体隔离。
|
||||||
|
|||||||
@ -21,11 +21,22 @@ function toId(value) {
|
|||||||
* - `POST /api/web/admin/doc/articles` 新增内容页
|
* - `POST /api/web/admin/doc/articles` 新增内容页
|
||||||
* - `PUT /api/web/admin/doc/articles/:id` 修改内容页
|
* - `PUT /api/web/admin/doc/articles/:id` 修改内容页
|
||||||
* - `DELETE /api/web/admin/doc/articles/:id` 删除内容页
|
* - `DELETE /api/web/admin/doc/articles/:id` 删除内容页
|
||||||
|
* - `POST /api/web/admin/doc/upload-image` 上传文档图片到 COS(multipart `file`)
|
||||||
* - `POST /api/web/admin/doc/rebuild` 手动整站重生成(排查用)
|
* - `POST /api/web/admin/doc/rebuild` 手动整站重生成(排查用)
|
||||||
*
|
*
|
||||||
* 所有写操作都会重生成 `/doc/**` 静态页面与 `/sitemap.txt`(见 `service/doc.js`)。
|
* 所有写操作都会重生成 `/doc/**` 静态页面与 `/sitemap.txt`(见 `service/doc.js`)。
|
||||||
*/
|
*/
|
||||||
class WebAdminDocController extends Controller {
|
class WebAdminDocController extends Controller {
|
||||||
|
/** POST /api/web/admin/doc/upload-image */
|
||||||
|
async uploadImage() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const image = await ctx.service.imageUpload.upload(await ctx.getFileStream(), {
|
||||||
|
category: 'doc',
|
||||||
|
dir: this.config.cos.dirs.doc,
|
||||||
|
});
|
||||||
|
ctx.body = { ok: true, data: image };
|
||||||
|
}
|
||||||
|
|
||||||
/** GET /api/web/admin/doc/tree */
|
/** GET /api/web/admin/doc/tree */
|
||||||
async tree() {
|
async tree() {
|
||||||
const data = await this.ctx.service.doc.tree();
|
const data = await this.ctx.service.doc.tree();
|
||||||
|
|||||||
70
backend/app/controller/web/admin_file.js
Normal file
70
backend/app/controller/web/admin_file.js
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
'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;
|
||||||
@ -44,6 +44,16 @@ class WebProfileController extends Controller {
|
|||||||
ctx.body = { ok: true, data: user };
|
ctx.body = { ok: true, data: user };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** POST /api/web/me/avatar —— 上传当前用户头像到 COS */
|
||||||
|
async uploadAvatar() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const image = await ctx.service.imageUpload.upload(await ctx.getFileStream(), {
|
||||||
|
category: 'avatar',
|
||||||
|
dir: `${this.config.cos.dirs.avatar}/${ctx.state.user.id}`,
|
||||||
|
});
|
||||||
|
ctx.body = { ok: true, data: image };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PUT /api/web/me/password —— 修改密码
|
* PUT /api/web/me/password —— 修改密码
|
||||||
* body: `{ oldPassword, newPassword }`
|
* body: `{ oldPassword, newPassword }`
|
||||||
|
|||||||
31
backend/app/model/file_record.js
Normal file
31
backend/app/model/file_record.js
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传文件登记(file_records)
|
||||||
|
*
|
||||||
|
* 只登记「上传成功」的对象;引用关系不落库,由 `service/fileStorage` 实时判断
|
||||||
|
* (用户头像 / 文档正文),所以删除业务数据后不会留下脏引用。
|
||||||
|
*/
|
||||||
|
module.exports = (app) => {
|
||||||
|
const { BIGINT, STRING } = app.Sequelize;
|
||||||
|
|
||||||
|
const FileRecord = app.model.define('file_record', {
|
||||||
|
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||||
|
// `key` 是 MySQL 保留字,落库列名用 object_key
|
||||||
|
key: { type: STRING(512), allowNull: false, unique: true, field: 'object_key', comment: 'COS 对象键' },
|
||||||
|
url: { type: STRING(512), allowNull: false, comment: '对外访问地址' },
|
||||||
|
fileName: { type: STRING(255), allowNull: false, defaultValue: '', comment: '原始文件名' },
|
||||||
|
size: { type: BIGINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '字节数' },
|
||||||
|
mimeType: { type: STRING(100), allowNull: false, defaultValue: '', comment: 'MIME 类型' },
|
||||||
|
hash: { type: STRING(64), allowNull: false, defaultValue: '', comment: '内容 SHA256' },
|
||||||
|
category: { type: STRING(32), allowNull: false, defaultValue: '', comment: '业务分类:avatar / doc' },
|
||||||
|
uploaderId: { type: BIGINT.UNSIGNED, allowNull: true, comment: '上传者 users.id' },
|
||||||
|
uploaderName: { type: STRING(64), allowNull: false, defaultValue: '', comment: '上传者快照' },
|
||||||
|
}, {
|
||||||
|
tableName: 'file_records',
|
||||||
|
paranoid: true,
|
||||||
|
comment: '上传文件登记表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return FileRecord;
|
||||||
|
};
|
||||||
@ -64,6 +64,7 @@ module.exports = (app) => {
|
|||||||
|
|
||||||
router.get('/api/web/me', apiAuth, controller.web.profile.show);
|
router.get('/api/web/me', apiAuth, controller.web.profile.show);
|
||||||
router.put('/api/web/me', apiAuth, controller.web.profile.update);
|
router.put('/api/web/me', apiAuth, controller.web.profile.update);
|
||||||
|
router.post('/api/web/me/avatar', apiAuth, controller.web.profile.uploadAvatar);
|
||||||
router.put('/api/web/me/password', apiAuth, controller.web.profile.changePassword);
|
router.put('/api/web/me/password', apiAuth, controller.web.profile.changePassword);
|
||||||
|
|
||||||
// 个人中心「绑定微信」(走微信登录网关,扫码绑定 / 解绑)
|
// 个人中心「绑定微信」(走微信登录网关,扫码绑定 / 解绑)
|
||||||
@ -94,6 +95,7 @@ module.exports = (app) => {
|
|||||||
|
|
||||||
// 文档站(简易 CMS):栏目 → 内容页(两级);保存后自动重生成 /doc/** 与 /sitemap.txt
|
// 文档站(简易 CMS):栏目 → 内容页(两级);保存后自动重生成 /doc/** 与 /sitemap.txt
|
||||||
router.get('/api/web/admin/doc/tree', apiAuth, platformAdmin, controller.web.adminDoc.tree);
|
router.get('/api/web/admin/doc/tree', apiAuth, platformAdmin, controller.web.adminDoc.tree);
|
||||||
|
router.post('/api/web/admin/doc/upload-image', apiAuth, platformAdmin, controller.web.adminDoc.uploadImage);
|
||||||
router.post('/api/web/admin/doc/sections', apiAuth, platformAdmin, controller.web.adminDoc.createSection);
|
router.post('/api/web/admin/doc/sections', apiAuth, platformAdmin, controller.web.adminDoc.createSection);
|
||||||
router.put('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.updateSection);
|
router.put('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.updateSection);
|
||||||
router.delete('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroySection);
|
router.delete('/api/web/admin/doc/sections/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroySection);
|
||||||
@ -103,6 +105,11 @@ module.exports = (app) => {
|
|||||||
router.delete('/api/web/admin/doc/articles/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroyArticle);
|
router.delete('/api/web/admin/doc/articles/:id', apiAuth, platformAdmin, controller.web.adminDoc.destroyArticle);
|
||||||
router.post('/api/web/admin/doc/rebuild', apiAuth, platformAdmin, controller.web.adminDoc.rebuild);
|
router.post('/api/web/admin/doc/rebuild', apiAuth, platformAdmin, controller.web.adminDoc.rebuild);
|
||||||
|
|
||||||
|
// 文件存储:COS 图片登记 / 引用状态 / 清理未引用(平台管理员)
|
||||||
|
router.get('/api/web/admin/files', apiAuth, platformAdmin, controller.web.adminFile.index);
|
||||||
|
router.post('/api/web/admin/files/cleanup', apiAuth, platformAdmin, controller.web.adminFile.cleanup);
|
||||||
|
router.delete('/api/web/admin/files/:id', apiAuth, platformAdmin, controller.web.adminFile.destroy);
|
||||||
|
|
||||||
// ---------- Chrome 插件读取(公开只读,无令牌) ----------
|
// ---------- Chrome 插件读取(公开只读,无令牌) ----------
|
||||||
// 只下发:前缀 + 生成好的正则 + 生效站点 + 跳转模板 + 安装包地址;不含任何账号/业务数据。
|
// 只下发:前缀 + 生成好的正则 + 生效站点 + 跳转模板 + 安装包地址;不含任何账号/业务数据。
|
||||||
// 生产若配了 CORS_ORIGINS,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。
|
// 生产若配了 CORS_ORIGINS,记得把 `chrome-extension://<扩展ID>` 加进去(默认 `*` 不用管)。
|
||||||
|
|||||||
410
backend/app/service/file_storage.js
Normal file
410
backend/app/service/file_storage.js
Normal file
@ -0,0 +1,410 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { Service } = require('egg');
|
||||||
|
const COS = require('cos-nodejs-sdk-v5');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 引用来源(SQL EXISTS 片段,`f` 固定指 file_records 别名)
|
||||||
|
*
|
||||||
|
* 引用关系**实时计算**,不单独存引用表:头像改动、文档删改后引用状态立刻更新,
|
||||||
|
* 不会出现「引用行还在、业务数据已删」的脏数据。
|
||||||
|
* 新增业务模块时在这里加一条即可(注意 `f.url` / `f.object_key` 两种匹配方式按需选)。
|
||||||
|
*/
|
||||||
|
const REFERENCE_SOURCES = [
|
||||||
|
{
|
||||||
|
type: 'avatar',
|
||||||
|
label: '用户头像',
|
||||||
|
// 头像存的是完整 URL;同时接受「URL 里包含对象键」,换 CDN 域名后也不会误判成未引用
|
||||||
|
exists: "EXISTS (SELECT 1 FROM users u WHERE u.deleted_at IS NULL AND (u.avatar = f.url OR u.avatar LIKE CONCAT('%', f.object_key, '%')))",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'doc',
|
||||||
|
label: '文档正文',
|
||||||
|
exists: "EXISTS (SELECT 1 FROM doc_articles d WHERE d.deleted_at IS NULL AND d.content LIKE CONCAT('%', f.object_key, '%'))",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const REFERENCED_SQL = `(${REFERENCE_SOURCES.map(source => source.exists).join(' OR ')})`;
|
||||||
|
|
||||||
|
const CATEGORY_TEXT = { avatar: '用户头像', doc: '文档图片' };
|
||||||
|
|
||||||
|
class FileStorageService extends Service {
|
||||||
|
get settings() {
|
||||||
|
return this.config.cos;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 管理端展示用:当前桶 / 地域 / 目录配置(不含任何密钥) */
|
||||||
|
storageMeta() {
|
||||||
|
const { bucket, region, publicUrl, maxFileSize, dirs, cleanupMinAgeHours, secretId, secretKey } = this.settings;
|
||||||
|
return {
|
||||||
|
bucket: bucket || '',
|
||||||
|
region: region || '',
|
||||||
|
publicUrl: publicUrl || '',
|
||||||
|
maxFileSize,
|
||||||
|
dirs,
|
||||||
|
cleanupMinAgeHours,
|
||||||
|
// 密钥没配时上传会 503,页面据此提示运维
|
||||||
|
configured: Boolean(secretId && secretKey && bucket && region && publicUrl),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** COS 客户端(进程内复用) */
|
||||||
|
client() {
|
||||||
|
const { secretId, secretKey } = this.settings;
|
||||||
|
if (!secretId || !secretKey) {
|
||||||
|
this.ctx.throw(503, '图片存储服务尚未配置(COS_SECRET_ID / COS_SECRET_KEY)', { expose: true });
|
||||||
|
}
|
||||||
|
if (!this.app.cosClient) {
|
||||||
|
this.app.cosClient = new COS({ SecretId: secretId, SecretKey: secretKey });
|
||||||
|
}
|
||||||
|
return this.app.cosClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传对象并登记到 file_records
|
||||||
|
*
|
||||||
|
* @param {object} params 上传参数
|
||||||
|
* @param {string} params.key 对象键(含目录前缀)
|
||||||
|
* @param {Buffer} params.body 文件内容
|
||||||
|
* @param {string} params.contentType MIME
|
||||||
|
* @param {string} params.filename 原始文件名
|
||||||
|
* @param {string} params.category avatar / doc
|
||||||
|
* @param {object} [params.uploader] 上传者(user JWT 里的用户)
|
||||||
|
* @return {Promise<object>} 登记后的文件信息
|
||||||
|
*/
|
||||||
|
async uploadObject({ key, body, contentType, filename, category, uploader }) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { bucket, region, publicUrl } = this.settings;
|
||||||
|
if (!bucket || !region || !publicUrl) {
|
||||||
|
ctx.throw(503, '图片存储服务尚未配置(COS_BUCKET / COS_REGION / COS_CDN_URL)', { expose: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.client().putObject({
|
||||||
|
Bucket: bucket,
|
||||||
|
Region: region,
|
||||||
|
Key: key,
|
||||||
|
Body: body,
|
||||||
|
ContentLength: body.length,
|
||||||
|
ContentType: contentType,
|
||||||
|
CacheControl: 'public, max-age=31536000, immutable',
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = `${publicUrl}/${key}`;
|
||||||
|
const hash = crypto.createHash('sha256').update(body).digest('hex');
|
||||||
|
const uploaderId = uploader && uploader.id ? Number(uploader.id) : null;
|
||||||
|
const uploaderName = uploader ? String(uploader.nickname || uploader.username || '').slice(0, 64) : '';
|
||||||
|
|
||||||
|
const [ result ] = await this.app.model.query(
|
||||||
|
`INSERT INTO file_records
|
||||||
|
(object_key, url, file_name, size, mime_type, hash, category, uploader_id, uploader_name, created_at, updated_at)
|
||||||
|
VALUES (:key, :url, :fileName, :size, :mimeType, :hash, :category, :uploaderId, :uploaderName, NOW(), NOW())`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
key,
|
||||||
|
url,
|
||||||
|
fileName: String(filename || '').slice(0, 255),
|
||||||
|
size: body.length,
|
||||||
|
mimeType: contentType,
|
||||||
|
hash,
|
||||||
|
category: category || '',
|
||||||
|
uploaderId,
|
||||||
|
uploaderName,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// Sequelize + mysql 对 INSERT 返回的是自增 ID(不同版本也可能是 `{ insertId }`),两种都兼容
|
||||||
|
const id = Number(typeof result === 'number' ? result : result && result.insertId) || null;
|
||||||
|
|
||||||
|
ctx.logger.info('[file] 上传:id=%s key=%s size=%s', id, key, body.length);
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
key,
|
||||||
|
url,
|
||||||
|
fileName: filename,
|
||||||
|
size: body.length,
|
||||||
|
mimeType: contentType,
|
||||||
|
category: category || '',
|
||||||
|
categoryText: CATEGORY_TEXT[category] || category || '',
|
||||||
|
uploaderId,
|
||||||
|
uploaderName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 删除 COS 对象(对象已不存在视为成功) */
|
||||||
|
async removeObject(key) {
|
||||||
|
const { bucket, region } = this.settings;
|
||||||
|
if (!bucket || !region) {
|
||||||
|
this.ctx.throw(503, '图片存储服务尚未配置(COS_BUCKET / COS_REGION)', { expose: true });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.client().deleteObject({ Bucket: bucket, Region: region, Key: key });
|
||||||
|
} catch (err) {
|
||||||
|
if (err && (err.statusCode === 404 || err.code === 'NoSuchKey')) return;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询(带引用状态与引用明细)
|
||||||
|
*
|
||||||
|
* @param {object} params 查询参数
|
||||||
|
* @param {number} [params.page] 页码(从 1 开始)
|
||||||
|
* @param {number} [params.pageSize] 每页条数
|
||||||
|
* @param {string} [params.keyword] 对象键 / 文件名模糊搜索
|
||||||
|
* @param {string} [params.category] avatar / doc / ''
|
||||||
|
* @param {boolean|''} [params.referenced] true 只看已引用,false 只看未引用,'' 全部
|
||||||
|
* @return {Promise<object>} `{ list, total, page, pageSize, stats }`
|
||||||
|
*/
|
||||||
|
async list({ page = 1, pageSize = 20, keyword = '', category = '', referenced = '' } = {}) {
|
||||||
|
const current = Math.max(Number(page) || 1, 1);
|
||||||
|
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 100);
|
||||||
|
|
||||||
|
const where = [ 'f.deleted_at IS NULL' ];
|
||||||
|
const replacements = {};
|
||||||
|
if (keyword) {
|
||||||
|
where.push('(f.object_key LIKE :keyword OR f.file_name LIKE :keyword)');
|
||||||
|
replacements.keyword = `%${keyword}%`;
|
||||||
|
}
|
||||||
|
if (category) {
|
||||||
|
where.push('f.category = :category');
|
||||||
|
replacements.category = category;
|
||||||
|
}
|
||||||
|
if (referenced === true) where.push(`AND ${REFERENCED_SQL}`);
|
||||||
|
if (referenced === false) where.push(`AND NOT ${REFERENCED_SQL}`);
|
||||||
|
|
||||||
|
// where 里前两项是普通条件,引用条件是整段 AND;这里统一拼成合法 SQL
|
||||||
|
const whereSql = where
|
||||||
|
.map(part => (part.startsWith('AND ') ? part : `AND ${part}`))
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
const [ countRows ] = await this.app.model.query(
|
||||||
|
`SELECT COUNT(*) AS total FROM file_records f WHERE 1 = 1\n${whereSql}`,
|
||||||
|
{ replacements },
|
||||||
|
);
|
||||||
|
const total = Number(countRows[0] && countRows[0].total) || 0;
|
||||||
|
|
||||||
|
const [ rows ] = await this.app.model.query(
|
||||||
|
`SELECT f.id, f.object_key, f.url, f.file_name, f.size, f.mime_type, f.category,
|
||||||
|
f.uploader_id, f.uploader_name, f.created_at,
|
||||||
|
${REFERENCED_SQL} AS referenced
|
||||||
|
FROM file_records f
|
||||||
|
WHERE 1 = 1
|
||||||
|
${whereSql}
|
||||||
|
ORDER BY f.id DESC
|
||||||
|
LIMIT :limit OFFSET :offset`,
|
||||||
|
{
|
||||||
|
replacements: {
|
||||||
|
...replacements,
|
||||||
|
limit: size,
|
||||||
|
offset: (current - 1) * size,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const references = await this.describeReferences(rows);
|
||||||
|
const list = rows.map(row => this.present(row, references.get(row.object_key) || []));
|
||||||
|
|
||||||
|
return {
|
||||||
|
list,
|
||||||
|
total,
|
||||||
|
page: current,
|
||||||
|
pageSize: size,
|
||||||
|
stats: await this.stats(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 已引用 / 未引用的数量与容量统计 */
|
||||||
|
async stats() {
|
||||||
|
const [ rows ] = await this.app.model.query(
|
||||||
|
`SELECT COUNT(*) AS total,
|
||||||
|
COALESCE(SUM(size), 0) AS total_bytes,
|
||||||
|
COALESCE(SUM(referenced), 0) AS referenced_count,
|
||||||
|
COALESCE(SUM(CASE WHEN referenced = 1 THEN size ELSE 0 END), 0) AS referenced_bytes
|
||||||
|
FROM (
|
||||||
|
SELECT f.size, ${REFERENCED_SQL} AS referenced
|
||||||
|
FROM file_records f
|
||||||
|
WHERE f.deleted_at IS NULL
|
||||||
|
) t`,
|
||||||
|
);
|
||||||
|
const row = rows[0] || {};
|
||||||
|
const total = Number(row.total) || 0;
|
||||||
|
const referencedCount = Number(row.referenced_count) || 0;
|
||||||
|
const totalBytes = Number(row.total_bytes) || 0;
|
||||||
|
const referencedBytes = Number(row.referenced_bytes) || 0;
|
||||||
|
return {
|
||||||
|
total,
|
||||||
|
totalBytes,
|
||||||
|
referencedCount,
|
||||||
|
referencedBytes,
|
||||||
|
unreferencedCount: Math.max(total - referencedCount, 0),
|
||||||
|
unreferencedBytes: Math.max(totalBytes - referencedBytes, 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除单个文件(默认拒绝删除仍被引用的文件)
|
||||||
|
*
|
||||||
|
* @param {number} id file_records.id
|
||||||
|
* @param {object} [options] 选项
|
||||||
|
* @param {boolean} [options.force] 已引用也强行删除(会让引用处图片失效)
|
||||||
|
* @return {Promise<object>} `{ id, key }`
|
||||||
|
*/
|
||||||
|
async remove(id, { force = false } = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const [ rows ] = await this.app.model.query(
|
||||||
|
`SELECT f.id, f.object_key, f.url, ${REFERENCED_SQL} AS referenced
|
||||||
|
FROM file_records f
|
||||||
|
WHERE f.id = :id AND f.deleted_at IS NULL
|
||||||
|
LIMIT 1`,
|
||||||
|
{ replacements: { id } },
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (!row) ctx.throw(404, '文件不存在');
|
||||||
|
|
||||||
|
if (Number(row.referenced) && !force) {
|
||||||
|
ctx.throw(409, '该图片仍被引用,确认要删除请带上 force=1');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.removeObject(row.object_key);
|
||||||
|
await this.app.model.query('DELETE FROM file_records WHERE id = :id', { replacements: { id } });
|
||||||
|
ctx.logger.info('[file] 删除:id=%s key=%s force=%s', id, row.object_key, force);
|
||||||
|
return { id: Number(row.id), key: row.object_key };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理「没有任何引用」的历史文件
|
||||||
|
*
|
||||||
|
* 保护措施:
|
||||||
|
* - 只处理上传超过 `minAgeHours` 的文件(默认 24h),避免刚上传还没保存的内容被误删;
|
||||||
|
* - 默认 `dryRun = true`,只返回将被清理的清单;显式传 `false` 才真正删除;
|
||||||
|
* - 单个文件失败不影响其余文件,失败明细原样返回给调用方。
|
||||||
|
*
|
||||||
|
* @param {object} [params] 参数
|
||||||
|
* @param {boolean} [params.dryRun] 是否只预览
|
||||||
|
* @param {number} [params.minAgeHours] 最小存活小时数
|
||||||
|
* @param {number} [params.limit] 单次最多处理多少个
|
||||||
|
* @return {Promise<object>} 清理结果
|
||||||
|
*/
|
||||||
|
async cleanup({ dryRun = true, minAgeHours, limit = 200 } = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const hours = Number.isFinite(Number(minAgeHours)) && Number(minAgeHours) >= 0
|
||||||
|
? Number(minAgeHours)
|
||||||
|
: this.settings.cleanupMinAgeHours;
|
||||||
|
const max = Math.min(Math.max(Number(limit) || 200, 1), 1000);
|
||||||
|
const cutoff = new Date(Date.now() - hours * 3600 * 1000);
|
||||||
|
|
||||||
|
const [ rows ] = await this.app.model.query(
|
||||||
|
`SELECT f.id, f.object_key, f.url, f.file_name, f.size, f.created_at
|
||||||
|
FROM file_records f
|
||||||
|
WHERE f.deleted_at IS NULL
|
||||||
|
AND f.created_at < :cutoff
|
||||||
|
AND NOT ${REFERENCED_SQL}
|
||||||
|
ORDER BY f.created_at ASC
|
||||||
|
LIMIT :max`,
|
||||||
|
{ replacements: { cutoff, max } },
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
dryRun,
|
||||||
|
minAgeHours: hours,
|
||||||
|
candidates: rows.length,
|
||||||
|
bytes: rows.reduce((sum, row) => sum + Number(row.size || 0), 0),
|
||||||
|
deleted: 0,
|
||||||
|
failed: [],
|
||||||
|
items: rows.map(row => ({
|
||||||
|
id: Number(row.id),
|
||||||
|
key: row.object_key,
|
||||||
|
url: row.url,
|
||||||
|
fileName: row.file_name,
|
||||||
|
size: Number(row.size || 0),
|
||||||
|
createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (dryRun) return result;
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
try {
|
||||||
|
await this.removeObject(row.object_key);
|
||||||
|
await this.app.model.query('DELETE FROM file_records WHERE id = :id', { replacements: { id: row.id } });
|
||||||
|
result.deleted += 1;
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.error('[file] 清理失败 id=%s key=%s:%s', row.id, row.object_key, err.message);
|
||||||
|
result.failed.push({ id: Number(row.id), key: row.object_key, message: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.logger.info('[file] 清理未引用文件:候选 %s,成功 %s,失败 %s', rows.length, result.deleted, result.failed.length);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查一页文件的引用明细(两条查询搞定,避免逐行查库)
|
||||||
|
*
|
||||||
|
* @param {Array} rows file_records 行
|
||||||
|
* @return {Promise<Map<string, Array>>} key → `[{ type, label, id }]`
|
||||||
|
*/
|
||||||
|
async describeReferences(rows) {
|
||||||
|
const map = new Map(rows.map(row => [ row.object_key, [] ]));
|
||||||
|
if (!rows.length) return map;
|
||||||
|
|
||||||
|
const urls = rows.map(row => row.url);
|
||||||
|
const byUrl = new Map(rows.map(row => [ row.url, row ]));
|
||||||
|
const [ users ] = await this.app.model.query(
|
||||||
|
'SELECT id, username, nickname, avatar FROM users u WHERE u.avatar IN (:urls) AND u.deleted_at IS NULL',
|
||||||
|
{ replacements: { urls } },
|
||||||
|
);
|
||||||
|
for (const user of users) {
|
||||||
|
const row = byUrl.get(user.avatar);
|
||||||
|
if (!row) continue;
|
||||||
|
map.get(row.object_key).push({
|
||||||
|
type: 'avatar',
|
||||||
|
id: Number(user.id),
|
||||||
|
label: `头像:${user.nickname || user.username || user.id}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const params = {};
|
||||||
|
const conditions = rows.map((row, index) => {
|
||||||
|
params[`k${index}`] = `%${row.object_key}%`;
|
||||||
|
return `d.content LIKE :k${index}`;
|
||||||
|
});
|
||||||
|
const [ docs ] = await this.app.model.query(
|
||||||
|
`SELECT d.id, d.title, d.content FROM doc_articles d
|
||||||
|
WHERE d.deleted_at IS NULL AND (${conditions.join(' OR ')})
|
||||||
|
LIMIT 500`,
|
||||||
|
{ replacements: params },
|
||||||
|
);
|
||||||
|
for (const doc of docs) {
|
||||||
|
for (const row of rows) {
|
||||||
|
if (doc.content && String(doc.content).includes(row.object_key)) {
|
||||||
|
map.get(row.object_key).push({ type: 'doc', id: Number(doc.id), label: `文档:${doc.title}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 行 → 接口返回结构 */
|
||||||
|
present(row, references) {
|
||||||
|
return {
|
||||||
|
id: Number(row.id),
|
||||||
|
key: row.object_key,
|
||||||
|
url: row.url,
|
||||||
|
fileName: row.file_name || '',
|
||||||
|
size: Number(row.size || 0),
|
||||||
|
mimeType: row.mime_type || '',
|
||||||
|
category: row.category || '',
|
||||||
|
categoryText: CATEGORY_TEXT[row.category] || row.category || '其他',
|
||||||
|
uploaderId: row.uploader_id ? Number(row.uploader_id) : null,
|
||||||
|
uploaderName: row.uploader_name || '',
|
||||||
|
createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
|
||||||
|
referenced: Boolean(Number(row.referenced)),
|
||||||
|
references,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = FileStorageService;
|
||||||
78
backend/app/service/image_upload.js
Normal file
78
backend/app/service/image_upload.js
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { Service } = require('egg');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const IMAGE_TYPES = {
|
||||||
|
'.bmp': { mime: 'image/bmp', matches: buffer => buffer.toString('ascii', 0, 2) === 'BM' },
|
||||||
|
'.gif': {
|
||||||
|
mime: 'image/gif',
|
||||||
|
matches: buffer => [ 'GIF87a', 'GIF89a' ].includes(buffer.toString('ascii', 0, 6)),
|
||||||
|
},
|
||||||
|
'.jpeg': { mime: 'image/jpeg', matches: buffer => buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff },
|
||||||
|
'.jpg': { mime: 'image/jpeg', matches: buffer => buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff },
|
||||||
|
'.png': { mime: 'image/png', matches: buffer => buffer.toString('hex', 0, 8) === '89504e470d0a1a0a' },
|
||||||
|
'.webp': {
|
||||||
|
mime: 'image/webp',
|
||||||
|
matches: buffer => buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片上传:校验 → 生成对象键 → 交给 `service/fileStorage` 上传并登记
|
||||||
|
*
|
||||||
|
* 目录前缀来自 `config.cos.dirs`(env `COS_DIR_AVATAR` / `COS_DIR_DOC`),
|
||||||
|
* 需要按业务再分子目录时由调用方传 `dir`(例如头像按用户 ID 分目录)。
|
||||||
|
*/
|
||||||
|
class ImageUploadService extends Service {
|
||||||
|
/**
|
||||||
|
* @param {object} fileStream Egg multipart 文件流
|
||||||
|
* @param {object} [options] 选项
|
||||||
|
* @param {string} [options.category] avatar / doc(决定登记的业务分类)
|
||||||
|
* @param {string} [options.dir] 对象键前缀;不传用 `config.cos.dirs[category]`
|
||||||
|
* @return {Promise<object>} 登记后的文件信息
|
||||||
|
*/
|
||||||
|
async upload(fileStream, { category = 'doc', dir } = {}) {
|
||||||
|
const { ctx, config } = this;
|
||||||
|
const { maxFileSize, dirs } = config.cos;
|
||||||
|
const targetDir = String(dir || dirs[category] || 'images')
|
||||||
|
.replace(/\\/g, '/')
|
||||||
|
.replace(/^\/+|\/+$/g, '');
|
||||||
|
|
||||||
|
const filename = String(fileStream.filename || '').replace(/\\/g, '/').split('/').pop();
|
||||||
|
const extension = path.extname(filename).toLowerCase();
|
||||||
|
const imageType = IMAGE_TYPES[extension];
|
||||||
|
if (!imageType || fileStream.mime !== imageType.mime) {
|
||||||
|
ctx.throw(422, '仅支持 BMP、GIF、JPEG、PNG 或 WebP 图片');
|
||||||
|
}
|
||||||
|
|
||||||
|
const chunks = [];
|
||||||
|
let size = 0;
|
||||||
|
for await (const chunk of fileStream) {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > maxFileSize) {
|
||||||
|
fileStream.destroy();
|
||||||
|
ctx.throw(413, `图片不能超过 ${Math.ceil(maxFileSize / 1024 / 1024)} MB`);
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
const buffer = Buffer.concat(chunks, size);
|
||||||
|
if (!imageType.matches(buffer)) {
|
||||||
|
ctx.throw(422, '图片内容与文件类型不匹配');
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = `${targetDir}/${crypto.randomUUID()}${extension}`;
|
||||||
|
return ctx.service.fileStorage.uploadObject({
|
||||||
|
key,
|
||||||
|
body: buffer,
|
||||||
|
contentType: imageType.mime,
|
||||||
|
filename,
|
||||||
|
category,
|
||||||
|
uploader: ctx.state.user,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ImageUploadService;
|
||||||
@ -56,6 +56,35 @@ module.exports = (appInfo) => {
|
|||||||
buffer: false, // MSI / APK 几十 MB,流式发送
|
buffer: false, // MSI / APK 几十 MB,流式发送
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 图片上传到腾讯云 COS;密钥只从环境变量读取,不进入仓库或接口响应。
|
||||||
|
// 路径(对象键前缀)也走配置:换目录 / 多环境隔离都不需要改代码。
|
||||||
|
const cosBucket = env.COS_BUCKET || '';
|
||||||
|
const cosRegion = env.COS_REGION || '';
|
||||||
|
const trimDir = value => String(value || '').replace(/^\/+|\/+$/g, '');
|
||||||
|
const cosMaxFileSize = Number(env.COS_MAX_FILE_SIZE || 5 * 1024 * 1024);
|
||||||
|
config.cos = {
|
||||||
|
secretId: env.COS_SECRET_ID || '',
|
||||||
|
secretKey: env.COS_SECRET_KEY || '',
|
||||||
|
bucket: cosBucket,
|
||||||
|
region: cosRegion,
|
||||||
|
publicUrl: String(env.COS_CDN_URL || env.COS_PUBLIC_URL || (
|
||||||
|
cosBucket && cosRegion ? `https://${cosBucket}.cos.${cosRegion}.myqcloud.com` : ''
|
||||||
|
)).replace(/\/+$/, ''),
|
||||||
|
// 单张图片上限(字节);multipart 的限制要略大于它,避免框架先一步截断
|
||||||
|
maxFileSize: cosMaxFileSize,
|
||||||
|
// 对象键前缀:头像 / 文档图片分开存,便于按目录清理与配 CDN 规则
|
||||||
|
dirs: {
|
||||||
|
avatar: trimDir(env.COS_DIR_AVATAR || 'images/avatars'),
|
||||||
|
doc: trimDir(env.COS_DIR_DOC || 'images/docs'),
|
||||||
|
},
|
||||||
|
// 「清理未引用图片」只处理上传超过 N 小时的文件:刚上传还没保存文章/资料的不能被误删
|
||||||
|
cleanupMinAgeHours: Math.max(Number(env.COS_CLEANUP_MIN_AGE_HOURS || 24), 0),
|
||||||
|
};
|
||||||
|
config.multipart = {
|
||||||
|
fileSize: `${Math.ceil(cosMaxFileSize / 1024 / 1024)}mb`,
|
||||||
|
files: 1,
|
||||||
|
};
|
||||||
|
|
||||||
// ==================== Chrome 插件(集中配置) ====================
|
// ==================== Chrome 插件(集中配置) ====================
|
||||||
// 插件只拉取执行:`GET /api/web/extension/config`(公开只读,内容由平台管理员在
|
// 插件只拉取执行:`GET /api/web/extension/config`(公开只读,内容由平台管理员在
|
||||||
// `/api/web/admin/extension` 维护,存 sys_config 的 group=extension)。
|
// `/api/web/admin/extension` 维护,存 sys_config 的 group=extension)。
|
||||||
|
|||||||
@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上传文件登记表(file_records)
|
||||||
|
*
|
||||||
|
* 每次上传成功都会登记一行:COS 对象键、访问地址、大小、类型、上传者。
|
||||||
|
* **引用关系不单独存表**:管理端查询时实时判断(用户头像 / 文档正文),
|
||||||
|
* 这样业务侧改动(改头像、删文档)不需要同步维护引用行,也不会出现脏引用。
|
||||||
|
*
|
||||||
|
* 扩展新的引用来源时,只需在 `service/fileStorage` 的 REFERENCE_SOURCES 里加一条 EXISTS 片段。
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
async up(queryInterface, Sequelize) {
|
||||||
|
const { BIGINT, STRING, DATE } = Sequelize;
|
||||||
|
|
||||||
|
await queryInterface.createTable('file_records', {
|
||||||
|
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
|
||||||
|
object_key: { type: STRING(512), allowNull: false, comment: 'COS 对象键(相对路径,唯一)' },
|
||||||
|
url: { type: STRING(512), allowNull: false, comment: '对外访问地址(CDN / COS 域名 + 对象键)' },
|
||||||
|
file_name: { type: STRING(255), allowNull: false, defaultValue: '', comment: '上传时的原始文件名' },
|
||||||
|
size: { type: BIGINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '文件大小(字节)' },
|
||||||
|
mime_type: { type: STRING(100), allowNull: false, defaultValue: '', comment: 'MIME 类型' },
|
||||||
|
hash: { type: STRING(64), allowNull: false, defaultValue: '', comment: '内容 SHA256(校验 / 排查重复)' },
|
||||||
|
category: { type: STRING(32), allowNull: false, defaultValue: '', comment: '业务分类:avatar 头像 / doc 文档图片' },
|
||||||
|
uploader_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '上传者 users.id' },
|
||||||
|
uploader_name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '上传者快照(昵称/用户名)' },
|
||||||
|
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||||
|
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
|
||||||
|
deleted_at: { type: DATE, allowNull: true },
|
||||||
|
}, { comment: '上传文件登记表(COS 对象与引用追踪)' });
|
||||||
|
|
||||||
|
await queryInterface.addIndex('file_records', [ 'object_key' ], {
|
||||||
|
name: 'uk_file_records_key',
|
||||||
|
unique: true,
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex('file_records', [ 'category', 'created_at' ], {
|
||||||
|
name: 'idx_file_records_category_created',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex('file_records', [ 'uploader_id' ], { name: 'idx_file_records_uploader' });
|
||||||
|
},
|
||||||
|
|
||||||
|
async down(queryInterface) {
|
||||||
|
await queryInterface.dropTable('file_records');
|
||||||
|
},
|
||||||
|
};
|
||||||
404
backend/package-lock.json
generated
404
backend/package-lock.json
generated
@ -9,6 +9,7 @@
|
|||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
|
"cos-nodejs-sdk-v5": "^3.0.0",
|
||||||
"egg": "^3.34.0",
|
"egg": "^3.34.0",
|
||||||
"egg-redis": "^2.6.1",
|
"egg-redis": "^2.6.1",
|
||||||
"egg-scripts": "^3.1.0",
|
"egg-scripts": "^3.1.0",
|
||||||
@ -1285,7 +1286,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
|
||||||
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
|
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~8.9.0"
|
"undici-types": "~8.9.0"
|
||||||
}
|
}
|
||||||
@ -1392,6 +1392,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"aix"
|
"aix"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1409,6 +1410,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"darwin"
|
"darwin"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1426,6 +1428,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"darwin"
|
"darwin"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1443,6 +1446,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"freebsd"
|
"freebsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1460,6 +1464,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"freebsd"
|
"freebsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1477,6 +1482,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1494,6 +1500,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1511,6 +1518,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1528,6 +1536,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1545,6 +1554,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1562,6 +1572,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1579,6 +1590,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1596,6 +1608,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"linux"
|
"linux"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1613,6 +1626,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"netbsd"
|
"netbsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1630,6 +1644,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"netbsd"
|
"netbsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1647,6 +1662,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"openbsd"
|
"openbsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1664,6 +1680,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"openbsd"
|
"openbsd"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1681,6 +1698,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"sunos"
|
"sunos"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1698,6 +1716,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1715,6 +1734,7 @@
|
|||||||
"os": [
|
"os": [
|
||||||
"win32"
|
"win32"
|
||||||
],
|
],
|
||||||
|
"peer": true,
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.20.0"
|
"node": ">=16.20.0"
|
||||||
}
|
}
|
||||||
@ -1925,6 +1945,24 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/asn1": {
|
||||||
|
"version": "0.2.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
|
||||||
|
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"safer-buffer": "~2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/assert-plus": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/asynckit": {
|
"node_modules/asynckit": {
|
||||||
"version": "0.4.0",
|
"version": "0.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||||
@ -1958,6 +1996,15 @@
|
|||||||
"node": ">= 6.0.0"
|
"node": ">= 6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/aws-sign2": {
|
||||||
|
"version": "0.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
|
||||||
|
"integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/aws-ssl-profiles": {
|
"node_modules/aws-ssl-profiles": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
||||||
@ -1967,6 +2014,12 @@
|
|||||||
"node": ">= 6.0.0"
|
"node": ">= 6.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/aws4": {
|
||||||
|
"version": "1.13.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
|
||||||
|
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/balanced-match": {
|
"node_modules/balanced-match": {
|
||||||
"version": "1.0.2",
|
"version": "1.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||||
@ -1993,6 +2046,15 @@
|
|||||||
],
|
],
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/bcrypt-pbkdf": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"tweetnacl": "^0.14.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/bcryptjs": {
|
"node_modules/bcryptjs": {
|
||||||
"version": "3.0.3",
|
"version": "3.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
||||||
@ -2274,6 +2336,12 @@
|
|||||||
"upper-case-first": "^2.0.2"
|
"upper-case-first": "^2.0.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/caseless": {
|
||||||
|
"version": "0.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
|
||||||
|
"integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==",
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
"node_modules/cfork": {
|
"node_modules/cfork": {
|
||||||
"version": "1.11.0",
|
"version": "1.11.0",
|
||||||
"resolved": "https://registry.npmjs.org/cfork/-/cfork-1.11.0.tgz",
|
"resolved": "https://registry.npmjs.org/cfork/-/cfork-1.11.0.tgz",
|
||||||
@ -3152,6 +3220,87 @@
|
|||||||
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cos-fast-xml-parser": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cos-fast-xml-parser/-/cos-fast-xml-parser-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-kOPJb1cuj+gc5E8jN5ekZn4rgQHaxYTLcQT+jmbHtlTNcNjv7wnOBEYH2uRA0pG3h8giot4z9h4WFLDuXATZwg==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/NaturalIntelligence"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"strnum": "^1.0.5"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"fxparser": "src/cli/cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cos-nodejs-sdk-v5": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/cos-nodejs-sdk-v5/-/cos-nodejs-sdk-v5-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-xUqiDdUxfEjfaWoyBA3qsSnlQVHPz13DRFErL+NliadBVUeeZhAPHGVa2inGpUvPTOs52ALIKkMbzL+inSqvXg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"cos-fast-xml-parser": "^1.0.0",
|
||||||
|
"cos-request": "^1.3.0",
|
||||||
|
"mime-types": "^2.1.35"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 9"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cos-request": {
|
||||||
|
"version": "1.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/cos-request/-/cos-request-1.3.3.tgz",
|
||||||
|
"integrity": "sha512-zD7fKMAIMfJNHssx8VZE5mUQ67hs3QDi7S2BX7JuD8MzT1XYqEOAN42PJ0BtRhgutnn+8HiUF+Fup+j5zORasQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"aws-sign2": "~0.7.0",
|
||||||
|
"aws4": "^1.8.0",
|
||||||
|
"caseless": "~0.12.0",
|
||||||
|
"combined-stream": "~1.0.6",
|
||||||
|
"extend": "~3.0.2",
|
||||||
|
"forever-agent": "~0.6.1",
|
||||||
|
"form-data": "~2.5.6",
|
||||||
|
"http-signature": "~1.2.0",
|
||||||
|
"is-typedarray": "~1.0.0",
|
||||||
|
"isstream": "~0.1.2",
|
||||||
|
"json-stringify-safe": "~5.0.1",
|
||||||
|
"mime-types": "~2.1.19",
|
||||||
|
"oauth-sign": "~0.9.0",
|
||||||
|
"performance-now": "^2.1.0",
|
||||||
|
"qs": "^6.15.2",
|
||||||
|
"safe-buffer": "^5.1.2",
|
||||||
|
"tough-cookie": "~4.1.4",
|
||||||
|
"tunnel-agent": "^0.6.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cos-request/node_modules/form-data": {
|
||||||
|
"version": "2.5.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.6.tgz",
|
||||||
|
"integrity": "sha512-Ogz/E85h9tlfJzpI6TuFpGcHZFhLrb9Gw8wq9v40CxSCPnv7ahKr6Xgtkn0KYCDQJ8DNn5VoMO8EXr9V5PadyA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.8",
|
||||||
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"hasown": "^2.0.4",
|
||||||
|
"mime-types": "^2.1.35",
|
||||||
|
"safe-buffer": "^5.2.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/crc": {
|
"node_modules/crc": {
|
||||||
"version": "3.8.0",
|
"version": "3.8.0",
|
||||||
"resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz",
|
"resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz",
|
||||||
@ -3227,6 +3376,18 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dashdash": {
|
||||||
|
"version": "1.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
|
||||||
|
"integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assert-plus": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/dateformat": {
|
"node_modules/dateformat": {
|
||||||
"version": "4.6.3",
|
"version": "4.6.3",
|
||||||
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
|
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
|
||||||
@ -3561,6 +3722,16 @@
|
|||||||
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
|
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/ecc-jsbn": {
|
||||||
|
"version": "0.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
|
||||||
|
"integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"jsbn": "~0.1.0",
|
||||||
|
"safer-buffer": "^2.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ecdsa-sig-formatter": {
|
"node_modules/ecdsa-sig-formatter": {
|
||||||
"version": "1.0.11",
|
"version": "1.0.11",
|
||||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||||
@ -3635,7 +3806,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/egg/-/egg-3.34.0.tgz",
|
"resolved": "https://registry.npmjs.org/egg/-/egg-3.34.0.tgz",
|
||||||
"integrity": "sha512-Zs4gwrp/iY7Vkdfm4/UTy1cZrEcWuK9ZiBix30Sco5ennR6k7TcsssYfIS40lgVvI7U4HwcR9HOmhYML3A0A3w==",
|
"integrity": "sha512-Zs4gwrp/iY7Vkdfm4/UTy1cZrEcWuK9ZiBix30Sco5ennR6k7TcsssYfIS40lgVvI7U4HwcR9HOmhYML3A0A3w==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@types/accepts": "^1.3.5",
|
"@types/accepts": "^1.3.5",
|
||||||
"@types/koa": "^2.13.5",
|
"@types/koa": "^2.13.5",
|
||||||
@ -4050,7 +4220,6 @@
|
|||||||
"resolved": "https://registry.npmjs.org/egg-mock/-/egg-mock-5.15.2.tgz",
|
"resolved": "https://registry.npmjs.org/egg-mock/-/egg-mock-5.15.2.tgz",
|
||||||
"integrity": "sha512-8g+GzGcjfPaM/XwGaoej27wfIw7qeKR3tqYZPB3mIRWMzChYnyI2Bb+5qud23Ealj0raNamE+85ZsBKI2kq8nw==",
|
"integrity": "sha512-8g+GzGcjfPaM/XwGaoej27wfIw7qeKR3tqYZPB3mIRWMzChYnyI2Bb+5qud23Ealj0raNamE+85ZsBKI2kq8nw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eggjs/utils": "^4.0.2",
|
"@eggjs/utils": "^4.0.2",
|
||||||
"@types/supertest": "^2.0.7",
|
"@types/supertest": "^2.0.7",
|
||||||
@ -4802,6 +4971,15 @@
|
|||||||
"integrity": "sha512-ISoKeVhtewd5YHzMo+r9KC3Zx0fdpNBqoRzot+6BeEQ3bWQYQQOt0jkkY5gLveI2e7j+vdCJKeszHJIbg2Uceg==",
|
"integrity": "sha512-ISoKeVhtewd5YHzMo+r9KC3Zx0fdpNBqoRzot+6BeEQ3bWQYQQOt0jkkY5gLveI2e7j+vdCJKeszHJIbg2Uceg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/extsprintf": {
|
||||||
|
"version": "1.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
|
||||||
|
"integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==",
|
||||||
|
"engines": [
|
||||||
|
"node >=0.6.0"
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/fast-glob": {
|
"node_modules/fast-glob": {
|
||||||
"version": "3.3.3",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||||
@ -4984,6 +5162,15 @@
|
|||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/forever-agent": {
|
||||||
|
"version": "0.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
|
||||||
|
"integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/form-data": {
|
"node_modules/form-data": {
|
||||||
"version": "4.0.6",
|
"version": "4.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
|
||||||
@ -5229,6 +5416,15 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/getpass": {
|
||||||
|
"version": "0.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
|
||||||
|
"integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assert-plus": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "8.1.0",
|
"version": "8.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz",
|
||||||
@ -5483,6 +5679,21 @@
|
|||||||
"node": ">=8.0.0"
|
"node": ">=8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/http-signature": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"jsprim": "^1.2.2",
|
||||||
|
"sshpk": "^1.7.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8",
|
||||||
|
"npm": ">=1.3.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/human-signals": {
|
"node_modules/human-signals": {
|
||||||
"version": "2.1.0",
|
"version": "2.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz",
|
||||||
@ -5929,6 +6140,12 @@
|
|||||||
"integrity": "sha512-72axShMJMnMy5HSU/jLGNOonZD5rWM0MwJSCYpKCTQCbggQZBJO/CLMMVP5HgS8kPSYFBkTysJexsD6NMvGKDQ==",
|
"integrity": "sha512-72axShMJMnMy5HSU/jLGNOonZD5rWM0MwJSCYpKCTQCbggQZBJO/CLMMVP5HgS8kPSYFBkTysJexsD6NMvGKDQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/is-typedarray": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/is-unicode-supported": {
|
"node_modules/is-unicode-supported": {
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz",
|
||||||
@ -6239,6 +6456,18 @@
|
|||||||
"js-yaml": "bin/js-yaml.js"
|
"js-yaml": "bin/js-yaml.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/jsbn": {
|
||||||
|
"version": "0.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
|
||||||
|
"integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/json-schema": {
|
||||||
|
"version": "0.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
|
||||||
|
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
|
||||||
|
"license": "(AFL-2.1 OR BSD-3-Clause)"
|
||||||
|
},
|
||||||
"node_modules/json-stringify-safe": {
|
"node_modules/json-stringify-safe": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
|
||||||
@ -6312,6 +6541,21 @@
|
|||||||
"node": ">=10"
|
"node": ">=10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/jsprim": {
|
||||||
|
"version": "1.4.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",
|
||||||
|
"integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assert-plus": "1.0.0",
|
||||||
|
"extsprintf": "1.3.0",
|
||||||
|
"json-schema": "0.4.0",
|
||||||
|
"verror": "1.10.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.6.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/jwa": {
|
"node_modules/jwa": {
|
||||||
"version": "2.0.1",
|
"version": "2.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
||||||
@ -7899,6 +8143,15 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/oauth-sign": {
|
||||||
|
"version": "0.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
|
||||||
|
"integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/object-assign": {
|
"node_modules/object-assign": {
|
||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||||
@ -8306,6 +8559,12 @@
|
|||||||
"through": "~2.3"
|
"through": "~2.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/performance-now": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/pg-connection-string": {
|
"node_modules/pg-connection-string": {
|
||||||
"version": "2.14.1",
|
"version": "2.14.1",
|
||||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||||
@ -8454,6 +8713,18 @@
|
|||||||
"node": ">= 0.10"
|
"node": ">= 0.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/psl": {
|
||||||
|
"version": "1.15.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
|
||||||
|
"integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"punycode": "^2.3.1"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/lupomontero"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/pump": {
|
"node_modules/pump": {
|
||||||
"version": "3.0.4",
|
"version": "3.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
|
||||||
@ -8485,6 +8756,15 @@
|
|||||||
"once": "^1.3.1"
|
"once": "^1.3.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/punycode": {
|
||||||
|
"version": "2.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||||
|
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/qrcode-generator": {
|
"node_modules/qrcode-generator": {
|
||||||
"version": "2.0.4",
|
"version": "2.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-2.0.4.tgz",
|
||||||
@ -8507,6 +8787,12 @@
|
|||||||
"url": "https://github.com/sponsors/ljharb"
|
"url": "https://github.com/sponsors/ljharb"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/querystringify": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/queue-microtask": {
|
"node_modules/queue-microtask": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||||
@ -8704,8 +8990,7 @@
|
|||||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz",
|
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.14.tgz",
|
||||||
"integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==",
|
"integrity": "sha512-ZhYeb6nRaXCfhnndflDK8qI6ZQ/YcWZCISRAWICW9XYqMUwjZM9Z0DveWX/ABN01oxSHwVxKQmxeYZSsm0jh5A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/require-directory": {
|
"node_modules/require-directory": {
|
||||||
"version": "2.1.1",
|
"version": "2.1.1",
|
||||||
@ -9550,6 +9835,31 @@
|
|||||||
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/sshpk": {
|
||||||
|
"version": "1.18.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz",
|
||||||
|
"integrity": "sha512-2p2KJZTSqQ/I3+HX42EpYOa2l3f8Erv8MWKsy2I9uf4wA7yFIkXRffYdsx86y6z4vHtV8u7g+pPlr8/4ouAxsQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"asn1": "~0.2.3",
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"bcrypt-pbkdf": "^1.0.0",
|
||||||
|
"dashdash": "^1.12.0",
|
||||||
|
"ecc-jsbn": "~0.1.1",
|
||||||
|
"getpass": "^0.1.1",
|
||||||
|
"jsbn": "~0.1.0",
|
||||||
|
"safer-buffer": "^2.0.2",
|
||||||
|
"tweetnacl": "~0.14.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"sshpk-conv": "bin/sshpk-conv",
|
||||||
|
"sshpk-sign": "bin/sshpk-sign",
|
||||||
|
"sshpk-verify": "bin/sshpk-verify"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/stack-trace": {
|
"node_modules/stack-trace": {
|
||||||
"version": "0.0.10",
|
"version": "0.0.10",
|
||||||
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
|
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
|
||||||
@ -9708,6 +10018,18 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/strnum": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/NaturalIntelligence"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/superagent": {
|
"node_modules/superagent": {
|
||||||
"version": "8.1.2",
|
"version": "8.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/superagent/-/superagent-8.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/superagent/-/superagent-8.1.2.tgz",
|
||||||
@ -10113,6 +10435,30 @@
|
|||||||
"integrity": "sha512-OsLcGGbYF3rMjPUf8oKktyvCiUxSbqMMS39m33MAjLTC1DVIH6x3WSt63/M77ihI09+Sdfk1AXvfhCEeUmC7mg==",
|
"integrity": "sha512-OsLcGGbYF3rMjPUf8oKktyvCiUxSbqMMS39m33MAjLTC1DVIH6x3WSt63/M77ihI09+Sdfk1AXvfhCEeUmC7mg==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/tough-cookie": {
|
||||||
|
"version": "4.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
|
||||||
|
"integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==",
|
||||||
|
"license": "BSD-3-Clause",
|
||||||
|
"dependencies": {
|
||||||
|
"psl": "^1.1.33",
|
||||||
|
"punycode": "^2.1.1",
|
||||||
|
"universalify": "^0.2.0",
|
||||||
|
"url-parse": "^1.5.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tough-cookie/node_modules/universalify": {
|
||||||
|
"version": "0.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
|
||||||
|
"integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ts-node": {
|
"node_modules/ts-node": {
|
||||||
"version": "10.9.2",
|
"version": "10.9.2",
|
||||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
|
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
|
||||||
@ -10196,6 +10542,24 @@
|
|||||||
"node": ">=0.6.x"
|
"node": ">=0.6.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tunnel-agent": {
|
||||||
|
"version": "0.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
|
||||||
|
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"safe-buffer": "^5.0.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tweetnacl": {
|
||||||
|
"version": "0.14.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
|
||||||
|
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
|
||||||
|
"license": "Unlicense"
|
||||||
|
},
|
||||||
"node_modules/type-fest": {
|
"node_modules/type-fest": {
|
||||||
"version": "3.13.1",
|
"version": "3.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-3.13.1.tgz",
|
||||||
@ -10364,6 +10728,16 @@
|
|||||||
"integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==",
|
"integrity": "sha512-HXgFDgDommxn5/bIv0cnQZsPhHDA90NPHD6+c/v21U5+Sx5hoP8+dP9IZXBU1gIfvdRfhG8cel9QNPeionfcCQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/url-parse": {
|
||||||
|
"version": "1.5.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
|
||||||
|
"integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"querystringify": "^2.1.1",
|
||||||
|
"requires-port": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/urllib": {
|
"node_modules/urllib": {
|
||||||
"version": "2.44.1",
|
"version": "2.44.1",
|
||||||
"resolved": "https://registry.npmjs.org/urllib/-/urllib-2.44.1.tgz",
|
"resolved": "https://registry.npmjs.org/urllib/-/urllib-2.44.1.tgz",
|
||||||
@ -10594,6 +10968,26 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/verror": {
|
||||||
|
"version": "1.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
|
||||||
|
"integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==",
|
||||||
|
"engines": [
|
||||||
|
"node >=0.6.0"
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assert-plus": "^1.0.0",
|
||||||
|
"core-util-is": "1.0.2",
|
||||||
|
"extsprintf": "^1.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/verror/node_modules/core-util-is": {
|
||||||
|
"version": "1.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
|
||||||
|
"integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/wcwidth": {
|
"node_modules/wcwidth": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",
|
||||||
|
|||||||
@ -8,6 +8,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
|
"cos-nodejs-sdk-v5": "^3.0.0",
|
||||||
"egg": "^3.34.0",
|
"egg": "^3.34.0",
|
||||||
"egg-redis": "^2.6.1",
|
"egg-redis": "^2.6.1",
|
||||||
"egg-scripts": "^3.1.0",
|
"egg-scripts": "^3.1.0",
|
||||||
|
|||||||
142
backend/test/app/controller/admin_file.test.js
Normal file
142
backend/test/app/controller/admin_file.test.js
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||||
|
|
||||||
|
/** 造一个可用的平台管理员令牌(apiAuth + platformAdmin 都放行) */
|
||||||
|
function adminToken(user = { id: 1, username: 'admin', nickname: '管理员', status: 1 }) {
|
||||||
|
mock(app, 'model', {
|
||||||
|
User: {
|
||||||
|
async findByPk() {
|
||||||
|
return { toJSON: () => user };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
app.mockService('adminMember', 'isAdmin', async () => true);
|
||||||
|
return app.createAnonymousContext().service.jwt.signUser(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('test/app/controller/admin_file.test.js', () => {
|
||||||
|
it('GET /api/web/admin/files:透传分页与引用过滤,返回统计与存储配置', async () => {
|
||||||
|
const token = adminToken();
|
||||||
|
let received = null;
|
||||||
|
app.mockService('fileStorage', 'list', async params => {
|
||||||
|
received = params;
|
||||||
|
return {
|
||||||
|
list: [ { id: 1, key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', referenced: false, references: [] } ],
|
||||||
|
total: 1,
|
||||||
|
page: 2,
|
||||||
|
pageSize: 10,
|
||||||
|
stats: { total: 1, totalBytes: 10, referencedCount: 0, referencedBytes: 0, unreferencedCount: 1, unreferencedBytes: 10 },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
app.mockService('fileStorage', 'storageMeta', () => ({
|
||||||
|
bucket: 'test-bucket-123456',
|
||||||
|
region: 'ap-guangzhou',
|
||||||
|
publicUrl: 'https://images.example.com',
|
||||||
|
maxFileSize: 5242880,
|
||||||
|
dirs: { avatar: 'images/avatars', doc: 'images/docs' },
|
||||||
|
cleanupMinAgeHours: 24,
|
||||||
|
configured: true,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const res = await app.httpRequest()
|
||||||
|
.get('/api/web/admin/files?page=2&pageSize=10&keyword=a&category=doc&referenced=0')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(received.page === 2 && received.pageSize === 10, JSON.stringify(received));
|
||||||
|
assert(received.keyword === 'a' && received.category === 'doc' && received.referenced === false, JSON.stringify(received));
|
||||||
|
assert(res.body.data.total === 1 && res.body.data.stats.unreferencedCount === 1, JSON.stringify(res.body));
|
||||||
|
assert(res.body.data.storage.bucket === 'test-bucket-123456');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/web/admin/files:pageSize 超过 100 时收敛到 100', async () => {
|
||||||
|
const token = adminToken();
|
||||||
|
let received = null;
|
||||||
|
app.mockService('fileStorage', 'list', async params => {
|
||||||
|
received = params;
|
||||||
|
return { list: [], total: 0, page: 1, pageSize: 100, stats: {} };
|
||||||
|
});
|
||||||
|
app.mockService('fileStorage', 'storageMeta', () => ({}));
|
||||||
|
|
||||||
|
await app.httpRequest()
|
||||||
|
.get('/api/web/admin/files?pageSize=9999')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(received.pageSize === 100, JSON.stringify(received));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /api/web/admin/files/cleanup:不传 dryRun 时按预览处理', async () => {
|
||||||
|
const token = adminToken();
|
||||||
|
let received = null;
|
||||||
|
app.mockService('fileStorage', 'cleanup', async params => {
|
||||||
|
received = params;
|
||||||
|
return { dryRun: params.dryRun, minAgeHours: 24, candidates: 0, bytes: 0, deleted: 0, failed: [], items: [] };
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.httpRequest()
|
||||||
|
.post('/api/web/admin/files/cleanup')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.send({})
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(received.dryRun === true, '默认必须是安全的预览模式');
|
||||||
|
assert(res.body.data.dryRun === true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST /api/web/admin/files/cleanup:dryRun=false 才真删,并透传保护期', async () => {
|
||||||
|
const token = adminToken();
|
||||||
|
let received = null;
|
||||||
|
app.mockService('fileStorage', 'cleanup', async params => {
|
||||||
|
received = params;
|
||||||
|
return { dryRun: false, minAgeHours: 6, candidates: 2, bytes: 20, deleted: 2, failed: [], items: [] };
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.httpRequest()
|
||||||
|
.post('/api/web/admin/files/cleanup')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.send({ dryRun: false, minAgeHours: 6, limit: 50 })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(received.dryRun === false && received.minAgeHours === 6 && received.limit === 50, JSON.stringify(received));
|
||||||
|
assert(res.body.data.deleted === 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('DELETE /api/web/admin/files/:id:id 非法 400,force 参数透传', async () => {
|
||||||
|
const token = adminToken();
|
||||||
|
|
||||||
|
await app.httpRequest()
|
||||||
|
.delete('/api/web/admin/files/abc')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(400);
|
||||||
|
|
||||||
|
let received = null;
|
||||||
|
app.mockService('fileStorage', 'remove', async (id, options) => {
|
||||||
|
received = { id, options };
|
||||||
|
return { id, key: 'images/docs/a.png' };
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.httpRequest()
|
||||||
|
.delete('/api/web/admin/files/7?force=1')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(received.id === 7 && received.options.force === true, JSON.stringify(received));
|
||||||
|
assert(res.body.data.key === 'images/docs/a.png');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('非平台管理员访问存储管理接口 → 403', async () => {
|
||||||
|
const user = { id: 5, username: 'member', status: 1 };
|
||||||
|
mock(app, 'model', { User: { async findByPk() { return { toJSON: () => user }; } } });
|
||||||
|
app.mockService('adminMember', 'isAdmin', async () => false);
|
||||||
|
const token = app.createAnonymousContext().service.jwt.signUser(user);
|
||||||
|
|
||||||
|
const res = await app.httpRequest()
|
||||||
|
.get('/api/web/admin/files')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(403);
|
||||||
|
|
||||||
|
assert(res.body.status === 'not_platform_admin', JSON.stringify(res.body));
|
||||||
|
});
|
||||||
|
});
|
||||||
34
backend/test/app/controller/image_upload.test.js
Normal file
34
backend/test/app/controller/image_upload.test.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||||
|
|
||||||
|
describe('test/app/controller/image_upload.test.js', () => {
|
||||||
|
it('accepts one authenticated multipart avatar and scopes it to the current user', async () => {
|
||||||
|
const user = { id: 17, username: 'member', status: 1, passwordChangedAt: null };
|
||||||
|
mock(app, 'model', {
|
||||||
|
User: {
|
||||||
|
async findByPk() {
|
||||||
|
return { toJSON: () => user };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let upload = null;
|
||||||
|
app.mockService('imageUpload', 'upload', async (fileStream, options) => {
|
||||||
|
upload = { filename: fileStream.filename, mime: fileStream.mime, options };
|
||||||
|
return { key: 'images/avatars/17/photo.png', url: 'https://images.example.com/photo.png' };
|
||||||
|
});
|
||||||
|
|
||||||
|
const token = app.createAnonymousContext().service.jwt.signUser(user);
|
||||||
|
const response = await app.httpRequest()
|
||||||
|
.post('/api/web/me/avatar')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.attach('file', Buffer.from('png'), { filename: 'photo.png', contentType: 'image/png' })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
assert(upload.filename === 'photo.png' && upload.mime === 'image/png', JSON.stringify(upload));
|
||||||
|
assert(upload.options.category === 'avatar', JSON.stringify(upload.options));
|
||||||
|
assert(upload.options.dir === `${app.config.cos.dirs.avatar}/17`, JSON.stringify(upload.options));
|
||||||
|
assert(response.body.data.url === 'https://images.example.com/photo.png', JSON.stringify(response.body));
|
||||||
|
});
|
||||||
|
});
|
||||||
226
backend/test/app/service/file_storage.test.js
Normal file
226
backend/test/app/service/file_storage.test.js
Normal file
@ -0,0 +1,226 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||||
|
|
||||||
|
function configureCos() {
|
||||||
|
const config = app.config.cos;
|
||||||
|
mock(config, 'secretId', 'test-secret-id');
|
||||||
|
mock(config, 'secretKey', 'test-secret-key');
|
||||||
|
mock(config, 'bucket', 'test-bucket-123456');
|
||||||
|
mock(config, 'region', 'ap-guangzhou');
|
||||||
|
mock(config, 'publicUrl', 'https://images.example.com');
|
||||||
|
mock(config, 'cleanupMinAgeHours', 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件登记 / 引用判定 / 清理
|
||||||
|
*
|
||||||
|
* 用假 `app.model.query` 模拟 SQL 结果:重点验证查询分支与「引用保护」逻辑,
|
||||||
|
* 不依赖真实 MySQL。
|
||||||
|
*/
|
||||||
|
describe('test/app/service/file_storage.test.js', () => {
|
||||||
|
it('上传后登记一行,并返回访问地址与上传者快照', async () => {
|
||||||
|
configureCos();
|
||||||
|
let inserted = null;
|
||||||
|
mock(app, 'cosClient', {
|
||||||
|
async putObject(options) {
|
||||||
|
this.uploaded = options;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql, options) {
|
||||||
|
if (sql.startsWith('INSERT INTO file_records')) {
|
||||||
|
inserted = options.replacements;
|
||||||
|
return [ 9, 1 ];
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await app.createAnonymousContext().service.fileStorage.uploadObject({
|
||||||
|
key: 'images/docs/a.png',
|
||||||
|
body: Buffer.from('89504e470d0a1a0a', 'hex'),
|
||||||
|
contentType: 'image/png',
|
||||||
|
filename: 'a.png',
|
||||||
|
category: 'doc',
|
||||||
|
uploader: { id: 17, nickname: '小林' },
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(inserted.key === 'images/docs/a.png' && inserted.uploaderId === 17, JSON.stringify(inserted));
|
||||||
|
assert(inserted.uploaderName === '小林' && inserted.size === 8, JSON.stringify(inserted));
|
||||||
|
assert(result.id === 9 && result.url === 'https://images.example.com/images/docs/a.png');
|
||||||
|
assert(app.cosClient.uploaded.Bucket === 'test-bucket-123456');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('COS 凭证缺失时上传返回可读的 503', async () => {
|
||||||
|
configureCos();
|
||||||
|
mock(app.config.cos, 'secretId', '');
|
||||||
|
|
||||||
|
let error = null;
|
||||||
|
try {
|
||||||
|
await app.createAnonymousContext().service.fileStorage.uploadObject({
|
||||||
|
key: 'images/docs/a.png',
|
||||||
|
body: Buffer.from('x'),
|
||||||
|
contentType: 'image/png',
|
||||||
|
filename: 'a.png',
|
||||||
|
category: 'doc',
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
error = err;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(error && error.status === 503 && error.expose, '缺少凭证要给运维看得见的错误');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('列表按引用条件分页,并给出引用明细与统计', async () => {
|
||||||
|
configureCos();
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql) {
|
||||||
|
// 统计 SQL 里也带引用子查询(含 users / doc_articles),必须先判断
|
||||||
|
if (sql.includes('AS total_bytes')) {
|
||||||
|
return [ [{ total: 2, total_bytes: 150, referenced_count: 1, referenced_bytes: 100 }], [] ];
|
||||||
|
}
|
||||||
|
if (sql.includes('COUNT(*) AS total FROM file_records f')) return [ [{ total: 2 }], [] ];
|
||||||
|
if (sql.includes('ORDER BY f.id DESC')) {
|
||||||
|
return [ [
|
||||||
|
{ id: 2, object_key: 'images/docs/used.png', url: 'https://images.example.com/images/docs/used.png', file_name: 'used.png', size: 100, mime_type: 'image/png', category: 'doc', uploader_id: 17, uploader_name: '小林', created_at: new Date('2026-11-20T02:00:00Z'), referenced: 1 },
|
||||||
|
{ id: 1, object_key: 'images/docs/orphan.png', url: 'https://images.example.com/images/docs/orphan.png', file_name: 'orphan.png', size: 50, mime_type: 'image/png', category: 'doc', uploader_id: null, uploader_name: '', created_at: new Date('2026-11-20T01:00:00Z'), referenced: 0 },
|
||||||
|
], [] ];
|
||||||
|
}
|
||||||
|
if (sql.includes('FROM users u')) {
|
||||||
|
return [ [{ id: 17, username: 'lin', nickname: '小林', avatar: 'https://images.example.com/images/docs/used.png' }], [] ];
|
||||||
|
}
|
||||||
|
if (sql.includes('FROM doc_articles d')) {
|
||||||
|
return [ [{ id: 3, title: '快速开始', content: '' }], [] ];
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await app.createAnonymousContext().service.fileStorage.list({ page: 1, pageSize: 20 });
|
||||||
|
|
||||||
|
assert(data.total === 2 && data.list.length === 2, JSON.stringify(data));
|
||||||
|
const [ used, orphan ] = data.list;
|
||||||
|
assert(used.referenced === true && used.references.length === 2, JSON.stringify(used));
|
||||||
|
assert(used.references.some(item => item.type === 'avatar') && used.references.some(item => item.type === 'doc'));
|
||||||
|
assert(orphan.referenced === false && orphan.references.length === 0);
|
||||||
|
assert(data.stats.unreferencedCount === 1 && data.stats.unreferencedBytes === 50, JSON.stringify(data.stats));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('未引用过滤:referenced=false 时 SQL 带 NOT EXISTS 条件', async () => {
|
||||||
|
configureCos();
|
||||||
|
const sqls = [];
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql) {
|
||||||
|
sqls.push(sql);
|
||||||
|
if (sql.includes('AS total_bytes')) {
|
||||||
|
return [ [{ total: 0, total_bytes: 0, referenced_count: 0, referenced_bytes: 0 }], [] ];
|
||||||
|
}
|
||||||
|
if (sql.includes('COUNT(*) AS total FROM file_records f')) return [ [{ total: 0 }], [] ];
|
||||||
|
if (sql.includes('ORDER BY f.id DESC')) return [ [], [] ];
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.createAnonymousContext().service.fileStorage.list({ referenced: false });
|
||||||
|
|
||||||
|
assert(sqls.some(sql => sql.includes('AND NOT (EXISTS')), sqls.join('\n---\n'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除仍被引用的文件默认拒绝,force 才真删', async () => {
|
||||||
|
configureCos();
|
||||||
|
const executed = [];
|
||||||
|
let deletedObject = null;
|
||||||
|
mock(app, 'cosClient', {
|
||||||
|
async deleteObject(options) {
|
||||||
|
deletedObject = options.Key;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql, options) {
|
||||||
|
executed.push(sql);
|
||||||
|
if (sql.includes('WHERE f.id = :id')) {
|
||||||
|
return [ [{ id: 5, object_key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', referenced: 1 }], [] ];
|
||||||
|
}
|
||||||
|
if (sql.startsWith('DELETE FROM file_records')) return [ { affectedRows: 1 }, [] ];
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = app.createAnonymousContext();
|
||||||
|
let error = null;
|
||||||
|
try {
|
||||||
|
await ctx.service.fileStorage.remove(5);
|
||||||
|
} catch (err) {
|
||||||
|
error = err;
|
||||||
|
}
|
||||||
|
assert(error && error.status === 409, '有引用时必须拒绝');
|
||||||
|
assert(deletedObject === null, '拒绝时不能动 COS');
|
||||||
|
|
||||||
|
const result = await ctx.service.fileStorage.remove(5, { force: true });
|
||||||
|
assert(result.key === 'images/docs/a.png' && deletedObject === 'images/docs/a.png');
|
||||||
|
assert(executed.some(sql => sql.startsWith('DELETE FROM file_records')), 'force 时应删登记行');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('清理:dryRun 只给清单,执行时才删 COS 与登记行', async () => {
|
||||||
|
configureCos();
|
||||||
|
const deletedKeys = [];
|
||||||
|
const deletedRows = [];
|
||||||
|
mock(app, 'cosClient', {
|
||||||
|
async deleteObject(options) {
|
||||||
|
deletedKeys.push(options.Key);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql, options) {
|
||||||
|
if (sql.includes('f.created_at < :cutoff')) {
|
||||||
|
return [ [
|
||||||
|
{ id: 11, object_key: 'images/docs/a.png', url: 'https://images.example.com/images/docs/a.png', file_name: 'a.png', size: 10, created_at: new Date('2026-11-01T00:00:00Z') },
|
||||||
|
], [] ];
|
||||||
|
}
|
||||||
|
if (sql.startsWith('DELETE FROM file_records')) {
|
||||||
|
deletedRows.push(options.replacements.id);
|
||||||
|
return [ { affectedRows: 1 }, [] ];
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const ctx = app.createAnonymousContext();
|
||||||
|
const preview = await ctx.service.fileStorage.cleanup({ dryRun: true });
|
||||||
|
|
||||||
|
assert(preview.dryRun === true && preview.candidates === 1 && preview.bytes === 10, JSON.stringify(preview));
|
||||||
|
assert(deletedKeys.length === 0 && deletedRows.length === 0, 'dryRun 不能产生删除');
|
||||||
|
|
||||||
|
const result = await ctx.service.fileStorage.cleanup({ dryRun: false, minAgeHours: 1 });
|
||||||
|
|
||||||
|
assert(result.deleted === 1 && result.failed.length === 0, JSON.stringify(result));
|
||||||
|
assert(deletedKeys[0] === 'images/docs/a.png' && deletedRows[0] === 11);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('清理时单个文件失败不影响其余文件', async () => {
|
||||||
|
configureCos();
|
||||||
|
mock(app, 'cosClient', {
|
||||||
|
async deleteObject(options) {
|
||||||
|
if (options.Key.endsWith('bad.png')) throw new Error('COS 500');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mock(app, 'model', {
|
||||||
|
async query(sql, options) {
|
||||||
|
if (sql.includes('f.created_at < :cutoff')) {
|
||||||
|
return [ [
|
||||||
|
{ id: 1, object_key: 'images/docs/bad.png', url: 'u1', file_name: 'bad.png', size: 1, created_at: new Date('2026-11-01T00:00:00Z') },
|
||||||
|
{ id: 2, object_key: 'images/docs/ok.png', url: 'u2', file_name: 'ok.png', size: 2, created_at: new Date('2026-11-01T00:00:00Z') },
|
||||||
|
], [] ];
|
||||||
|
}
|
||||||
|
if (sql.startsWith('DELETE FROM file_records')) return [ { affectedRows: 1 }, [] ];
|
||||||
|
throw new Error(`unexpected sql: ${sql}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await app.createAnonymousContext().service.fileStorage.cleanup({ dryRun: false });
|
||||||
|
|
||||||
|
assert(result.deleted === 1 && result.failed.length === 1, JSON.stringify(result));
|
||||||
|
assert(result.failed[0].key === 'images/docs/bad.png');
|
||||||
|
});
|
||||||
|
});
|
||||||
107
backend/test/app/service/image_upload.test.js
Normal file
107
backend/test/app/service/image_upload.test.js
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||||
|
const { Readable } = require('stream');
|
||||||
|
|
||||||
|
/** 填一套假 COS 配置(含目录前缀) */
|
||||||
|
function configureCos() {
|
||||||
|
const config = app.config.cos;
|
||||||
|
mock(config, 'secretId', 'test-secret-id');
|
||||||
|
mock(config, 'secretKey', 'test-secret-key');
|
||||||
|
mock(config, 'bucket', 'test-bucket-123456');
|
||||||
|
mock(config, 'region', 'ap-guangzhou');
|
||||||
|
mock(config, 'publicUrl', 'https://images.example.com');
|
||||||
|
mock(config, 'maxFileSize', 5 * 1024 * 1024);
|
||||||
|
mock(config, 'dirs', { avatar: 'images/avatars', doc: 'images/docs' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function pngStream() {
|
||||||
|
const stream = Readable.from([ Buffer.from('89504e470d0a1a0a0000', 'hex') ]);
|
||||||
|
stream.filename = 'photo.png';
|
||||||
|
stream.mime = 'image/png';
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('test/app/service/image_upload.test.js', () => {
|
||||||
|
it('使用配置里的目录前缀,把校验通过的内容交给 fileStorage 登记', async () => {
|
||||||
|
configureCos();
|
||||||
|
let uploaded = null;
|
||||||
|
app.mockService('fileStorage', 'uploadObject', async params => {
|
||||||
|
uploaded = params;
|
||||||
|
return { id: 1, key: params.key, url: `https://images.example.com/${params.key}` };
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await app.createAnonymousContext().service.imageUpload.upload(pngStream(), { category: 'doc' });
|
||||||
|
|
||||||
|
assert(uploaded.key.startsWith('images/docs/') && uploaded.key.endsWith('.png'), uploaded.key);
|
||||||
|
assert(uploaded.contentType === 'image/png');
|
||||||
|
assert(uploaded.category === 'doc');
|
||||||
|
assert(uploaded.body.toString('hex').startsWith('89504e470d0a1a0a'), '应把完整字节交给存储层');
|
||||||
|
assert(result.url === `https://images.example.com/${uploaded.key}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('支持按业务子目录上传(头像按用户 ID 分目录)', async () => {
|
||||||
|
configureCos();
|
||||||
|
let uploaded = null;
|
||||||
|
app.mockService('fileStorage', 'uploadObject', async params => {
|
||||||
|
uploaded = params;
|
||||||
|
return { id: 2, key: params.key, url: '' };
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.createAnonymousContext().service.imageUpload.upload(pngStream(), {
|
||||||
|
category: 'avatar',
|
||||||
|
dir: 'images/avatars/17',
|
||||||
|
});
|
||||||
|
|
||||||
|
assert(uploaded.key.startsWith('images/avatars/17/'), uploaded.key);
|
||||||
|
assert(uploaded.category === 'avatar');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('扩展名与 MIME 不一致时拒绝上传', async () => {
|
||||||
|
configureCos();
|
||||||
|
const stream = pngStream();
|
||||||
|
stream.mime = 'image/jpeg';
|
||||||
|
|
||||||
|
let error = null;
|
||||||
|
try {
|
||||||
|
await app.createAnonymousContext().service.imageUpload.upload(stream, { category: 'doc' });
|
||||||
|
} catch (err) {
|
||||||
|
error = err;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(error && error.status === 422, '扩展名与 MIME 不一致必须拒绝');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('文件内容与扩展名不符时拒绝上传(防伪造后缀)', async () => {
|
||||||
|
configureCos();
|
||||||
|
const stream = Readable.from([ Buffer.from('not-a-png') ]);
|
||||||
|
stream.filename = 'fake.png';
|
||||||
|
stream.mime = 'image/png';
|
||||||
|
|
||||||
|
let error = null;
|
||||||
|
try {
|
||||||
|
await app.createAnonymousContext().service.imageUpload.upload(stream, { category: 'doc' });
|
||||||
|
} catch (err) {
|
||||||
|
error = err;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(error && error.status === 422, '文件头不匹配必须拒绝');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('超过大小上限时返回 413', async () => {
|
||||||
|
configureCos();
|
||||||
|
mock(app.config.cos, 'maxFileSize', 8);
|
||||||
|
const stream = Readable.from([ Buffer.from('89504e470d0a1a0a', 'hex'), Buffer.alloc(32) ]);
|
||||||
|
stream.filename = 'big.png';
|
||||||
|
stream.mime = 'image/png';
|
||||||
|
|
||||||
|
let error = null;
|
||||||
|
try {
|
||||||
|
await app.createAnonymousContext().service.imageUpload.upload(stream, { category: 'doc' });
|
||||||
|
} catch (err) {
|
||||||
|
error = err;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(error && error.status === 413, '超过上限必须拒绝');
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -266,6 +266,18 @@ export interface DocArticleInput {
|
|||||||
status?: number;
|
status?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UploadedImage {
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上传文档图片至 COS */
|
||||||
|
export function uploadDocImage(file: File): Promise<UploadedImage> {
|
||||||
|
const body = new FormData();
|
||||||
|
body.append('file', file);
|
||||||
|
return api.post('/api/web/admin/doc/upload-image', body);
|
||||||
|
}
|
||||||
|
|
||||||
/** 整棵文档树(栏目 → 内容页) */
|
/** 整棵文档树(栏目 → 内容页) */
|
||||||
export function fetchDocTree(): Promise<{ list: DocSectionNode[]; total: number }> {
|
export function fetchDocTree(): Promise<{ list: DocSectionNode[]; total: number }> {
|
||||||
return api.get('/api/web/admin/doc/tree');
|
return api.get('/api/web/admin/doc/tree');
|
||||||
|
|||||||
@ -43,8 +43,9 @@ interface RequestOptions {
|
|||||||
|
|
||||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||||
const { method = 'GET', body, auth = true, signal } = options;
|
const { method = 'GET', body, auth = true, signal } = options;
|
||||||
|
const isFormData = typeof FormData !== 'undefined' && body instanceof FormData;
|
||||||
const headers: Record<string, string> = {};
|
const headers: Record<string, string> = {};
|
||||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
if (body !== undefined && !isFormData) headers['Content-Type'] = 'application/json';
|
||||||
if (auth) {
|
if (auth) {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (token) headers.Authorization = `Bearer ${token}`;
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
@ -56,7 +57,7 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
|
|||||||
const res = await fetch(`${BASE}${path}`, {
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
method,
|
method,
|
||||||
headers,
|
headers,
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
body: body === undefined ? undefined : isFormData ? body : JSON.stringify(body),
|
||||||
signal,
|
signal,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
107
frontend/src/api/files.ts
Normal file
107
frontend/src/api/files.ts
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
/**
|
||||||
|
* 平台管理 · 文件存储(COS 图片)
|
||||||
|
*
|
||||||
|
* 后端:
|
||||||
|
* - `GET /api/web/admin/files` 分页列表(带引用状态 / 引用明细 / 全局统计)
|
||||||
|
* - `POST /api/web/admin/files/cleanup` 清理未引用文件(默认 dryRun 只预览)
|
||||||
|
* - `DELETE /api/web/admin/files/:id` 删除单个文件(`force` 可删仍被引用的)
|
||||||
|
*
|
||||||
|
* 「引用」是按用户头像与文档正文实时算的,不是上传时的标记。
|
||||||
|
*/
|
||||||
|
import { api } from '@/api/client';
|
||||||
|
|
||||||
|
/** 一处引用(头像 / 文档正文) */
|
||||||
|
export interface FileReference {
|
||||||
|
type: string;
|
||||||
|
id: number;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StoredFile {
|
||||||
|
id: number;
|
||||||
|
/** COS 对象键(相对路径) */
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
fileName: string;
|
||||||
|
size: number;
|
||||||
|
mimeType: string;
|
||||||
|
category: string;
|
||||||
|
categoryText: string;
|
||||||
|
uploaderId: number | null;
|
||||||
|
uploaderName: string;
|
||||||
|
createdAt: string;
|
||||||
|
/** 是否仍被引用 */
|
||||||
|
referenced: boolean;
|
||||||
|
references: FileReference[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FileStats {
|
||||||
|
total: number;
|
||||||
|
totalBytes: number;
|
||||||
|
referencedCount: number;
|
||||||
|
referencedBytes: number;
|
||||||
|
unreferencedCount: number;
|
||||||
|
unreferencedBytes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 当前存储配置(只读,不含密钥) */
|
||||||
|
export interface StorageMeta {
|
||||||
|
bucket: string;
|
||||||
|
region: string;
|
||||||
|
publicUrl: string;
|
||||||
|
maxFileSize: number;
|
||||||
|
dirs: Record<string, string>;
|
||||||
|
cleanupMinAgeHours: number;
|
||||||
|
configured: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StoredFileList {
|
||||||
|
list: StoredFile[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
stats: FileStats;
|
||||||
|
storage: StorageMeta;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CleanupResult {
|
||||||
|
dryRun: boolean;
|
||||||
|
minAgeHours: number;
|
||||||
|
candidates: number;
|
||||||
|
bytes: number;
|
||||||
|
deleted: number;
|
||||||
|
failed: { id: number; key: string; message: string }[];
|
||||||
|
items: { id: number; key: string; url: string; fileName: string; size: number; createdAt: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 分页查询文件(`referenced` 不传 = 全部) */
|
||||||
|
export function fetchFiles(params: {
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
keyword?: string;
|
||||||
|
category?: string;
|
||||||
|
referenced?: boolean;
|
||||||
|
} = {}): Promise<StoredFileList> {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (params.page) query.set('page', String(params.page));
|
||||||
|
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||||
|
if (params.keyword) query.set('keyword', params.keyword);
|
||||||
|
if (params.category) query.set('category', params.category);
|
||||||
|
if (params.referenced !== undefined) query.set('referenced', params.referenced ? '1' : '0');
|
||||||
|
const qs = query.toString();
|
||||||
|
return api.get<StoredFileList>(`/api/web/admin/files${qs ? `?${qs}` : ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 清理未引用文件(先 `dryRun: true` 预览,再 `false` 真删) */
|
||||||
|
export function cleanupUnreferencedFiles(body: {
|
||||||
|
dryRun: boolean;
|
||||||
|
minAgeHours?: number;
|
||||||
|
limit?: number;
|
||||||
|
}): Promise<CleanupResult> {
|
||||||
|
return api.post('/api/web/admin/files/cleanup', body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 删除单个文件;`force` = 仍被引用也删(会让引用处图片失效) */
|
||||||
|
export function deleteStoredFile(id: number, force = false): Promise<{ id: number; key: string }> {
|
||||||
|
return api.del(`/api/web/admin/files/${id}${force ? '?force=1' : ''}`);
|
||||||
|
}
|
||||||
@ -15,6 +15,18 @@ import type {
|
|||||||
WechatCodeStatus,
|
WechatCodeStatus,
|
||||||
} from '@/api/types';
|
} from '@/api/types';
|
||||||
|
|
||||||
|
export interface UploadedImage {
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 上传当前用户头像至 COS */
|
||||||
|
export function uploadAvatar(file: File): Promise<UploadedImage> {
|
||||||
|
const body = new FormData();
|
||||||
|
body.append('file', file);
|
||||||
|
return api.post('/api/web/me/avatar', body);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 首页统计
|
* 首页统计
|
||||||
*
|
*
|
||||||
|
|||||||
@ -64,6 +64,7 @@ const platformMenus = [
|
|||||||
{ to: '/admin/members', label: '管理员' },
|
{ to: '/admin/members', label: '管理员' },
|
||||||
{ to: '/admin/extension', label: '插件配置' },
|
{ to: '/admin/extension', label: '插件配置' },
|
||||||
{ to: '/admin/doc', label: '文档管理' },
|
{ to: '/admin/doc', label: '文档管理' },
|
||||||
|
{ to: '/admin/files', label: '存储管理' },
|
||||||
];
|
];
|
||||||
|
|
||||||
/** 当前主体(用于右上角展示 / 过期提示) */
|
/** 当前主体(用于右上角展示 / 过期提示) */
|
||||||
|
|||||||
@ -84,6 +84,13 @@ const routes: RouteRecordRaw[] = [
|
|||||||
component: () => import('@/views/AdminDocView.vue'),
|
component: () => import('@/views/AdminDocView.vue'),
|
||||||
meta: { allowNoSubject: true, platformAdmin: true },
|
meta: { allowNoSubject: true, platformAdmin: true },
|
||||||
},
|
},
|
||||||
|
// 存储管理:COS 图片登记 / 引用状态 / 清理未引用
|
||||||
|
{
|
||||||
|
path: '/admin/files',
|
||||||
|
name: 'admin-files',
|
||||||
|
component: () => import('@/views/AdminFilesView.vue'),
|
||||||
|
meta: { allowNoSubject: true, platformAdmin: true },
|
||||||
|
},
|
||||||
// 测试页只在开发构建里存在:生产包不包含该路由,也不会产出它的 chunk
|
// 测试页只在开发构建里存在:生产包不包含该路由,也不会产出它的 chunk
|
||||||
...(import.meta.env.DEV
|
...(import.meta.env.DEV
|
||||||
? [{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue'), meta: { adminOnly: true } } as RouteRecordRaw]
|
? [{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue'), meta: { adminOnly: true } } as RouteRecordRaw]
|
||||||
|
|||||||
@ -8,7 +8,7 @@
|
|||||||
*
|
*
|
||||||
* 接口:`/api/web/admin/doc/*`(平台管理员)
|
* 接口:`/api/web/admin/doc/*`(平台管理员)
|
||||||
*/
|
*/
|
||||||
import { computed, onMounted, reactive, ref } from 'vue';
|
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
|
||||||
import AppLayout from '@/components/AppLayout.vue';
|
import AppLayout from '@/components/AppLayout.vue';
|
||||||
import ModalBox from '@/components/ModalBox.vue';
|
import ModalBox from '@/components/ModalBox.vue';
|
||||||
import { ApiError } from '@/api/client';
|
import { ApiError } from '@/api/client';
|
||||||
@ -22,6 +22,7 @@ import {
|
|||||||
removeDocSection,
|
removeDocSection,
|
||||||
updateDocArticle,
|
updateDocArticle,
|
||||||
updateDocSection,
|
updateDocSection,
|
||||||
|
uploadDocImage,
|
||||||
type DocArticleInput,
|
type DocArticleInput,
|
||||||
type DocSectionInput,
|
type DocSectionInput,
|
||||||
type DocSectionNode,
|
type DocSectionNode,
|
||||||
@ -84,8 +85,10 @@ function blankArticle(): ArticleForm {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const articleForm = reactive<ArticleForm>(blankArticle());
|
const articleForm = reactive<ArticleForm>(blankArticle());
|
||||||
|
const articleContentInput = ref<HTMLTextAreaElement | null>(null);
|
||||||
const articleLoading = ref(false);
|
const articleLoading = ref(false);
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
|
const imageUploading = ref(false);
|
||||||
const editing = computed(() => articleForm.id > 0);
|
const editing = computed(() => articleForm.id > 0);
|
||||||
|
|
||||||
function resetArticle() {
|
function resetArticle() {
|
||||||
@ -190,6 +193,38 @@ async function saveArticle() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function uploadArticleImage(event: Event) {
|
||||||
|
const input = event.target as HTMLInputElement;
|
||||||
|
const file = input.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
imageUploading.value = true;
|
||||||
|
error.value = '';
|
||||||
|
ok.value = '';
|
||||||
|
const selectionStart = articleContentInput.value?.selectionStart ?? articleForm.content.length;
|
||||||
|
const selectionEnd = articleContentInput.value?.selectionEnd ?? selectionStart;
|
||||||
|
try {
|
||||||
|
const image = await uploadDocImage(file);
|
||||||
|
const alt = file.name.replace(/\.[^.]+$/, '').replace(/[\[\]]/g, '');
|
||||||
|
const markdown = ``;
|
||||||
|
const before = articleForm.content.slice(0, selectionStart);
|
||||||
|
const after = articleForm.content.slice(selectionEnd);
|
||||||
|
const prefix = before && !before.endsWith('\n') ? '\n' : '';
|
||||||
|
const suffix = after && !after.startsWith('\n') ? '\n' : '';
|
||||||
|
articleForm.content = `${before}${prefix}${markdown}${suffix}${after}`;
|
||||||
|
await nextTick();
|
||||||
|
const cursor = before.length + prefix.length + markdown.length;
|
||||||
|
articleContentInput.value?.focus();
|
||||||
|
articleContentInput.value?.setSelectionRange(cursor, cursor);
|
||||||
|
ok.value = '图片已上传并插入正文,保存文章后生效';
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err instanceof ApiError ? err.message : '图片上传失败';
|
||||||
|
} finally {
|
||||||
|
imageUploading.value = false;
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function deleteArticle() {
|
async function deleteArticle() {
|
||||||
if (!editing.value) return;
|
if (!editing.value) return;
|
||||||
if (!window.confirm(`确认删除内容页「${articleForm.title}」?\n\n删除后文档页面与 sitemap 里的链接会一起移除,且不能恢复。`)) return;
|
if (!window.confirm(`确认删除内容页「${articleForm.title}」?\n\n删除后文档页面与 sitemap 里的链接会一起移除,且不能恢复。`)) return;
|
||||||
@ -450,11 +485,21 @@ onMounted(() => load(false));
|
|||||||
<label class="field span-2">
|
<label class="field span-2">
|
||||||
<span>正文(Markdown:标题 # / ##、列表、代码块、链接、粗体、图片)</span>
|
<span>正文(Markdown:标题 # / ##、列表、代码块、链接、粗体、图片)</span>
|
||||||
<textarea
|
<textarea
|
||||||
|
ref="articleContentInput"
|
||||||
v-model="articleForm.content"
|
v-model="articleForm.content"
|
||||||
rows="18"
|
rows="18"
|
||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
placeholder="## 小标题 正文内容… "
|
placeholder="## 小标题 正文内容… 使用下方图片上传控件插入 COS 图片"
|
||||||
/>
|
/>
|
||||||
|
<span class="image-upload">
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="image/bmp,image/gif,image/jpeg,image/png,image/webp"
|
||||||
|
:disabled="imageUploading"
|
||||||
|
@change="uploadArticleImage"
|
||||||
|
/>
|
||||||
|
<span class="hint">{{ imageUploading ? '正在上传图片…' : '选择图片后上传至 COS,并插入 Markdown' }}</span>
|
||||||
|
</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
374
frontend/src/views/AdminFilesView.vue
Normal file
374
frontend/src/views/AdminFilesView.vue
Normal file
@ -0,0 +1,374 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* 平台管理 · 存储管理(COS 图片)
|
||||||
|
*
|
||||||
|
* 每张上传成功的图片都会登记到 `file_records`;「是否被引用」由后端**实时计算**
|
||||||
|
* (用户头像 / 文档正文),所以删改业务数据后引用状态会立刻跟着变。
|
||||||
|
*
|
||||||
|
* 接口:`/api/web/admin/files*`(平台管理员)
|
||||||
|
* - 列表:`GET /api/web/admin/files`
|
||||||
|
* - 清理:`POST /api/web/admin/files/cleanup`(先 dryRun 预览,再确认执行)
|
||||||
|
* - 删除:`DELETE /api/web/admin/files/:id`(仍被引用时默认拒绝,可强制删除)
|
||||||
|
*/
|
||||||
|
import { computed, onMounted, ref } from 'vue';
|
||||||
|
import AppLayout from '@/components/AppLayout.vue';
|
||||||
|
import DataPager from '@/components/DataPager.vue';
|
||||||
|
import { ApiError } from '@/api/client';
|
||||||
|
import {
|
||||||
|
cleanupUnreferencedFiles,
|
||||||
|
deleteStoredFile,
|
||||||
|
fetchFiles,
|
||||||
|
type FileStats,
|
||||||
|
type StorageMeta,
|
||||||
|
type StoredFile,
|
||||||
|
} from '@/api/files';
|
||||||
|
import { formatTime } from '@/utils/format';
|
||||||
|
|
||||||
|
const list = ref<StoredFile[]>([]);
|
||||||
|
const stats = ref<FileStats>({
|
||||||
|
total: 0,
|
||||||
|
totalBytes: 0,
|
||||||
|
referencedCount: 0,
|
||||||
|
referencedBytes: 0,
|
||||||
|
unreferencedCount: 0,
|
||||||
|
unreferencedBytes: 0,
|
||||||
|
});
|
||||||
|
const storage = ref<StorageMeta | null>(null);
|
||||||
|
|
||||||
|
const page = ref(1);
|
||||||
|
const pageSize = ref(20);
|
||||||
|
const total = ref(0);
|
||||||
|
const keyword = ref('');
|
||||||
|
const category = ref('');
|
||||||
|
const referenced = ref<'' | '1' | '0'>('');
|
||||||
|
|
||||||
|
const loading = ref(false);
|
||||||
|
const cleaning = ref(false);
|
||||||
|
const deleting = ref(0);
|
||||||
|
const error = ref('');
|
||||||
|
const ok = ref('');
|
||||||
|
|
||||||
|
/** 「未引用 + 已过保护期」= 可安全清理的数量(用统计值给个粗略提示) */
|
||||||
|
const cleanupHint = computed(() => {
|
||||||
|
if (!storage.value) return '';
|
||||||
|
return `只清理上传超过 ${storage.value.cleanupMinAgeHours} 小时、且没有任何引用的图片`;
|
||||||
|
});
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loading.value = true;
|
||||||
|
error.value = '';
|
||||||
|
try {
|
||||||
|
const data = await fetchFiles({
|
||||||
|
page: page.value,
|
||||||
|
pageSize: pageSize.value,
|
||||||
|
keyword: keyword.value.trim() || undefined,
|
||||||
|
category: category.value || undefined,
|
||||||
|
referenced: referenced.value === '' ? undefined : referenced.value === '1',
|
||||||
|
});
|
||||||
|
list.value = data.list;
|
||||||
|
total.value = data.total;
|
||||||
|
stats.value = data.stats;
|
||||||
|
storage.value = data.storage;
|
||||||
|
// 删到空页时自动回退一页,避免停在空白页
|
||||||
|
if (!data.list.length && data.total > 0 && page.value > 1) {
|
||||||
|
page.value = Math.max(Math.ceil(data.total / pageSize.value), 1);
|
||||||
|
await load();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err instanceof ApiError ? err.message : '加载失败';
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function search() {
|
||||||
|
page.value = 1;
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function changePageSize(size: number) {
|
||||||
|
pageSize.value = size;
|
||||||
|
page.value = 1;
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(bytes: number): string {
|
||||||
|
const value = Number(bytes) || 0;
|
||||||
|
if (value < 1024) return `${value} B`;
|
||||||
|
const units = [ 'KB', 'MB', 'GB', 'TB' ];
|
||||||
|
let size = value / 1024;
|
||||||
|
let index = 0;
|
||||||
|
while (size >= 1024 && index < units.length - 1) {
|
||||||
|
size /= 1024;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
return `${size.toFixed(size >= 10 ? 0 : 1)} ${units[index]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 引用明细压成一行:`头像:张三 / 文档:快速开始` */
|
||||||
|
function referenceText(row: StoredFile): string {
|
||||||
|
if (!row.referenced) return '';
|
||||||
|
return row.references.map(item => item.label).join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(row: StoredFile) {
|
||||||
|
const tip = row.referenced
|
||||||
|
? `该图片仍被 ${row.references.length} 处引用:\n${row.references.map(item => `- ${item.label}`).join('\n')}\n\n强制删除后这些位置会显示不出图片,确认继续?`
|
||||||
|
: `确认删除「${row.fileName || row.key}」?\n\nCOS 对象与登记记录都会被删除,且不能恢复。`;
|
||||||
|
if (!window.confirm(tip)) return;
|
||||||
|
|
||||||
|
deleting.value = row.id;
|
||||||
|
error.value = '';
|
||||||
|
ok.value = '';
|
||||||
|
try {
|
||||||
|
await deleteStoredFile(row.id, row.referenced);
|
||||||
|
ok.value = `已删除「${row.fileName || row.key}」`;
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err instanceof ApiError ? err.message : '删除失败';
|
||||||
|
} finally {
|
||||||
|
deleting.value = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 两步清理:先 dryRun 看数量,用户确认后再真删 */
|
||||||
|
async function cleanup() {
|
||||||
|
cleaning.value = true;
|
||||||
|
error.value = '';
|
||||||
|
ok.value = '';
|
||||||
|
try {
|
||||||
|
const preview = await cleanupUnreferencedFiles({ dryRun: true });
|
||||||
|
if (!preview.candidates) {
|
||||||
|
ok.value = `没有可清理的未引用图片(${cleanupHint.value})`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const confirmed = window.confirm(
|
||||||
|
`发现 ${preview.candidates} 个未引用图片,共 ${formatSize(preview.bytes)}(${cleanupHint.value})。\n\n` +
|
||||||
|
'确认后会从 COS 和登记表中删除,不能恢复。继续?',
|
||||||
|
);
|
||||||
|
if (!confirmed) return;
|
||||||
|
|
||||||
|
const result = await cleanupUnreferencedFiles({ dryRun: false });
|
||||||
|
const failed = result.failed.length ? `,${result.failed.length} 个失败(详见服务端日志)` : '';
|
||||||
|
ok.value = `已清理 ${result.deleted} 个未引用图片,释放 ${formatSize(result.items
|
||||||
|
.filter(item => !result.failed.some(fail => fail.id === item.id))
|
||||||
|
.reduce((sum, item) => sum + item.size, 0))}${failed}`;
|
||||||
|
await load();
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err instanceof ApiError ? err.message : '清理失败';
|
||||||
|
} finally {
|
||||||
|
cleaning.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AppLayout fill>
|
||||||
|
<template #title>存储管理</template>
|
||||||
|
|
||||||
|
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||||
|
<div v-if="ok" class="alert alert-ok">{{ ok }}</div>
|
||||||
|
|
||||||
|
<div class="stat-grid">
|
||||||
|
<div class="stat">
|
||||||
|
<span class="stat-label">文件总数</span>
|
||||||
|
<b class="stat-value">{{ stats.total }}</b>
|
||||||
|
<span class="hint">{{ formatSize(stats.totalBytes) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<span class="stat-label">已引用</span>
|
||||||
|
<b class="stat-value ok">{{ stats.referencedCount }}</b>
|
||||||
|
<span class="hint">{{ formatSize(stats.referencedBytes) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<span class="stat-label">未引用</span>
|
||||||
|
<b class="stat-value warn">{{ stats.unreferencedCount }}</b>
|
||||||
|
<span class="hint">{{ formatSize(stats.unreferencedBytes) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<span class="stat-label">存储桶</span>
|
||||||
|
<b class="stat-value small">{{ storage?.bucket || '未配置' }}</b>
|
||||||
|
<span class="hint">{{ storage?.region || '—' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="storage" class="card storage-meta">
|
||||||
|
<p class="hint">
|
||||||
|
头像目录 <code>{{ storage.dirs.avatar || '—' }}</code> ·
|
||||||
|
文档目录 <code>{{ storage.dirs.doc || '—' }}</code> ·
|
||||||
|
单张上限 {{ formatSize(storage.maxFileSize) }} ·
|
||||||
|
访问域名 <code>{{ storage.publicUrl || '—' }}</code>
|
||||||
|
</p>
|
||||||
|
<p v-if="!storage.configured" class="alert alert-error">
|
||||||
|
COS 凭证未配置完整(COS_SECRET_ID / COS_SECRET_KEY / COS_BUCKET / COS_REGION),上传接口会返回 503。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="toolbar">
|
||||||
|
<input v-model="keyword" placeholder="搜索文件名 / 对象键" @keyup.enter="search" />
|
||||||
|
<select v-model="category" class="filter-select" @change="search">
|
||||||
|
<option value="">全部分类</option>
|
||||||
|
<option value="avatar">用户头像</option>
|
||||||
|
<option value="doc">文档图片</option>
|
||||||
|
</select>
|
||||||
|
<select v-model="referenced" class="filter-select" @change="search">
|
||||||
|
<option value="">全部引用状态</option>
|
||||||
|
<option value="1">已引用</option>
|
||||||
|
<option value="0">未引用</option>
|
||||||
|
</select>
|
||||||
|
<button class="btn" :disabled="loading" @click="search">搜索</button>
|
||||||
|
<button class="btn btn-danger" :disabled="cleaning || loading" @click="cleanup">
|
||||||
|
{{ cleaning ? '清理中…' : '清理未引用' }}
|
||||||
|
</button>
|
||||||
|
<span class="hint toolbar-tip">{{ cleanupHint }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table table-list">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th style="width: 64px">预览</th>
|
||||||
|
<th>文件</th>
|
||||||
|
<th style="width: 90px">大小</th>
|
||||||
|
<th style="width: 100px">分类</th>
|
||||||
|
<th style="width: 130px">上传者</th>
|
||||||
|
<th style="width: 150px">上传时间</th>
|
||||||
|
<th>引用状态</th>
|
||||||
|
<th style="width: 90px">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="row in list" :key="row.id">
|
||||||
|
<td>
|
||||||
|
<a :href="row.url" target="_blank" rel="noopener">
|
||||||
|
<img class="thumb" :src="row.url" :alt="row.fileName || row.key" loading="lazy" />
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<b>{{ row.fileName || '(未命名)' }}</b>
|
||||||
|
<span class="cell-sub"><code>{{ row.key }}</code></span>
|
||||||
|
<span class="cell-sub">{{ row.mimeType }}</span>
|
||||||
|
</td>
|
||||||
|
<td>{{ formatSize(row.size) }}</td>
|
||||||
|
<td>{{ row.categoryText || '其他' }}</td>
|
||||||
|
<td class="muted">{{ row.uploaderName || (row.uploaderId ? `#${row.uploaderId}` : '—') }}</td>
|
||||||
|
<td class="muted">{{ row.createdAt ? formatTime(row.createdAt) : '—' }}</td>
|
||||||
|
<td>
|
||||||
|
<span :class="['badge', row.referenced ? 'badge-ok' : 'badge-warn']">
|
||||||
|
{{ row.referenced ? '已引用' : '未引用' }}
|
||||||
|
</span>
|
||||||
|
<span v-if="row.referenced" class="cell-sub">{{ referenceText(row) }}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-sm" :class="row.referenced ? 'btn-danger' : ''"
|
||||||
|
:disabled="deleting === row.id" @click="remove(row)">
|
||||||
|
{{ deleting === row.id ? '删除中…' : '删除' }}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!list.length">
|
||||||
|
<td colspan="8" class="hint">
|
||||||
|
{{ loading ? '加载中…' : '还没有上传过图片,或没有符合条件的记录。' }}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||||
|
unit="个文件" @update:page="load" @update:page-size="changePageSize" />
|
||||||
|
</div>
|
||||||
|
</AppLayout>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.stat-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-label {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
font-size: 22px;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value.small {
|
||||||
|
font-size: 14px;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value.ok {
|
||||||
|
color: #12805c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value.warn {
|
||||||
|
color: #b45309;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-meta {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-meta p {
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar-tip {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-select {
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fff;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cell-sub {
|
||||||
|
display: block;
|
||||||
|
margin-top: 2px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.thumb {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
object-fit: cover;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #f7f7f7;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@ -9,6 +9,7 @@ import {
|
|||||||
createWechatBindQr,
|
createWechatBindQr,
|
||||||
fetchWechatBindings,
|
fetchWechatBindings,
|
||||||
fetchWechatBindStatus,
|
fetchWechatBindStatus,
|
||||||
|
uploadAvatar,
|
||||||
unbindWechat,
|
unbindWechat,
|
||||||
type WxBinding,
|
type WxBinding,
|
||||||
} from '@/api/web';
|
} from '@/api/web';
|
||||||
@ -17,9 +18,10 @@ import { formatTime } from '@/utils/format';
|
|||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const form = reactive({ nickname: '', email: '', phone: '' });
|
const form = reactive({ nickname: '', email: '', phone: '', avatar: '' });
|
||||||
const pwd = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' });
|
const pwd = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' });
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
|
const avatarUploading = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const ok = ref('');
|
const ok = ref('');
|
||||||
|
|
||||||
@ -124,6 +126,27 @@ function fill(user: CurrentUser | null) {
|
|||||||
form.nickname = user?.nickname || '';
|
form.nickname = user?.nickname || '';
|
||||||
form.email = user?.email || '';
|
form.email = user?.email || '';
|
||||||
form.phone = user?.phone || '';
|
form.phone = user?.phone || '';
|
||||||
|
form.avatar = user?.avatar || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onAvatarSelected(event: Event) {
|
||||||
|
const input = event.target as HTMLInputElement;
|
||||||
|
const file = input.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
error.value = '';
|
||||||
|
ok.value = '';
|
||||||
|
avatarUploading.value = true;
|
||||||
|
try {
|
||||||
|
const image = await uploadAvatar(file);
|
||||||
|
form.avatar = image.url;
|
||||||
|
ok.value = '头像已上传,请保存资料使其生效';
|
||||||
|
} catch (err) {
|
||||||
|
error.value = err instanceof ApiError ? err.message : '头像上传失败';
|
||||||
|
} finally {
|
||||||
|
avatarUploading.value = false;
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
@ -149,6 +172,7 @@ async function saveProfile() {
|
|||||||
nickname: form.nickname,
|
nickname: form.nickname,
|
||||||
email: form.email,
|
email: form.email,
|
||||||
phone: form.phone,
|
phone: form.phone,
|
||||||
|
avatar: form.avatar,
|
||||||
});
|
});
|
||||||
setUser(me);
|
setUser(me);
|
||||||
fill(me);
|
fill(me);
|
||||||
@ -207,7 +231,17 @@ async function savePassword() {
|
|||||||
<span>手机号</span>
|
<span>手机号</span>
|
||||||
<input v-model="form.phone" placeholder="13800000000" />
|
<input v-model="form.phone" placeholder="13800000000" />
|
||||||
</label>
|
</label>
|
||||||
<button class="btn" :disabled="busy">保存资料</button>
|
<label class="field">
|
||||||
|
<span>头像</span>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept="image/bmp,image/gif,image/jpeg,image/png,image/webp"
|
||||||
|
:disabled="avatarUploading"
|
||||||
|
@change="onAvatarSelected"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<img v-if="form.avatar" class="avatar-preview" :src="form.avatar" alt="头像预览" />
|
||||||
|
<button class="btn" :disabled="busy || avatarUploading">保存资料</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<form class="card" @submit.prevent="savePassword">
|
<form class="card" @submit.prevent="savePassword">
|
||||||
@ -282,6 +316,13 @@ h3 {
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
.avatar-preview {
|
||||||
|
width: 72px;
|
||||||
|
height: 72px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 50%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
.bind-list li {
|
.bind-list li {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user