来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
200 lines
6.9 KiB
TypeScript
200 lines
6.9 KiB
TypeScript
import path from 'path';
|
||
import { getStorageProvider } from './storageProvider';
|
||
import {
|
||
buildInspectionResultObjectName,
|
||
INSPECTION_PHOTO_BUCKETS,
|
||
INSPECTION_RESULT_FOLDERS,
|
||
mimeFromFilename,
|
||
parseProductSlugFromResultBasename,
|
||
sanitizeUploadExt,
|
||
type InspectionResultFolder,
|
||
} from './storageBucketConfig';
|
||
import {
|
||
INSPECTION_RESULT_FAIL,
|
||
INSPECTION_RESULT_PASS,
|
||
normalizeInspectionResult,
|
||
} from './inspectionResultUtils';
|
||
import { toEnglishProductSlug } from '../utils/englishProductSlug';
|
||
|
||
function resultFolderFromRating(qualityRating: string | null | undefined): InspectionResultFolder {
|
||
const rating = normalizeInspectionResult(qualityRating);
|
||
return rating === INSPECTION_RESULT_FAIL ? INSPECTION_RESULT_FAIL : INSPECTION_RESULT_PASS;
|
||
}
|
||
|
||
function parseBase64Photo(photo: string): { content: string; ext: string } | null {
|
||
const trimmed = String(photo || '').trim();
|
||
if (!trimmed) return null;
|
||
|
||
const dataUrl = /^data:image\/([a-zA-Z0-9+.-]+);base64,(.+)$/i.exec(trimmed);
|
||
if (dataUrl) {
|
||
const rawExt = dataUrl[1].toLowerCase().replace('jpeg', 'jpg');
|
||
return { content: dataUrl[2], ext: rawExt || 'jpg' };
|
||
}
|
||
|
||
if (trimmed.length > 200 && /^[A-Za-z0-9+/=\s]+$/.test(trimmed)) {
|
||
return { content: trimmed.replace(/\s+/g, ''), ext: 'jpg' };
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
function resolveExt(filenameOrExt: string, fallback = 'jpg') {
|
||
const raw = String(filenameOrExt || '').trim().toLowerCase().replace(/^\./, '');
|
||
const fromName = path.extname(raw).replace(/^\./, '');
|
||
const ext = (fromName || raw || fallback).replace(/[^a-z0-9]/g, '');
|
||
return ext || fallback;
|
||
}
|
||
|
||
/** 品名文件夹内的时点文件名(不再把 slug 拼进 basename) */
|
||
function buildTimedPhotoBasename(ext: string) {
|
||
const safeExt = resolveExt(ext);
|
||
return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${safeExt}`;
|
||
}
|
||
|
||
function normalizePhotoKey(photo: string) {
|
||
return String(photo || '')
|
||
.trim()
|
||
.replace(/\\/g, '/')
|
||
.replace(/^\/+/, '');
|
||
}
|
||
|
||
function isAlreadyInProductFolder(photo: string, folder: InspectionResultFolder, productSlug: string) {
|
||
const key = normalizePhotoKey(photo);
|
||
const prefix = `${folder}/${productSlug}/`;
|
||
return key.startsWith(prefix) && key.split('/').filter(Boolean).length === 3;
|
||
}
|
||
|
||
export async function saveBase64Upload(
|
||
bucket: string,
|
||
content: string,
|
||
ext = 'jpg',
|
||
options?: { folder?: InspectionResultFolder; productSlug?: string; objectPrefix?: string }
|
||
) {
|
||
// H11:客户端给的扩展名先收敛到该桶白名单(图片桶非法扩展名降级为 jpg,文档桶直接拒),
|
||
// 否则 `ext=html` 这类值会把 HTML 落进公共可读桶 → 存储型 XSS。
|
||
const basename = buildTimedPhotoBasename(sanitizeUploadExt(bucket, ext));
|
||
let filename: string;
|
||
if (options?.objectPrefix) {
|
||
const prefix = String(options.objectPrefix).replace(/^\/+|\/+$/g, '');
|
||
filename = `${prefix}/${basename}`;
|
||
} else if (options?.folder && options?.productSlug) {
|
||
filename = buildInspectionResultObjectName(options.folder, options.productSlug, basename);
|
||
} else if (options?.folder) {
|
||
filename = buildInspectionResultObjectName(options.folder, basename);
|
||
} else {
|
||
filename = basename;
|
||
}
|
||
const parsed = parseBase64Photo(content);
|
||
const buffer = Buffer.from(parsed?.content || content.replace(/^data:[^;]+;base64,/i, ''), 'base64');
|
||
await getStorageProvider().putObject(bucket, filename, buffer, mimeFromFilename(filename));
|
||
return filename;
|
||
}
|
||
|
||
/** 在逻辑桶下创建「合格 / 不合格」目录占位,便于对象存储控制台可见 */
|
||
export async function ensureInspectionResultFolders(bucket: string) {
|
||
const storage = getStorageProvider();
|
||
const marker = Buffer.from('keep\n', 'utf8');
|
||
for (const folder of INSPECTION_RESULT_FOLDERS) {
|
||
const key = buildInspectionResultObjectName(folder, '.keep');
|
||
if (await storage.exists(bucket, key)) continue;
|
||
await storage.putObject(bucket, key, marker, 'text/plain');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将验收最终照片落到:
|
||
* `合格|{不合格}/{englishSlug}/{timestamp}-{rand}.ext`
|
||
*/
|
||
export async function finalizeInspectionPhotosToResultFolder(options: {
|
||
bucket: (typeof INSPECTION_PHOTO_BUCKETS)[number];
|
||
qualityRating: string | null | undefined;
|
||
photos: string[];
|
||
productName?: string | null;
|
||
skuCode?: string | null;
|
||
}): Promise<string[]> {
|
||
const folder = resultFolderFromRating(options.qualityRating);
|
||
const productSlug = toEnglishProductSlug(options.productName, options.skuCode);
|
||
await ensureInspectionResultFolders(options.bucket);
|
||
|
||
const storage = getStorageProvider();
|
||
const out: string[] = [];
|
||
const folderPrefix = `${folder}/`;
|
||
|
||
for (const raw of options.photos) {
|
||
const photo = normalizePhotoKey(raw);
|
||
if (!photo) continue;
|
||
|
||
const parsed = parseBase64Photo(photo);
|
||
if (parsed) {
|
||
out.push(
|
||
await saveBase64Upload(options.bucket, parsed.content, parsed.ext, {
|
||
folder,
|
||
productSlug,
|
||
})
|
||
);
|
||
continue;
|
||
}
|
||
|
||
if (photo.startsWith('http://') || photo.startsWith('https://')) {
|
||
out.push(photo);
|
||
continue;
|
||
}
|
||
|
||
const parts = photo.split('/').filter(Boolean);
|
||
const currentBase = path.basename(photo);
|
||
if (!currentBase || currentBase === '.' || currentBase === '..') continue;
|
||
|
||
if (isAlreadyInProductFolder(photo, folder, productSlug)) {
|
||
out.push(photo);
|
||
continue;
|
||
}
|
||
|
||
// 旧二层:合格/tudou-ts-rand.jpg → 合格/tudou/ts-rand.jpg(尽量去掉 slug 前缀)
|
||
let destBase = currentBase;
|
||
if (parts.length === 2 && parts[0] === folder) {
|
||
const parsedSlug = parseProductSlugFromResultBasename(currentBase);
|
||
if (parsedSlug && currentBase.toLowerCase().startsWith(`${parsedSlug}-`)) {
|
||
destBase = currentBase.slice(parsedSlug.length + 1);
|
||
}
|
||
} else if (parts.length === 1) {
|
||
destBase = buildTimedPhotoBasename(resolveExt(currentBase));
|
||
} else {
|
||
destBase = buildTimedPhotoBasename(resolveExt(currentBase));
|
||
}
|
||
|
||
const dest = buildInspectionResultObjectName(folder, productSlug, destBase);
|
||
|
||
try {
|
||
const existing = await storage.getObject(options.bucket, photo);
|
||
if (existing?.buffer?.byteLength) {
|
||
await storage.putObject(
|
||
options.bucket,
|
||
dest,
|
||
existing.buffer,
|
||
existing.contentType || mimeFromFilename(dest)
|
||
);
|
||
if (photo !== dest) {
|
||
try {
|
||
await storage.deleteObject(options.bucket, photo);
|
||
} catch (err) {
|
||
console.warn(`[inspection-photos] 删除临时文件失败 ${options.bucket}/${photo}:`, err);
|
||
}
|
||
}
|
||
out.push(dest);
|
||
continue;
|
||
}
|
||
} catch (err) {
|
||
console.warn(`[inspection-photos] 迁移失败 ${options.bucket}/${photo}:`, err);
|
||
}
|
||
|
||
// 对象读不到时仍记录目标键,避免丢引用;调用方可能随后再传 base64
|
||
if (!photo.startsWith(folderPrefix)) {
|
||
out.push(dest);
|
||
} else {
|
||
out.push(dest);
|
||
}
|
||
}
|
||
|
||
return out;
|
||
}
|