From 0b49caec0021327c6a83730069c33dd5646fa236 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 13 Jul 2026 01:01:00 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AA=92=E4=BD=93=E5=AD=98=E5=82=A8?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E6=A8=A1=E6=9D=BFID/=E6=A1=A3=E6=A1=88?= =?UTF-8?q?=E7=BC=96=E5=8F=B7=E5=B1=82=E7=BA=A7=E5=B9=B6=E6=8C=89=E4=BA=BA?= =?UTF-8?q?=E7=B1=BB=E5=8F=AF=E8=AF=BB=E5=91=BD=E5=90=8D=E5=BD=92=E4=BD=8D?= =?UTF-8?q?(=E5=87=BA=E5=BA=93=E5=9B=BE=E7=8B=AC=E7=AB=8B=E8=BF=BD?= =?UTF-8?q?=E6=BA=AF=E7=A0=81=E5=AD=90=E7=9B=AE=E5=BD=95)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aidocs/project_context.md | 1 + apps/api/src/artwork/artwork.service.ts | 143 ++++++++++++++++++++-- apps/api/src/outbound/import.processor.ts | 21 +++- apps/api/src/outbound/outbound.service.ts | 18 ++- apps/api/src/storage/storage.service.ts | 74 +++++++++++ 5 files changed, 240 insertions(+), 17 deletions(-) diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 4292e7e..cf3c0b1 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -252,6 +252,7 @@ - 天河链方案 B 落地(存证+发行+轮换,2026-07-10,dev/refine):按甲方决策「其余全做、媒体待定」实现。① 数据模型:`blockchain_proof` 加 `token_id`/`contract_address`(迁移 `20260710110000_add_proof_token_fields`);schema 补 `@db.VarChar` 注解消除历史 drift(operation_log.path 512 / outbound_import_session.file_key 512 / backup_record.file_path 1024)。② `TianheProvider` 新增 `publish`(接口2,operateId≤20,name≤42,author≤120,feature≤500)与 `updateUserKey`(接口7)。③ `BlockchainService.attestWithTianhe`:upload 存证→publish 铸 1 NFT(productId=追溯码、feature=存证链接)→ 主 txHash 切为 mint 交易、confirmationRequired=true 走接口9确认→ONCHAIN;合约地址存 `tianheContractAddress`、已发行最大 tokenId 存 `tianheMaxTokenId`(指定合约时作 baseTokenId,队列串行无争用);缺 product 时退化纯存证。`confirmTransaction` 确认成功回填 tokenId、更新 maxTokenId。④ `rotateTianheUserKey`:生成新随机 key→接口7链上改→持久化→接口8校验地址,`/settings/tianhe/identity/rotate` + 设置页「轮换密钥」(二次确认+回显强提示)。⑤ C 端:public-trace + Trace.vue 区块链卡增 tokenId/合约地址展示(i18n chain.tokenId/chain.contract)。⑥ 实测(测试环境):追溯码 412680781069 走通 upload→publish(合约 0xc96ae8a4... tokenId=0)→确认(区块高度 5820347)→ONCHAIN,C 端展示数字藏品编号 0/合约地址/区块高度;轮换 UserKey 成功(钱包地址不变),新 key 回填测试文档。验证:4 包构建 + 27 单测通过。**唯一待定:媒体上链层级 L1/L2/L3 待甲方确认「链上放什么」,当前维持 JSON 存证。** - 追溯码客户端预览功能(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):后台可预览 C 端页面且**零副作用**(不激活/不计数/不写查询日志)。① 令牌:`common/utils/preview-token.util.ts` 类 TOTP——HMAC-SHA256(jwt.secret, `preview:窗口号`) 取 16 hex,周期 10 分钟,校验接受当前+上一窗口(实际有效 10~20 分钟),无状态不落库,`timingSafeEqual` 防时序;外泄地址最长 2 窗口失效。② 后端:`GET /trace-codes/preview-token`(登录态)返回 `{token, clientBase, periodMs}`;`GET public/trace/:shortCode/preview?token&state`(@Public+限流)校验失败返回 `{status:'PREVIEW_EXPIRED'}`,成功走 `PublicTraceService.preview(state)`——与 trace() 共用 `buildArtworkPayload`(作品/时间线/证书/链上),但无任何 update/writeLog;`state=inactive` 时 antiCounterfeit 演示为首次扫码,`active` 用库中现值(0 时占位 2)。③ C 端:路由 `/trace/preview/:code` 复用 Trace.vue;`isPreview` 按路径判定,预览条(sticky 橙色)含「未激活/已激活」切换(切换重新请求),PREVIEW_EXPIRED 显示「预览链接已过期请回后台重开」。④ 后台:`traceCodeApi.previewToken`;TraceCodePanel 令牌缓存 8 分钟;**点追溯码=进预览页**(hover 提示「点击进入预览页(不激活、不计入查询次数)」;先同步 window.open('about:blank') 再异步填 URL 防弹窗拦截);**点链接列=弹确认框**告知直接访问会激活/计数,按钮[取消][访问预览页面][访问实际页面]。⑤ 预览 URL 仅点击时临时拼接不进行数据,导出仍只含真实短链。验证:5 项令牌单测 + API 实测(preview 前后 queryCount=0/INACTIVE 不变、查询日志 0 条、坏令牌拒绝、双状态正确)+ 全量构建 + 32 单测通过。 - 追溯码列表列重排+关联跳转(2026-07-12,分支 `dev/tianhe-no-metadata-upload`,两页共用 `TraceCodePanel` 同时生效):列顺序改为 追溯码→名称→档案编号→批次编号→分组→出库状态→上链状态→出库时间→激活状态→查询次数→激活时间→链接→创建时间→操作;名称/档案编号仅全局页显示(`fixedArtworkId` 时隐藏,档案内为同一作品)。关联:追溯码列渲染为 `` 点击开 C 端溯源页;名称/档案编号渲染为 `.cell-link` 点击 `goArtwork(id)` → `router.push({name:'artwork-detail'})`。`status` 列标题改用 `pages.traceCode.activationStatus`(激活状态),`firstActivatedAt` 标签改为「激活时间」,新增 `openTrace` i18n。追溯码列 `fixed:'left'`、操作列 `fixed:'right'`。浏览器双页实测通过。 +- 媒体存储层级改为人类可读目录(2026-07-13):原为 `YYYY/MM/DD/{hash16}-{nanoid}{ext}` 按上传日期混存、文件名不可辨认。新层级 **`{模板ID}/{档案编号}/`**:作品图 `作品图_{YYYYMMDDHHmmss}_{序号}.ext`、节点图 `节点-{标题}_...`、证书 `证书-{名称}_...`(水印件沿用 derivedKey 同目录 `_wm` 后缀);出库实况图再下一级 **`{模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号}.ext`**。实现=「上传仍进通用日期目录,实体保存时归位(move)」:① `StorageService` 增 `sanitizeSegment`(清洗非法字符)/`moveKey`(读→写→删,失败保留原 key 不断业务)/`relocateMedia`(批量归位+改写 url+返回 oldKey→newKey 映射,跳过已在目录内/http/data:);② `artwork.service.relocateArtworkMedia`:create 事务后归位(档案编号事务内才生成)并回写初始 revision afterSnapshot;update 开头先归位既有媒体(顺带渐进迁移历史存量)→ keyMap 改写 DTO → 再归位 DTO 新上传,快照/`applySnapshot` 的证书按 originKey reconcile 因两侧同步改写不受影响;③ `outbound.updateSingle` 与 `import.processor` 在写 outImages 前归位(include artwork 取 templateId/archiveNo)。已知取舍:历史 revision 快照仍持旧 key,其文件被迁移后历史审核详情预览会 404(业务数据不受影响)。构建+32 单测通过。 - AppKey 揭示改为明文(2026-07-13):用户原话「APPKey点击眼睛后显示442******de7 而不是完整的key」实为**吐槽**(点眼睛只看到掩码、看不到完整 key),前两轮误读成"要求只显示掩码"。改正:`POST /settings/tianhe/app-key/reveal`(超管+操作日志)改回返回明文 `appKey`;前端确认框文案改为「将显示完整 App Key 并记入操作日志」,确认后输入框回填明文(type=text 完整可见),收起眼睛时若未编辑则恢复服务端掩码(明文不留输入框);`update()` 的 `isMaskedSecret` 跳过逻辑保证掩码值保存不会覆盖真实 key。教训:**用户描述现象时"显示X而不是Y"大概率是抱怨现状X、想要Y,拿不准先确认**。 - 追溯码链接直连客户端地址(2026-07-13):用户设置了「客户端地址」但列表/二维码仍生成 `/t/` 短链(仅取 origin 拼 `/t/`,丢了路径且必须经后端跳转)。改为 `buildDynamicShortLink = ${clientBaseUrl}/#/trace/${shortCode}`(完整含路径,列表/详情/二维码/导出四处共用,动态生成换地址自动跟随);删除无人引用的 `buildTraceUrl/buildShortLink/shortLinkOrigin` 与 ConfigService 注入。`GET /t/:shortCode` 跳转端点保留,兼容历史已打印二维码。API 构建+32 单测通过。 - 系统设置页排版返工(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):上一版分页布局被用户否掉(全竖排、控件不自适应、卡片标题与 tab 重复、区块链两卡没有真正左右排、AppKey 掩码被窄输入框截断)。重做要点:① 各 tab 去掉与 tab 同名的内层卡片标题,直接放 `n-form label-placement="left" :label-width="150" :show-feedback="false"`(标题左、控件右、`max-width:720px` 内自适应拉伸);② 备份 tab=顶部横排 inline 表单(定时备份/保留天数/数量)+ 分割线 + `BackupRestorePanel` flex 填满剩余高度(tab-pane 加 `pane-flex` 关外层滚动),表格自适应宽度;③ 区块链 tab=`chain-grid`(`grid-template-columns:repeat(auto-fit,minmax(430px,1fr))`)两卡真左右并排:左卡「接口配置」(新 i18n 键 `chainApiConfig`,避免与 tab 名重复)、右卡「链上身份」按钮在卡头右侧;④ AppKey 输入框拉宽后揭示的掩码 `442******de7` 完整可见(实测);⑤ 补 `watch(route.query.tab)` 支持浏览器前进/后退与手改地址栏同步切 tab。浏览器逐 tab 截图实测通过(URL 跟随、确认框、掩码、备份表格填充)。教训:**转包 UI 布局任务必须附截图级验收标准,否则容易做成"能编译但难看"**。 diff --git a/apps/api/src/artwork/artwork.service.ts b/apps/api/src/artwork/artwork.service.ts index 8160674..e4f08f6 100644 --- a/apps/api/src/artwork/artwork.service.ts +++ b/apps/api/src/artwork/artwork.service.ts @@ -23,6 +23,7 @@ interface MediaItem { key: string; name?: string; type?: string; + url?: string; } interface TraceNodeSnapshot { @@ -83,6 +84,80 @@ export class ArtworkService { return `ARTVERIS-${String(id).padStart(6, '0')}`; } + // 媒体目录层级:{模板ID}/{档案编号}/(追溯码出库图再下一级 {追溯码}/,见 outbound) + private mediaDir(templateId: number, archiveNo: string): string { + return `${templateId}/${archiveNo}`; + } + + // 把作品的既有媒体(主图/节点图/证书原件+水印件)归位到 {模板ID}/{档案编号}/, + // 文件名人类可读:作品图_{时间戳}_{序号} / 节点-{标题}_... / 证书-{名称}_...; + // 同步更新 DB 引用,返回 oldKey->newKey 映射(供调用方改写快照/DTO 中的旧引用)。 + private async relocateArtworkMedia(artworkId: number): Promise> { + const keyMap = new Map(); + const artwork = await this.prisma.artwork.findFirst({ + where: { id: artworkId, deletedAt: null }, + include: { traceNodes: true, certificates: true }, + }); + if (!artwork?.archiveNo) return keyMap; + const dir = this.mediaDir(artwork.templateId, artwork.archiveNo); + + const images = await this.storage.relocateMedia((artwork.images ?? []) as unknown as MediaItem[], dir, '作品图'); + images.keyMap.forEach((v, k) => keyMap.set(k, v)); + if (images.changed) { + await this.prisma.artwork.update({ + where: { id: artworkId }, + data: { images: images.items as unknown as Prisma.InputJsonValue }, + }); + } + + for (const node of artwork.traceNodes) { + const media = await this.storage.relocateMedia( + (node.mediaFiles ?? []) as unknown as MediaItem[], + dir, + `节点-${this.storage.sanitizeSegment(node.title)}`, + ); + media.keyMap.forEach((v, k) => keyMap.set(k, v)); + if (media.changed) { + await this.prisma.traceNode.update({ + where: { id: node.id }, + data: { mediaFiles: media.items as unknown as Prisma.InputJsonValue }, + }); + } + } + + for (const cert of artwork.certificates) { + const origin = await this.storage.relocateMedia( + [{ key: cert.originFileUrl }], + dir, + `证书-${this.storage.sanitizeSegment(cert.name)}`, + ); + const newOrigin = origin.items[0]?.key ?? cert.originFileUrl; + let newWatermark = cert.watermarkFileUrl; + if (origin.changed) { + keyMap.set(cert.originFileUrl, newOrigin); + // 水印件跟随原件命名(derivedKey 加 _wm 后缀、同目录) + if (cert.watermarkFileUrl) { + newWatermark = await this.storage.moveKey(cert.watermarkFileUrl, this.storage.derivedKey(newOrigin, 'wm')); + if (newWatermark !== cert.watermarkFileUrl) keyMap.set(cert.watermarkFileUrl, newWatermark); + } + await this.prisma.certificate.update({ + where: { id: cert.id }, + data: { originFileUrl: newOrigin, watermarkFileUrl: newWatermark }, + }); + } + } + return keyMap; + } + + // 用 oldKey->newKey 映射改写媒体数组引用 + private remapMedia(items: MediaItem[] | undefined, keyMap: Map): MediaItem[] | undefined { + if (!items?.length || !keyMap.size) return items; + return items.map((item) => { + const next = item?.key ? keyMap.get(item.key) : undefined; + return next ? { ...item, key: next, ...(item.url ? { url: this.storage.getUrl(next) } : {}) } : item; + }); + } + async create(dto: CreateArtworkDto, userId: number) { const tpl = await this.prisma.template.findFirst({ where: { id: dto.templateId, deletedAt: null }, @@ -94,7 +169,7 @@ export class ArtworkService { dto.traceNodes === undefined ? DEFAULT_TRACE_NODES : this.normalizeTraceNodeDto(dto.traceNodes); const certificates = this.normalizeCertificateDto(dto.certificates ?? []); - const artwork = await this.prisma.$transaction(async (tx) => { + const { created: artwork, revisionId } = await this.prisma.$transaction(async (tx) => { const created = await tx.artwork.create({ data: { templateId: dto.templateId, @@ -136,7 +211,7 @@ export class ArtworkService { const archiveNo = this.buildArchiveNo(created.id); await tx.artwork.update({ where: { id: created.id }, data: { archiveNo } }); const snapshot = this.snapshotFromRecord(created); - await tx.artworkRevision.create({ + const revision = await tx.artworkRevision.create({ data: { artworkId: created.id, title: status === ArtworkStatus.DRAFT ? '创建草稿' : '提交初次审核', @@ -147,9 +222,24 @@ export class ArtworkService { submittedBy: userId, }, }); - return created; + return { created, revisionId: revision.id }; }); + // 媒体归位到 {模板ID}/{档案编号}/(档案编号在事务内生成,只能事后归位),并同步初始快照引用 + const keyMap = await this.relocateArtworkMedia(artwork.id); + if (keyMap.size) { + const refreshed = await this.prisma.artwork.findFirst({ + where: { id: artwork.id }, + include: { traceNodes: true, certificates: true }, + }); + if (refreshed) { + await this.prisma.artworkRevision.update({ + where: { id: revisionId }, + data: { afterSnapshot: this.snapshotFromRecord(refreshed) as unknown as Prisma.InputJsonObject }, + }); + } + } + await this.enqueuePendingCertificateWatermarks(artwork.id); return this.get(artwork.id); } @@ -269,6 +359,45 @@ export class ArtworkService { async update(id: number, dto: UpdateArtworkDto, user: AuthUser) { const userId = user.id; + const artwork = await this.ensureExists(id); + // 先把既有媒体归位(含历史日期目录的旧文件),拿到 old->new 映射改写 DTO 引用; + // 再把 DTO 里新上传的媒体(仍在通用上传目录)归位,保证快照/落库全部使用最终 key + const keyMap = await this.relocateArtworkMedia(id); + const dir = artwork.archiveNo ? this.mediaDir(artwork.templateId, artwork.archiveNo) : null; + + let dtoImages = this.remapMedia(dto.images as MediaItem[] | undefined, keyMap); + if (dtoImages && dir) { + dtoImages = (await this.storage.relocateMedia(dtoImages, dir, '作品图')).items; + } + let dtoNodes = dto.traceNodes ? this.normalizeTraceNodeDto(dto.traceNodes) : undefined; + if (dtoNodes && dir) { + dtoNodes = await Promise.all( + dtoNodes.map(async (node) => { + const media = this.remapMedia(node.mediaFiles, keyMap) ?? []; + const relocated = await this.storage.relocateMedia(media, dir, `节点-${this.storage.sanitizeSegment(node.title)}`); + return { ...node, mediaFiles: relocated.items }; + }), + ); + } + let dtoCerts = dto.certificates ? this.normalizeCertificateDto(dto.certificates) : undefined; + if (dtoCerts && dir) { + dtoCerts = await Promise.all( + dtoCerts.map(async (cert) => { + let originKey = keyMap.get(cert.originKey) ?? cert.originKey; + if (!originKey.startsWith(`${dir}/`)) { + const relocated = await this.storage.relocateMedia( + [{ key: originKey }], + dir, + `证书-${this.storage.sanitizeSegment(cert.name)}`, + ); + originKey = relocated.items[0]?.key ?? originKey; + } + const watermarkKey = cert.watermarkKey ? keyMap.get(cert.watermarkKey) ?? cert.watermarkKey : cert.watermarkKey; + return { ...cert, originKey, watermarkKey }; + }), + ); + } + const current = await this.getSnapshot(id); const nextStatus = dto.status === ArtworkStatus.DRAFT ? ArtworkStatus.ACTIVE : dto.status ?? current.artwork.status; const afterSnapshot: ArtworkSnapshot = { @@ -278,13 +407,11 @@ export class ArtworkService { artist: dto.artist ?? current.artwork.artist, status: nextStatus, dynamicFields: dto.dynamicFields ?? current.artwork.dynamicFields, - images: (dto.images ?? current.artwork.images) as MediaItem[], + images: (dtoImages ?? current.artwork.images) as MediaItem[], }, - traceNodes: dto.traceNodes ? this.normalizeTraceNodeDto(dto.traceNodes) : current.traceNodes, - certificates: dto.certificates ? this.normalizeCertificateDto(dto.certificates) : current.certificates, + traceNodes: dtoNodes ?? current.traceNodes, + certificates: dtoCerts ?? current.certificates, }; - - const artwork = await this.ensureExists(id); const shouldApplyDirectly = artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED; const shouldAutoApprove = user.role === RoleType.SUPER_ADMIN; if (!this.hasSnapshotChanged(current, afterSnapshot)) { diff --git a/apps/api/src/outbound/import.processor.ts b/apps/api/src/outbound/import.processor.ts index 6222c03..76d54a4 100644 --- a/apps/api/src/outbound/import.processor.ts +++ b/apps/api/src/outbound/import.processor.ts @@ -41,18 +41,29 @@ export class ImportProcessor extends WorkerHost { let fail = 0; for (const row of rows) { try { - const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } }); + const code = await this.prisma.traceCode.findUnique({ + where: { shortCode: row.shortCode || '' }, + include: { artwork: { select: { templateId: true, archiveNo: true } } }, + }); if (!code) throw new Error('追溯码不存在'); // 预览到提交之间可能已被出库:再次校验,避免重复出库 if (isOutbound(code)) throw new Error('该追溯码已登记出库,不可重复出库'); - const imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys); + let imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys).map( + (item) => ({ key: item.key, name: item.name, type: item.type || 'image' }), + ); + // 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号} + if (imageItems.length && code.artwork?.archiveNo) { + const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`; + imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({ + ...item, + name: item.key.split('/').pop() || item.name, + })); + } await this.prisma.traceCode.update({ where: { id: code.id }, data: { outTime: row.outTime ?? undefined, - outImages: imageItems.length - ? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' })) - : undefined, + outImages: imageItems.length ? imageItems : undefined, remark: row.remark || undefined, }, }); diff --git a/apps/api/src/outbound/outbound.service.ts b/apps/api/src/outbound/outbound.service.ts index 156910d..0c04d83 100644 --- a/apps/api/src/outbound/outbound.service.ts +++ b/apps/api/src/outbound/outbound.service.ts @@ -32,7 +32,10 @@ export class OutboundService { ) {} async updateSingle(traceCodeId: bigint, dto: OutboundDto) { - const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } }); + const code = await this.prisma.traceCode.findUnique({ + where: { id: traceCodeId }, + include: { artwork: { select: { templateId: true, archiveNo: true } } }, + }); if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); // 一物一码只能出库一次:已登记出库时间或出库图任一即视为已出库 if (isOutbound(code)) { @@ -46,10 +49,17 @@ export class OutboundService { const data: Prisma.TraceCodeUpdateInput = {}; if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null; if ('outImageKeys' in dto || 'outImageKey' in dto) { + let imageItems = imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' })); + // 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号} + if (imageItems.length && code.artwork?.archiveNo) { + const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`; + imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({ + ...item, + name: item.key.split('/').pop() || item.name, + })); + } // 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致 - data.outImages = imageKeys.length - ? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' })) - : Prisma.DbNull; + data.outImages = imageItems.length ? imageItems : Prisma.DbNull; } if ('remark' in dto) data.remark = dto.remark || null; return this.prisma.traceCode.update({ diff --git a/apps/api/src/storage/storage.service.ts b/apps/api/src/storage/storage.service.ts index 7bff93c..2430696 100644 --- a/apps/api/src/storage/storage.service.ts +++ b/apps/api/src/storage/storage.service.ts @@ -23,6 +23,15 @@ const MIME_EXT: Record = { 'application/pdf': '.pdf', }; +const EXT_MIME: Record = Object.fromEntries( + Object.entries(MIME_EXT).map(([mime, ext]) => [ext, mime]), +); + +export interface RelocatableMedia { + key: string; + url?: string; +} + @Injectable() export class StorageService implements OnModuleInit { private readonly logger = new Logger(StorageService.name); @@ -120,6 +129,71 @@ export class StorageService implements OnModuleInit { return `${base}_${suffix}${ext || '.jpg'}`; } + // 清洗目录/文件名片段:去掉路径分隔与 Windows 非法字符,限长,空值兜底 + sanitizeSegment(name: string, fallback = '未命名'): string { + const cleaned = (name || '') + // eslint-disable-next-line no-control-regex + .replace(/[\\/:*?"<>|\x00-\x1f]/g, '') + .replace(/\s+/g, ' ') + .trim() + .replace(/^\.+|\.+$/g, ''); + return (cleaned || fallback).slice(0, 32); + } + + // 移动(重命名)一个存储对象;失败时保留原 key 并告警,绝不让业务流程因归位失败而中断 + async moveKey(oldKey: string, newKey: string): Promise { + if (!oldKey || oldKey === newKey) return oldKey; + try { + const buffer = await this.driver.get(oldKey); + await this.driver.put(newKey, buffer, { + contentType: EXT_MIME[extname(newKey).toLowerCase()], + cacheControl: STATIC_ASSET_CACHE_CONTROL, + }); + await this.driver.remove(oldKey).catch(() => undefined); + return newKey; + } catch (e) { + this.logger.warn(`媒体归位失败(${oldKey} -> ${newKey}):${(e as Error).message}`); + return oldKey; + } + } + + // 把一组媒体归位到指定目录,命名 {基础名}_{时间戳}_{序号}{扩展名}(人类可读)。 + // 已在目录内 / 外链(http/data:) 的条目跳过;同一 key 重复引用复用同一次移动结果。 + // 返回改写后的条目、是否有变化、oldKey->newKey 映射(供调用方同步改写其它引用)。 + async relocateMedia( + items: T[] | undefined | null, + dir: string, + baseName: string, + ): Promise<{ items: T[]; changed: boolean; keyMap: Map }> { + const list = Array.isArray(items) ? items : []; + const keyMap = new Map(); + const result: T[] = []; + const stamp = dayjs().format('YYYYMMDDHHmmss'); + let seq = 0; + let changed = false; + for (const item of list) { + const key = item?.key; + if (!key || /^(https?:|data:)/i.test(key) || key.startsWith(`${dir}/`)) { + result.push(item); + continue; + } + let nextKey = keyMap.get(key); + if (!nextKey) { + seq += 1; + const ext = extname(key) || '.jpg'; + nextKey = await this.moveKey(key, `${dir}/${baseName}_${stamp}_${seq}${ext}`); + if (nextKey !== key) keyMap.set(key, nextKey); + } + if (nextKey !== key) { + changed = true; + result.push({ ...item, key: nextKey, ...(item.url ? { url: this.getUrl(nextKey) } : {}) }); + } else { + result.push(item); + } + } + return { items: result, changed, keyMap }; + } + getUrl(key: string): string { return this.driver.getPublicUrl(key); }