- 头像 / 文档图片改由后端校验并转发到 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>
411 lines
14 KiB
JavaScript
411 lines
14 KiB
JavaScript
'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;
|