Clean up web debug logs and repair test fixtures
This commit is contained in:
parent
06c82a58e5
commit
a6f0551bf2
@ -20,8 +20,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const { userId, department } = await request.json();
|
||||
|
||||
console.log('[Update Department] Request:', { userId, department });
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ error: '缺少用户ID' },
|
||||
|
||||
@ -33,7 +33,6 @@ export async function GET(request: NextRequest) {
|
||||
} catch (err) {
|
||||
// 忽略关闭错误(可能已经关闭)
|
||||
}
|
||||
console.log('[Danmaku SSE] Connection closed and cleaned up');
|
||||
};
|
||||
|
||||
try {
|
||||
@ -53,13 +52,11 @@ export async function GET(request: NextRequest) {
|
||||
// 检查是否超时(无活动或连接时间过长)
|
||||
const now = Date.now();
|
||||
if (now - lastActivity > maxIdleTime) {
|
||||
console.log('[Danmaku SSE] Connection idle timeout, closing');
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
if (now - connectionStartTime > maxConnectionTime) {
|
||||
console.log('[Danmaku SSE] Connection time limit reached, closing');
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
@ -83,7 +80,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
// 客户端断开连接时清理
|
||||
request.signal.addEventListener('abort', () => {
|
||||
console.log('[Danmaku SSE] Client aborted connection');
|
||||
cleanup();
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@ -44,8 +44,6 @@ export async function POST(request: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
console.log('完善用户信息(选择部门):', { userId: authorizedUserId, department: normalizedDepartment })
|
||||
|
||||
// 获取当前钉钉用户信息
|
||||
const currentUser = await prisma.user.findUnique({
|
||||
where: { id: authorizedUserId }
|
||||
@ -82,8 +80,6 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
})
|
||||
|
||||
console.log('用户信息更新成功:', user.username)
|
||||
|
||||
// 返回用户信息(不包含敏感信息)
|
||||
const response = NextResponse.json({
|
||||
success: true,
|
||||
|
||||
@ -110,25 +110,8 @@ function buildPublicUrl(path: string, request?: NextRequest) {
|
||||
}
|
||||
|
||||
function appendSetCookies(target: NextResponse, cookies: string[]) {
|
||||
const cookieNames: string[] = []
|
||||
|
||||
for (const cookie of cookies) {
|
||||
target.headers.append('set-cookie', cookie)
|
||||
const cookieName = String(cookie).split('=', 1)[0]?.trim()
|
||||
if (cookieName) {
|
||||
cookieNames.push(cookieName)
|
||||
}
|
||||
}
|
||||
|
||||
return cookieNames
|
||||
}
|
||||
|
||||
function getRequestHeaderSnapshot(request: NextRequest) {
|
||||
return {
|
||||
host: request.headers.get('host') || '',
|
||||
forwardedHost: request.headers.get('x-forwarded-host') || '',
|
||||
forwardedProto: request.headers.get('x-forwarded-proto') || '',
|
||||
userAgent: request.headers.get('user-agent')?.includes('DingTalk') ? 'DingTalk' : 'other',
|
||||
}
|
||||
}
|
||||
|
||||
@ -218,13 +201,7 @@ ${SURVEY_OPENING_PAGE_MARKUP}
|
||||
},
|
||||
)
|
||||
|
||||
const cookieNames = appendSetCookies(response, cookies)
|
||||
console.log('[Dingtalk H5] 已在免登落地页写入会话Cookie:', {
|
||||
redirectPath,
|
||||
redirectUrl,
|
||||
cookieNames,
|
||||
requestHeaders: getRequestHeaderSnapshot(request),
|
||||
})
|
||||
appendSetCookies(response, cookies)
|
||||
return response
|
||||
}
|
||||
|
||||
@ -238,11 +215,6 @@ function createPerformanceSurveySessionTransferPage({
|
||||
token: string
|
||||
}) {
|
||||
const redirectUrl = buildPublicUrl(redirectPath, request)
|
||||
console.log('[Dingtalk H5] 已生成考核调研钉钉访问凭证:', {
|
||||
redirectPath,
|
||||
redirectUrl,
|
||||
requestHeaders: getRequestHeaderSnapshot(request),
|
||||
})
|
||||
|
||||
const response = new NextResponse(
|
||||
`<!doctype html>
|
||||
@ -432,14 +404,6 @@ async function handleH5LoginPage(request: NextRequest, code: string) {
|
||||
request.nextUrl.searchParams.get('redirect'),
|
||||
'/performance-survey',
|
||||
)
|
||||
const source = request.nextUrl.searchParams.get('source') || ''
|
||||
|
||||
console.log('[Dingtalk H5] 收到免登入口请求:', {
|
||||
hasCode: Boolean(code),
|
||||
redirectPath,
|
||||
source,
|
||||
requestHeaders: getRequestHeaderSnapshot(request),
|
||||
})
|
||||
|
||||
if (!code) {
|
||||
return createH5LoginErrorPage('暂时无法打开页面,请从最新通知重新进入。')
|
||||
|
||||
@ -46,24 +46,8 @@ function buildRedirectUrl(path: string, request?: NextRequest, targetOrigin?: st
|
||||
}
|
||||
|
||||
function appendSetCookies(target: NextResponse, cookies: string[]) {
|
||||
const cookieNames: string[] = []
|
||||
|
||||
for (const cookie of cookies) {
|
||||
target.headers.append('set-cookie', cookie)
|
||||
const cookieName = String(cookie).split('=', 1)[0]?.trim()
|
||||
if (cookieName) {
|
||||
cookieNames.push(cookieName)
|
||||
}
|
||||
}
|
||||
|
||||
return cookieNames
|
||||
}
|
||||
|
||||
function getRequestHeaderSnapshot(request: NextRequest) {
|
||||
return {
|
||||
host: request.headers.get('host') || '',
|
||||
forwardedHost: request.headers.get('x-forwarded-host') || '',
|
||||
forwardedProto: request.headers.get('x-forwarded-proto') || '',
|
||||
}
|
||||
}
|
||||
|
||||
@ -190,13 +174,7 @@ ${LOGIN_TRANSITION_PAGE_MARKUP}
|
||||
},
|
||||
)
|
||||
|
||||
const cookieNames = appendSetCookies(response, cookies)
|
||||
console.log('[Dingtalk H5] 通过一次性票据写入会话Cookie并返回落地页:', {
|
||||
redirectPath,
|
||||
redirectUrl,
|
||||
cookieNames,
|
||||
requestHeaders: getRequestHeaderSnapshot(request),
|
||||
})
|
||||
appendSetCookies(response, cookies)
|
||||
return response
|
||||
}
|
||||
|
||||
|
||||
21
app/api/external/download/route.ts
vendored
21
app/api/external/download/route.ts
vendored
@ -190,22 +190,6 @@ async function handleDownload(request: NextRequest) {
|
||||
const isTaskMaterial = ['任务-详情', '任务-页面', '任务-其他', '任务-3D原图', '任务-AI原图', '任务-实拍原图', '任务-视频截图'].includes(material.materialType);
|
||||
|
||||
if (isTaskMaterial) {
|
||||
console.log(`[external/download] ========== 任务类型素材下载 ==========`);
|
||||
console.log(`[external/download] materialId: ${materialId}`);
|
||||
console.log(`[external/download] materialType: ${material.materialType}`);
|
||||
console.log(`[external/download] taskNo: ${material.taskNo}`);
|
||||
console.log(`[external/download] downloadType: ${downloadType}`);
|
||||
console.log(`[external/download] zipFilePath: ${material.zipFilePath || '(无)'}`);
|
||||
console.log(`[external/download] 数据库中资产总数: ${material.assets?.length || 0}`);
|
||||
|
||||
// 按类型统计资产数量
|
||||
const assetsByType: Record<string, number> = {};
|
||||
(material.assets || []).forEach((a: any) => {
|
||||
assetsByType[a.assetType] = (assetsByType[a.assetType] || 0) + 1;
|
||||
});
|
||||
console.log(`[external/download] 资产分布:`, assetsByType);
|
||||
console.log(`[external/download] ====================================`);
|
||||
|
||||
if (isProductPackageType(material.materialType)) {
|
||||
// 任务-详情:使用预先生成的zip文件
|
||||
|
||||
@ -213,7 +197,6 @@ async function handleDownload(request: NextRequest) {
|
||||
if (downloadType === 'all') {
|
||||
const allZipAsset = material.assets.find((a: any) => a.assetType === 'all');
|
||||
if (allZipAsset) {
|
||||
console.log(`[external/download] 使用 all.zip: ${allZipAsset.fileUrl}`);
|
||||
return await downloadSingleFile(allZipAsset, rangeHeader);
|
||||
}
|
||||
|
||||
@ -238,7 +221,6 @@ async function handleDownload(request: NextRequest) {
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
console.log(`[external/download] 使用 ${downloadType}.zip: ${zipAsset.fileUrl}`);
|
||||
return await downloadSingleFile(zipAsset, rangeHeader);
|
||||
}
|
||||
|
||||
@ -865,8 +847,6 @@ async function downloadNonProductPackageMaterial(material: any, downloadType: st
|
||||
try {
|
||||
await access(localZipPath);
|
||||
|
||||
console.log(`[external/download] 使用本地 ZIP 文件: ${localZipPath}`);
|
||||
|
||||
const ext = path.extname(material.zipFileName || localZipPath) || '.zip';
|
||||
|
||||
const filenameParts = [
|
||||
@ -895,7 +875,6 @@ async function downloadNonProductPackageMaterial(material: any, downloadType: st
|
||||
// 仅兼容历史素材:部分音频/视频源文件曾把 S3 URL 写入 zipFileName。
|
||||
// 新视频源以 videoSourceUrl 对应的生产 uploads/NAS 文件为准,预览产物才写入 S3。
|
||||
if (zipUrl && isHttpUrl(zipUrl)) {
|
||||
console.log('[external/download] zipFilePath empty, proxy S3 url from zipFileName:', zipUrl);
|
||||
|
||||
const urlObj = new URL(zipUrl);
|
||||
const extFromUrl = path.extname(urlObj.pathname) || '';
|
||||
|
||||
18
app/api/external/product-assets/route.ts
vendored
18
app/api/external/product-assets/route.ts
vendored
@ -113,7 +113,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
try {
|
||||
// 查询素材
|
||||
console.log('[external/product-assets] Querying material:', { taskNo, materialId });
|
||||
const found: any = materialId ? await getMaterialById(materialId) : await getMaterialByTaskNo(taskNo as string);
|
||||
let material = found && !isRestrictedMaterial(found)
|
||||
&& (!listingOnly || isXiaoyiDeliveryMaterial(found.materialType)) ? found : null;
|
||||
@ -123,14 +122,6 @@ export async function GET(request: NextRequest) {
|
||||
});
|
||||
if (!updated.count) material = null;
|
||||
}
|
||||
console.log('[external/product-assets] Material found:', material ? {
|
||||
id: material.id,
|
||||
taskNo: material.taskNo,
|
||||
materialType: material.materialType,
|
||||
taskStatus: material.taskStatus,
|
||||
assetsCount: material.assets?.length || 0,
|
||||
hasPreviewUrl: !!material.previewUrl,
|
||||
} : 'null');
|
||||
|
||||
if (!material) {
|
||||
await logApiCall({
|
||||
@ -166,8 +157,6 @@ export async function GET(request: NextRequest) {
|
||||
material.assets,
|
||||
Boolean(material.isFullSet),
|
||||
);
|
||||
console.log('[external/product-assets] Base URL:', baseUrl);
|
||||
console.log('[external/product-assets] Material type:', material.materialType);
|
||||
|
||||
if (isXiaoyiDeliveryMaterial(material.materialType)) {
|
||||
const requestedRevision = request.nextUrl.searchParams.get('revisionId')
|
||||
@ -312,13 +301,6 @@ export async function GET(request: NextRequest) {
|
||||
const detailAssets = (material.assets || []).filter((a: any) => a.assetType === ASSET_TYPE.DETAIL);
|
||||
const psdAssets = (material.assets || []).filter((a: any) => a.assetType === ASSET_TYPE.PSD);
|
||||
|
||||
console.log('[external/product-assets] Assets grouped:', {
|
||||
main: mainAssets.length,
|
||||
sku: skuAssets.length,
|
||||
detail: detailAssets.length,
|
||||
psd: psdAssets.length
|
||||
});
|
||||
|
||||
// 检查是否有资产(产品全案至少应该有主图、SKU图或详情图)
|
||||
if (mainAssets.length === 0 && skuAssets.length === 0 && detailAssets.length === 0) {
|
||||
console.warn('[external/product-assets] Warning: Product package material has no assets:', {
|
||||
|
||||
@ -182,8 +182,6 @@ async function handleProductPackageDownload(
|
||||
assetId?: string | null,
|
||||
validateOnly: boolean = false
|
||||
) {
|
||||
console.log(`[Download] ========== 任务-详情下载 ==========`);
|
||||
console.log(`[Download] materialId=${material.id}, downloadType=${downloadType}, assetId=${assetId}`);
|
||||
|
||||
// 查询资产
|
||||
let asset: any = null;
|
||||
@ -226,9 +224,6 @@ async function handleProductPackageDownload(
|
||||
? filePath
|
||||
: resolveStoredUploadPath(filePath);
|
||||
|
||||
console.log(`[Download] 文件路径: ${absolutePath}`);
|
||||
console.log(`[Download] 文件名: ${asset.fileName}`);
|
||||
|
||||
return serveFile(absolutePath, material, downloadType === 'all' ? '全部' : downloadType, validateOnly);
|
||||
}
|
||||
|
||||
@ -281,8 +276,6 @@ async function serveFile(filePath: string, material: any, fileNameSuffix: string
|
||||
|
||||
const stream = nodeReadableToWebStream(createReadStream(filePath));
|
||||
|
||||
console.log(`[Download] 开始下载: ${filename}, size=${fileStats.size} bytes`);
|
||||
|
||||
// 修复:记录下载日志并更新下载次数(在后台异步执行)
|
||||
recordDownloadLog(material.id).catch(err => {
|
||||
console.error('[Download] 记录下载日志失败:', err);
|
||||
@ -342,7 +335,6 @@ async function recordDownloadLog(materialId: string) {
|
||||
}),
|
||||
]);
|
||||
|
||||
console.log(`[Download] 记录下载日志成功: materialId=${materialId}, userId=${userId}`);
|
||||
} catch (error) {
|
||||
console.error('[Download] 记录下载日志失败:', error);
|
||||
// 不抛出错误,避免影响下载
|
||||
|
||||
@ -241,7 +241,6 @@ export async function GET(request: NextRequest) {
|
||||
const previewAsset = material.assets.find((a: any) => a.assetType === 'main-preview');
|
||||
if (previewAsset) {
|
||||
previewUrl = previewAsset.fileUrl;
|
||||
console.log('[Materials API] Using preview from assets:', previewUrl);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -216,15 +216,7 @@ export async function GET(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
rawAssetsForFullSet = rawAssets;
|
||||
|
||||
// 添加详细日志
|
||||
console.log(`[Share API] ========== 查询资产 ==========`);
|
||||
console.log(`[Share API] MaterialId: ${id}`);
|
||||
console.log(`[Share API] Total assets: ${rawAssets.length}`);
|
||||
rawAssets.forEach((asset: any, index: number) => {
|
||||
console.log(`[Share API] Asset ${index}: id=${asset.id}, type=${asset.assetType}, url=${asset.fileUrl}, fileName=${asset.fileName}`);
|
||||
});
|
||||
|
||||
|
||||
// 检查是否有重复的fileUrl
|
||||
const urlCounts: { [key: string]: { count: number; types: string[] } } = {};
|
||||
rawAssets.forEach((asset: any) => {
|
||||
@ -246,8 +238,6 @@ export async function GET(request: NextRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`[Share API] ====================================`);
|
||||
|
||||
// 将 BigInt 转换为字符串
|
||||
assets = rawAssets.map(asset => ({
|
||||
...asset,
|
||||
|
||||
@ -278,8 +278,6 @@ export async function POST(request: NextRequest) {
|
||||
executeTranscodeTask
|
||||
);
|
||||
|
||||
console.log(`[Transcode] Task queued for material ${normalizedMaterialId}`);
|
||||
|
||||
const queueStatus = isSystemAdministrator
|
||||
? await getOrganizationQueueStatus(canAccessG)
|
||||
: transcodeQueue.getStatus();
|
||||
|
||||
@ -54,13 +54,9 @@ export async function POST(req: NextRequest) {
|
||||
let releaseCrossProcessLock: MaterialUploadStorageLockRelease | null = null
|
||||
let releaseStorageReservation: (() => void) | null = null
|
||||
let pendingChunkPath: string | null = null
|
||||
console.log(`[UploadChunk] 📥 收到请求 at ${new Date().toISOString()}`)
|
||||
|
||||
try {
|
||||
const authStartedAt = Date.now()
|
||||
const userId = await getDesktopDeliveryUploadUserId(req, 'chunk') || await getAuthenticatedUploadUserId(req)
|
||||
const authTime = Date.now() - authStartedAt
|
||||
console.log(`[UploadChunk] 🔐 认证完成: ${authTime}ms`)
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 })
|
||||
@ -70,12 +66,7 @@ export async function POST(req: NextRequest) {
|
||||
// multipart 的 formData() 会完整解析请求体,必须先进入并发槽,不能让
|
||||
// 任意数量的 21MiB 请求在限流之外同时占用 Node 内存。
|
||||
releaseChunkSlot = await materialUploadChunkRequestLimiter.acquire()
|
||||
const payloadStartedAt = Date.now()
|
||||
const payload = await resolveChunkPayload(req)
|
||||
const payloadResolveTime = Date.now() - payloadStartedAt
|
||||
console.log(
|
||||
`[UploadChunk] 📦 请求参数解析完成: ${payloadResolveTime}ms, mode=${payload.mode}, chunkIndex=${payload.chunkIndex}`,
|
||||
)
|
||||
|
||||
if (!payload.uploadId || Number.isNaN(payload.chunkIndex)) {
|
||||
return NextResponse.json({ error: '缺少必要参数' }, { status: 400 })
|
||||
@ -90,13 +81,9 @@ export async function POST(req: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
const sessionStartedAt = Date.now()
|
||||
const sessionData = await getUploadSession(payload.uploadId)
|
||||
const getSessionTime = Date.now() - sessionStartedAt
|
||||
console.log(`[UploadChunk] 🔍 获取会话完成: ${getSessionTime}ms, 会话存在: ${!!sessionData}`)
|
||||
|
||||
if (!sessionData) {
|
||||
console.log(`[UploadChunk] ❌ 会话不存在: ${payload.uploadId}`)
|
||||
return NextResponse.json({ error: '上传会话不存在或已过期' }, { status: 404 })
|
||||
}
|
||||
|
||||
@ -149,10 +136,8 @@ export async function POST(req: NextRequest) {
|
||||
? sessionData.chunks.size
|
||||
: sessionData.chunks.size + 1
|
||||
|
||||
const mkdirStartedAt = Date.now()
|
||||
const tempDir = path.join(process.env.UPLOAD_DIR || './uploads', 'temp', payload.uploadId)
|
||||
await mkdir(tempDir, { recursive: true })
|
||||
const mkdirTime = Date.now() - mkdirStartedAt
|
||||
|
||||
releaseStorageReservation = await materialUploadStorageReservations.acquire(
|
||||
tempDir,
|
||||
@ -161,7 +146,6 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
const chunkFilePath = path.join(tempDir, `chunk-${payload.chunkIndex}`)
|
||||
pendingChunkPath = `${chunkFilePath}.partial-${randomUUID()}`
|
||||
const writeStartedAt = Date.now()
|
||||
const writtenBytes =
|
||||
payload.mode === 'raw'
|
||||
? await writeRawRequestBodyToFile(req, pendingChunkPath, MAX_CHUNK_BYTES)
|
||||
@ -184,29 +168,9 @@ export async function POST(req: NextRequest) {
|
||||
await rename(pendingChunkPath, chunkFilePath)
|
||||
pendingChunkPath = null
|
||||
|
||||
const writeTime = Date.now() - writeStartedAt
|
||||
|
||||
const statsStartedAt = Date.now()
|
||||
await updateChunkWithStats(payload.uploadId, payload.chunkIndex, chunkFilePath, writtenBytes)
|
||||
const updateChunkTime = Date.now() - statsStartedAt
|
||||
|
||||
const totalTime = Date.now() - requestStartTime
|
||||
console.log(`[UploadChunk] ⏱️ Chunk ${payload.chunkIndex}/${sessionData.totalChunks} 总耗时: ${totalTime}ms`, {
|
||||
认证: `${authTime}ms (${percent(authTime, totalTime)}%)`,
|
||||
请求参数解析: `${payloadResolveTime}ms (${percent(payloadResolveTime, totalTime)}%)`,
|
||||
获取会话: `${getSessionTime}ms (${percent(getSessionTime, totalTime)}%)`,
|
||||
创建目录: `${mkdirTime}ms (${percent(mkdirTime, totalTime)}%)`,
|
||||
流式写盘: `${writeTime}ms (${percent(writeTime, totalTime)}%)`,
|
||||
更新会话: `${updateChunkTime}ms (${percent(updateChunkTime, totalTime)}%)`,
|
||||
大小: `${(writtenBytes / 1024 / 1024).toFixed(2)}MB`,
|
||||
模式: payload.mode,
|
||||
})
|
||||
|
||||
if (writeTime / totalTime > 0.8) {
|
||||
console.log(
|
||||
`[UploadChunk] ⚠️ 流式写盘阶段占比 ${percent(writeTime, totalTime)}%,当前主要瓶颈仍在网络接收`,
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
@ -443,10 +407,3 @@ function safeDecodeURIComponent(value: string): string {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
function percent(part: number, total: number): string {
|
||||
if (total <= 0) {
|
||||
return '0.0'
|
||||
}
|
||||
return ((part / total) * 100).toFixed(1)
|
||||
}
|
||||
|
||||
@ -239,7 +239,6 @@ async function cleanupCompletedUpload(uploadId: string, chunkFiles: string[]): P
|
||||
|
||||
try {
|
||||
await deleteUploadSession(uploadId)
|
||||
console.log('[UploadComplete] 已删除会话:', uploadId)
|
||||
} catch (error) {
|
||||
console.warn('[UploadComplete] 删除会话失败(保留已验证的合并文件):', error)
|
||||
}
|
||||
|
||||
@ -154,8 +154,6 @@ export async function POST(req: NextRequest) {
|
||||
...(uploadPurpose ? { uploadPurpose } : {}),
|
||||
})
|
||||
|
||||
console.log(`[UploadInit] Created upload session: ${uploadId}, chunks: ${normalizedTotalChunks}`)
|
||||
|
||||
return NextResponse.json({ uploadId })
|
||||
} catch (error) {
|
||||
console.error('[UploadInit] Error:', error)
|
||||
|
||||
@ -20,13 +20,11 @@ export const dynamic = 'force-dynamic'
|
||||
* - ttl: number (秒)
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
console.log(`[RefreshSession] 收到会话刷新请求 at ${new Date().toISOString()}`)
|
||||
|
||||
try {
|
||||
// 验证用户身份
|
||||
const session = await getServerSession(authOptions)
|
||||
if (!session) {
|
||||
console.log(`[RefreshSession] 用户未登录`)
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 })
|
||||
}
|
||||
|
||||
@ -34,28 +32,22 @@ export async function POST(req: NextRequest) {
|
||||
const { uploadId } = await req.json()
|
||||
|
||||
if (!uploadId) {
|
||||
console.log(`[RefreshSession] 缺少uploadId参数`)
|
||||
return NextResponse.json(
|
||||
{ error: '缺少uploadId参数' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log(`[RefreshSession] 尝试刷新会话: ${uploadId}, 用户: ${(session.user as any).id}`)
|
||||
|
||||
// 刷新会话TTL
|
||||
const success = await refreshUploadSession(uploadId)
|
||||
|
||||
if (!success) {
|
||||
console.log(`[RefreshSession] 会话不存在或已过期: ${uploadId}`)
|
||||
return NextResponse.json(
|
||||
{ error: '会话不存在或已过期' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log(`[RefreshSession] 会话刷新成功: ${uploadId}, TTL: 8小时`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
uploadId,
|
||||
|
||||
@ -438,7 +438,6 @@ export async function POST(request: NextRequest) {
|
||||
let releaseUploadSessionLock: MaterialUploadStorageLockRelease | null = null;
|
||||
|
||||
try {
|
||||
console.log('[Upload] Starting upload process...');
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) {
|
||||
@ -661,20 +660,6 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[Upload] Form data received:', {
|
||||
hasPreviewImage: !!previewImage,
|
||||
previewImagesCount: previewImages.length,
|
||||
hasDisplayImage: !!displayImage,
|
||||
modelImagesCount: modelImages.length,
|
||||
hasZipFile: !!zipFile,
|
||||
hasExistingFilePath: !!existingFilePath,
|
||||
productModel,
|
||||
categoryName: resolvedCategoryName,
|
||||
sceneName: resolvedSceneName,
|
||||
materialType,
|
||||
materialTypeRaw,
|
||||
});
|
||||
|
||||
// 使用统一的验证逻辑验证必填字段
|
||||
if (!productModel) {
|
||||
return NextResponse.json(
|
||||
@ -774,11 +759,9 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
console.log('[Upload] Processing preview image (1/1)...');
|
||||
const buffer = Buffer.from(await previewImage.arrayBuffer());
|
||||
|
||||
// 压缩预览图
|
||||
console.log('[Upload] Compressing preview image...');
|
||||
const compressedBuffer = await compressImage(buffer, {
|
||||
maxSizeKB: 300,
|
||||
maxWidth: 1200,
|
||||
@ -788,7 +771,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const fileName = sanitizeFileName(previewImage.name);
|
||||
const filename = generateUniqueFilename('preview', '.webp');
|
||||
console.log('[Upload] Uploading compressed preview image to S3...');
|
||||
previewUrl = await uploadPublicDisplayToS3(
|
||||
compressedBuffer,
|
||||
buildMaterialPublicDisplayPath(filename),
|
||||
@ -796,14 +778,12 @@ export async function POST(request: NextRequest) {
|
||||
protectedMaterialId,
|
||||
);
|
||||
uploadedFileUrls.push(previewUrl); // 记录已上传的文件,用于失败时清理
|
||||
console.log('[Upload] Preview image uploaded:', previewUrl);
|
||||
}
|
||||
|
||||
// 处理其他预览图(作为展示图)。图片解码会使用 Sharp 原生内存,
|
||||
// 这里必须串行处理,避免一个请求内同时解码多张大图。
|
||||
// 详情页/详情模板:其他预览图也作为展示图处理
|
||||
if (previewImages.length > 0 && !['模特'].includes(materialType)) {
|
||||
console.log(`[Upload] Processing ${previewImages.length} preview images sequentially...`);
|
||||
|
||||
// 验证所有图片大小
|
||||
for (let i = 0; i < previewImages.length; i++) {
|
||||
@ -817,11 +797,9 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
for (let index = 0; index < previewImages.length; index += 1) {
|
||||
const image = previewImages[index]
|
||||
console.log(`[Upload] Processing preview image ${index + 2}/${previewImages.length + 1}...`);
|
||||
const buffer = Buffer.from(await image.arrayBuffer());
|
||||
|
||||
// 压缩预览图
|
||||
console.log(`[Upload] Compressing preview image ${index + 2}...`);
|
||||
const compressedBuffer = await compressImage(buffer, {
|
||||
maxSizeKB: 300,
|
||||
maxWidth: 1200,
|
||||
@ -830,7 +808,6 @@ export async function POST(request: NextRequest) {
|
||||
});
|
||||
|
||||
const filename = generateUniqueFilename(`preview-${index + 2}`, '.webp');
|
||||
console.log(`[Upload] Uploading compressed preview image ${index + 2} to S3...`);
|
||||
const url = await uploadPublicDisplayToS3(
|
||||
compressedBuffer,
|
||||
buildMaterialPublicDisplayPath(filename),
|
||||
@ -838,10 +815,8 @@ export async function POST(request: NextRequest) {
|
||||
protectedMaterialId,
|
||||
);
|
||||
uploadedFileUrls.push(url); // 记录已上传的文件,用于失败时清理
|
||||
console.log(`[Upload] Preview image ${index + 2} uploaded:`, url);
|
||||
displayImages.push(url);
|
||||
}
|
||||
console.log(`[Upload] All ${previewImages.length} preview images uploaded successfully`);
|
||||
}
|
||||
|
||||
// 处理展示图片(详情模板)- 后端自动压缩和切片
|
||||
@ -850,7 +825,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// 使用后端的 sliceImage 函数自动压缩和切片
|
||||
const { sliceImage } = await import('@/lib/image-processor');
|
||||
console.log('[Upload] Processing display image (backend slicing)...');
|
||||
const slices = await sliceImage(buffer, 1500, 500); // maxHeight=1500px, maxSizeKB=500KB
|
||||
|
||||
// 上传所有切片
|
||||
@ -869,9 +843,7 @@ export async function POST(request: NextRequest) {
|
||||
// 如果用户没有上传预览图,使用第一张切片作为预览图
|
||||
if (i === 0 && !previewUrl) {
|
||||
previewUrl = url;
|
||||
console.log('[Upload] Using first display image slice as preview (no user preview uploaded)');
|
||||
}
|
||||
console.log(`[Upload] Display image slice ${i + 1}/${slices.length} uploaded:`, url);
|
||||
}
|
||||
}
|
||||
|
||||
@ -898,7 +870,6 @@ export async function POST(request: NextRequest) {
|
||||
if (i === 0 && !previewUrl) {
|
||||
previewUrl = url;
|
||||
}
|
||||
console.log(`[Upload] Model image ${i + 1} uploaded:`, url);
|
||||
} catch (imageError) {
|
||||
console.error(`[Upload] Failed to process model image ${i + 1}:`, imageError);
|
||||
throw new Error(`处理图片 ${i + 1} 失败: ${imageError instanceof Error ? imageError.message : String(imageError)}`);
|
||||
@ -928,7 +899,6 @@ export async function POST(request: NextRequest) {
|
||||
if (!previewUrl) {
|
||||
previewUrl = url;
|
||||
}
|
||||
console.log(`[Upload] Display image ${i + 1} uploaded:`, url);
|
||||
} catch (imageError) {
|
||||
console.error(`[Upload] Failed to process display image ${i + 1}:`, imageError);
|
||||
throw new Error(`处理展示图 ${i + 1} 失败: ${imageError instanceof Error ? imageError.message : String(imageError)}`);
|
||||
@ -950,7 +920,6 @@ export async function POST(request: NextRequest) {
|
||||
ext = getUploadStorageExtension(zipFile.name);
|
||||
buffer = Buffer.from(await zipFile.arrayBuffer());
|
||||
zipFileSize = BigInt(buffer.length);
|
||||
console.log('[Upload] Using uploaded file buffer');
|
||||
} else {
|
||||
// 使用分片合并后的服务器侧文件
|
||||
sourcePath = ownedMergedUpload!.filePath;
|
||||
@ -981,7 +950,6 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
ext = getUploadStorageExtension(originalFileName || ownedMergedUpload!.session.fileName || sourcePath);
|
||||
console.log('[Upload] Using existing merged file:', sourcePath, 'size:', stat.size);
|
||||
}
|
||||
|
||||
const isVideoOrAudio = isVideoMaterial(materialType) || isAudioMaterial(materialType);
|
||||
@ -1056,11 +1024,9 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
// 已经移动到最终位置,不再额外清理
|
||||
sourcePath = '';
|
||||
console.log('[Upload] Moved merged file to final path (no re-copy):', zipFilePath);
|
||||
} else if (buffer) {
|
||||
// 直传场景:使用内存中的 buffer 写入
|
||||
await fs.writeFile(zipFilePath, buffer);
|
||||
console.log('[Upload] File saved locally:', zipFilePath);
|
||||
} else {
|
||||
throw new Error('未找到可写入的素材文件数据');
|
||||
}
|
||||
@ -1074,23 +1040,13 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// PDF:从PDF文件提取第一页作为预览图(在文件保存后)
|
||||
if (materialType === '品牌VI灵感') {
|
||||
console.log('[Upload] 开始处理品牌VI灵感PDF预览图提取...');
|
||||
console.log('[Upload] PDF文件路径:', zipFilePath);
|
||||
|
||||
// 强制提取PDF预览图,即使已有previewUrl也要重新提取(确保是图片而不是PDF文件)
|
||||
const pdfResult = await processPdfUpload(zipFilePath, '', protectedMaterialId);
|
||||
|
||||
console.log('[Upload] PDF预览图提取结果:', {
|
||||
success: pdfResult.success,
|
||||
hasPreviewUrl: !!pdfResult.previewUrl,
|
||||
previewUrl: pdfResult.previewUrl,
|
||||
error: pdfResult.error
|
||||
});
|
||||
|
||||
if (pdfResult.success && pdfResult.previewUrl) {
|
||||
previewUrl = pdfResult.previewUrl;
|
||||
uploadedFileUrls.push(previewUrl);
|
||||
console.log('[Upload] ✅ PDF预览图提取成功,已设置previewUrl:', previewUrl);
|
||||
} else {
|
||||
const errorMsg = pdfResult.error || '未知错误';
|
||||
console.error('[Upload] ❌ PDF预览图提取失败:', errorMsg);
|
||||
@ -1105,16 +1061,9 @@ export async function POST(request: NextRequest) {
|
||||
// 音频:尝试从本地文件/缓冲中解析封面信息,仅用于生成预览图,源文件仍本地化
|
||||
if (materialType === '音乐' && zipFile && buffer && isAudioFile(zipFile.type)) {
|
||||
try {
|
||||
console.log('[Upload] Audio file detected, parsing metadata and extracting cover image...');
|
||||
const audioMetadata = await parseAudioMetadata(buffer, zipFile.type);
|
||||
|
||||
if (audioMetadata) {
|
||||
console.log('[Upload] Audio metadata parsed:', {
|
||||
duration: audioMetadata.duration,
|
||||
durationFormatted: audioMetadata.durationFormatted,
|
||||
format: audioMetadata.format,
|
||||
hasPicture: !!audioMetadata.picture,
|
||||
});
|
||||
|
||||
// 如果音频文件包含封面图,提取并上传到 MinIO 作为预览
|
||||
if (audioMetadata.picture && !previewUrl) {
|
||||
@ -1126,7 +1075,6 @@ export async function POST(request: NextRequest) {
|
||||
const pictureUrl = await uploadToS3(pictureBuffer, pictureFilename, pictureFormat, protectedMaterialId);
|
||||
previewUrl = pictureUrl;
|
||||
uploadedFileUrls.push(pictureUrl); // 记录已上传的文件,用于失败时清理
|
||||
console.log('[Upload] Audio cover image extracted and uploaded:', pictureUrl);
|
||||
} catch (coverError) {
|
||||
console.error('[Upload] Failed to upload audio cover image:', coverError);
|
||||
}
|
||||
@ -1146,9 +1094,7 @@ export async function POST(request: NextRequest) {
|
||||
const { cleanupUploadSession } = await import('@/lib/temp-cleanup');
|
||||
const uploadId = path.basename(tempDir);
|
||||
const success = await cleanupUploadSession(uploadId);
|
||||
if (success) {
|
||||
console.log('[Upload] 已清理临时目录:', tempDir);
|
||||
} else {
|
||||
if (!success) {
|
||||
console.warn('[Upload] 清理临时目录失败:', tempDir);
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
@ -1160,7 +1106,6 @@ export async function POST(request: NextRequest) {
|
||||
// 音频素材:如果没有预览图,使用占位符
|
||||
if (materialType === '音乐' && (!previewUrl || previewUrl.trim() === '')) {
|
||||
previewUrl = AUDIO_PLACEHOLDER
|
||||
console.log('[Upload] Audio material without cover image, using audio placeholder')
|
||||
}
|
||||
|
||||
// 验证买家秀图片必须有至少一张图片和预览图
|
||||
@ -1192,16 +1137,6 @@ export async function POST(request: NextRequest) {
|
||||
? previewUrl
|
||||
: null;
|
||||
|
||||
// 最终保存前的previewUrl验证
|
||||
if (materialType === '品牌VI灵感') {
|
||||
console.log('[Upload] ========== 品牌VI灵感预览图最终检查 ==========');
|
||||
console.log('[Upload] previewUrl:', previewUrl);
|
||||
console.log('[Upload] previewUrl是否为空:', !previewUrl || previewUrl.trim() === '');
|
||||
console.log('[Upload] previewUrl是否为PDF文件:', previewUrl && previewUrl.endsWith('.pdf'));
|
||||
console.log('[Upload] previewUrl是否为图片文件:', previewUrl && (previewUrl.endsWith('.jpg') || previewUrl.endsWith('.jpeg') || previewUrl.endsWith('.png') || previewUrl.endsWith('.webp')));
|
||||
console.log('[Upload] ============================================');
|
||||
}
|
||||
|
||||
// SKU模板:如果没有预览图,使用占位符
|
||||
if (materialType === 'SKU模版' && (!previewUrl || previewUrl.trim() === '')) {
|
||||
console.warn('[Upload] ⚠️ SKU模板没有预览图,使用占位符');
|
||||
@ -1308,7 +1243,6 @@ export async function POST(request: NextRequest) {
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[Upload] Database record created:', material.id);
|
||||
materialId = material.id; // 保存materialId,用于失败时清理
|
||||
invalidateMaterialFacetsCache();
|
||||
|
||||
@ -1399,7 +1333,6 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
const { cleanupUploadSession } = await import('@/lib/temp-cleanup');
|
||||
await cleanupUploadSession(ownedMergedUpload.uploadId);
|
||||
console.log('[Upload] 已清理上传会话:', ownedMergedUpload.uploadId);
|
||||
} catch (cleanupError) {
|
||||
console.warn('[Upload] 清理上传会话失败(忽略):', cleanupError);
|
||||
}
|
||||
@ -1411,9 +1344,6 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// 不 await,让入队操作在后台异步执行,不阻塞上传接口返回 201
|
||||
enqueueVideoTranscodeTask(material.id, videoSourceUrl, needsCoverImage)
|
||||
.then(() => {
|
||||
console.log('[Upload] ✅ Video transcode task enqueued successfully:', material.id);
|
||||
})
|
||||
.catch(async (e: any) => {
|
||||
// 入队失败时保持 pending 可恢复状态。canonical 源视频必须保留,
|
||||
// 60 秒周期扫描会重新装载该任务,错误信息仅用于诊断。
|
||||
|
||||
@ -78,7 +78,6 @@ export async function POST(request: NextRequest) {
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
// 压缩预览图
|
||||
console.log('[Preview Upload] Compressing preview image...');
|
||||
const compressedBuffer = await compressImage(buffer, {
|
||||
maxSizeKB: 300,
|
||||
maxWidth: 1200,
|
||||
@ -88,10 +87,8 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
// 生成文件名并上传到S3
|
||||
const filename = generateUniqueFilename('preview', '.webp');
|
||||
console.log('[Preview Upload] Uploading compressed preview image to S3...');
|
||||
const url = await uploadToS3(compressedBuffer, filename, 'image/webp');
|
||||
|
||||
console.log('[Preview Upload] Preview image uploaded:', url);
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error('上传预览图失败:', error);
|
||||
|
||||
@ -53,12 +53,6 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`[S3 Original Upload] ========== Processing original file ==========`);
|
||||
console.log(`[S3 Original Upload] Type: ${type}`);
|
||||
console.log(`[S3 Original Upload] Original fileName: ${file.name}`);
|
||||
console.log(`[S3 Original Upload] File size: ${file.size} bytes (${(file.size / 1024 / 1024).toFixed(2)} MB)`);
|
||||
console.log(`[S3 Original Upload] ⚠️ NO COMPRESSION - Uploading as-is`);
|
||||
|
||||
// 读取文件buffer(不压缩)
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
|
||||
@ -69,15 +63,9 @@ export async function POST(request: NextRequest) {
|
||||
const fileName = `${type}-${timestamp}-${randomSuffix}.${extension}`;
|
||||
const s3Path = `product-package/${fileName}`;
|
||||
|
||||
console.log(`[S3 Original Upload] Generated fileName: ${fileName}`);
|
||||
console.log(`[S3 Original Upload] S3 path: ${s3Path}`);
|
||||
|
||||
// 直接上传原图到 S3(不压缩)
|
||||
const url = await uploadToS3(buffer, s3Path, file.type || 'image/jpeg');
|
||||
|
||||
console.log(`[S3 Original Upload] Uploaded successfully: url=${url}`);
|
||||
console.log(`[S3 Original Upload] ==========================================`);
|
||||
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error('[S3 Original Upload] Error:', error);
|
||||
|
||||
@ -57,28 +57,15 @@ export async function POST(request: NextRequest) {
|
||||
// 保持原始格式,不转换为webp
|
||||
const mimeType = file.type || 'image/jpeg';
|
||||
|
||||
console.log(`[S3 Upload] ========== Processing file (NO COMPRESSION) ==========`);
|
||||
console.log(`[S3 Upload] Type: ${type}`);
|
||||
console.log(`[S3 Upload] Original fileName: ${file.name}`);
|
||||
console.log(`[S3 Upload] Original file size: ${buffer.length} bytes (${(buffer.length / 1024 / 1024).toFixed(2)} MB)`);
|
||||
console.log(`[S3 Upload] MIME type: ${mimeType}`);
|
||||
console.log(`[S3 Upload] 任务-详情类型:保持原图质量,不做压缩处理`);
|
||||
|
||||
// 生成文件路径(保持原始格式)
|
||||
const timestamp = Date.now();
|
||||
const randomSuffix = Math.random().toString(36).substring(2, 9); // 7位随机字符串
|
||||
const fileName = `${type}-${timestamp}-${randomSuffix}${originalExt}`;
|
||||
const s3Path = `product-package/${fileName}`;
|
||||
|
||||
console.log(`[S3 Upload] Generated fileName: ${fileName}`);
|
||||
console.log(`[S3 Upload] S3 path: ${s3Path}`);
|
||||
|
||||
// 直接上传原图到 S3(不压缩)
|
||||
const url = await uploadToS3(buffer, s3Path, mimeType);
|
||||
|
||||
console.log(`[S3 Upload] Uploaded successfully: url=${url}`);
|
||||
console.log(`[S3 Upload] ====================================`);
|
||||
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error('[S3 Upload] Error:', error);
|
||||
|
||||
@ -19,10 +19,7 @@ export async function POST(request: NextRequest) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const userId = session?.user ? (session.user as any).id : undefined;
|
||||
|
||||
console.log('[UserAvatar] Session:', { userId, hasSession: !!session, hasUser: !!session?.user });
|
||||
|
||||
if (!userId) {
|
||||
console.log('[UserAvatar] No user ID in session');
|
||||
return NextResponse.json({ error: '未登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
@ -43,12 +40,9 @@ export async function POST(request: NextRequest) {
|
||||
const avatar = formData.get('avatar') as File | null;
|
||||
|
||||
if (!avatar) {
|
||||
console.log('[UserAvatar] No avatar file provided');
|
||||
return NextResponse.json({ error: '请选择头像文件' }, { status: 400 });
|
||||
}
|
||||
|
||||
console.log('[UserAvatar] File info:', { name: avatar.name, type: avatar.type, size: avatar.size });
|
||||
|
||||
// 验证文件类型
|
||||
if (!['image/jpeg', 'image/jpg', 'image/png', 'image/webp'].includes(avatar.type)) {
|
||||
return NextResponse.json(
|
||||
@ -77,21 +71,14 @@ export async function POST(request: NextRequest) {
|
||||
// 上传到S3
|
||||
const fileName = `avatar-${userId}-${Date.now()}.webp`;
|
||||
|
||||
console.log('[UserAvatar] Uploading to S3:', fileName, `(${(compressedBuffer.length / 1024).toFixed(2)}KB)`);
|
||||
|
||||
const avatarUrl = await uploadToS3(compressedBuffer, fileName, 'image/webp');
|
||||
|
||||
console.log('[UserAvatar] S3 URL:', avatarUrl);
|
||||
|
||||
// 更新用户头像
|
||||
console.log('[UserAvatar] Updating user:', userId);
|
||||
const updatedUser = await prisma.user.update({
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { avatar: avatarUrl },
|
||||
});
|
||||
|
||||
console.log('[UserAvatar] User updated:', { id: updatedUser.id, avatar: updatedUser.avatar });
|
||||
|
||||
// 规范化URL
|
||||
const normalizedUrl = normalizeUrl(avatarUrl);
|
||||
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
/** @jest-environment node */
|
||||
import path from 'node:path'
|
||||
import type { readArtPointConfiguration } from '../art-workflow-point-configuration'
|
||||
|
||||
jest.mock('node:fs/promises', () => ({ readFile: jest.fn() }))
|
||||
@ -41,7 +42,7 @@ test('远程免扣按流程、人员、角色去重,不叠加本地文件,
|
||||
request.mockResolvedValue(response(payload([contribution, contribution, { ...contribution, name: '策划乙', overtimeExempted: false }])))
|
||||
expect(await readConfiguration()).toEqual({ deductions, overtimeExemptions: [{ workflowKey: 'flow', name: '策划甲', role: 'planner' }] })
|
||||
expect(readFile).toHaveBeenCalledTimes(1)
|
||||
expect(readFile).toHaveBeenCalledWith('/private-config/deductions.json', 'utf8')
|
||||
expect(readFile).toHaveBeenCalledWith(path.join('/private-config', 'deductions.json'), 'utf8')
|
||||
expect(request).toHaveBeenCalledWith(url, expect.objectContaining({ cache: 'no-store', signal: expect.any(AbortSignal) }))
|
||||
})
|
||||
|
||||
|
||||
@ -5,6 +5,7 @@ import { isSuperAdmin } from '@/lib/department-permission'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { prepareDetailTextRecovery, findDetailJob } from '@/lib/detail-generator/repository'
|
||||
import { processDetailJob } from '@/lib/detail-generator/jobs'
|
||||
import { recoverDetailTextJob } from '@/lib/detail-generator/recovery'
|
||||
|
||||
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
||||
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
||||
@ -34,26 +35,31 @@ test.each(['anonymous', 'ordinary', 'revoked', 'suspended'] as const)('%s access
|
||||
})
|
||||
|
||||
test.each([{ action: 'query', modelId: 'override' }, { action: 'continue', requestId: id }, { action: 'query', requestId: '../other' }, { action: 'resend' }])('invalid or overridden recovery body never reaches admission: %p', async body => {
|
||||
const response = await POST(request(body), { params: { id } })
|
||||
expect(response.status).toBe(400)
|
||||
await expect(recoverDetailTextJob('owner-1', id, body)).rejects.toMatchObject({ status: 400, code: 'invalid_request' })
|
||||
expect(prepareDetailTextRecovery).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('query executes only the prepared original lease; continuation only queues unfinished work', async () => {
|
||||
const response = await POST(request({ action: 'query' }), { params: { id } })
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('cache-control')).toContain('no-store')
|
||||
await expect(recoverDetailTextJob('owner-1', id, { action: 'query' })).resolves.toEqual({ job: { id, status: 'unknown' } })
|
||||
expect(prepareDetailTextRecovery).toHaveBeenCalledWith(id, 'owner-1', 'query', undefined)
|
||||
expect(processDetailJob).toHaveBeenCalledTimes(1)
|
||||
;(processDetailJob as jest.Mock).mockClear()
|
||||
;(prepareDetailTextRecovery as jest.Mock).mockResolvedValue({ id, status: 'queued', leaseToken: null })
|
||||
expect((await POST(request({ action: 'continue' }), { params: { id } })).status).toBe(200)
|
||||
await expect(recoverDetailTextJob('owner-1', id, { action: 'continue' })).resolves.toEqual({ job: { id, status: 'unknown' } })
|
||||
expect(prepareDetailTextRecovery).toHaveBeenLastCalledWith(id, 'owner-1', 'continue', undefined)
|
||||
expect(processDetailJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('simple cross-site form and text/plain submissions cannot trigger recovery or continuation', async () => {
|
||||
const response = await POST(new Request('https://platform.test/api/detail-generator/jobs/' + id + '/recover', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{"action":"continue"}' }), { params: { id } })
|
||||
expect(response.status).toBe(415)
|
||||
test.each(['application/json', 'text/plain'])('browser submissions with %s cannot dispatch recovery', async contentType => {
|
||||
const submission = new Request('https://platform.test/api/detail-generator/jobs/' + id + '/recover', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': contentType },
|
||||
body: '{"action":"continue"}',
|
||||
})
|
||||
const response = await POST(submission, { params: { id } })
|
||||
expect(response.status).toBe(409)
|
||||
expect(response.headers.get('cache-control')).toContain('no-store')
|
||||
await expect(response.json()).resolves.toMatchObject({ code: 'client_required' })
|
||||
expect(prepareDetailTextRecovery).not.toHaveBeenCalled()
|
||||
expect(processDetailJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@ -10,7 +10,7 @@ describe('大文件下载流清理与背压', () => {
|
||||
['app/api/materials/download/route.ts', 'nodeReadableToWebStream'],
|
||||
['app/api/materials/[id]/skus/[skuId]/download/route.ts', 'createArchiveDownloadStream'],
|
||||
['app/api/materials/[id]/skus/batch-download/route.ts', 'createArchiveDownloadStream'],
|
||||
['app/api/external/download/route.ts', 'createArchiveDownloadStream'],
|
||||
['app/api/external/download/route.ts', 'streamExternalZip'],
|
||||
]
|
||||
|
||||
test.each(downloadRoutes)('%s 应使用统一的背压/取消流转换器', (routePath, helperName) => {
|
||||
|
||||
@ -22,17 +22,18 @@ import {
|
||||
safelyCleanupMaterialUploadSession,
|
||||
} from '@/lib/temp-cleanup'
|
||||
import { uploadSessions, type UploadSession } from '@/lib/upload-sessions'
|
||||
|
||||
const mockBrandKnowledgeFindFirst = jest.fn()
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
jest.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
brandKnowledge: {
|
||||
findFirst: mockBrandKnowledgeFindFirst,
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const mockBrandKnowledgeFindFirst = jest.mocked(prisma.brandKnowledge.findFirst)
|
||||
|
||||
describe('safe material upload cleanup protocol', () => {
|
||||
let uploadRoot: string
|
||||
const uploadId = 'safe-cleanup-upload-1'
|
||||
|
||||
@ -29,6 +29,13 @@ jest.mock('@/lib/prisma', () => ({
|
||||
},
|
||||
user: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
userEmployeeBinding: {
|
||||
findFirst: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
organizationUnit: {
|
||||
findUnique: jest.fn().mockResolvedValue(null),
|
||||
},
|
||||
},
|
||||
}))
|
||||
@ -37,6 +44,7 @@ jest.mock('@/lib/department-permission', () => ({
|
||||
getUserViewableMaterialTypes: jest.fn(),
|
||||
isSuperAdmin: jest.fn(),
|
||||
isSystemAdmin: jest.fn(),
|
||||
resolveRosterPermissionPack: jest.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
describe('search suggestions special init visibility', () => {
|
||||
|
||||
@ -8,6 +8,10 @@ import { spawn } from 'child_process'
|
||||
import { processVideoTranscode } from '@/lib/video-processor'
|
||||
import { deleteFromS3, uploadFileToS3 } from '@/lib/s3'
|
||||
|
||||
jest.mock('@/lib/file-cleanup', () => ({
|
||||
deleteFileIfUnreferenced: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('child_process', () => {
|
||||
const { promisify } = jest.requireActual('util') as typeof import('util')
|
||||
const execFile = jest.fn()
|
||||
|
||||
@ -12,6 +12,10 @@ import {
|
||||
resolveTranscodeOutputRoot,
|
||||
} from '@/lib/video-processor'
|
||||
|
||||
jest.mock('@/lib/file-cleanup', () => ({
|
||||
deleteFileIfUnreferenced: jest.fn(),
|
||||
}))
|
||||
|
||||
jest.mock('child_process', () => ({
|
||||
execFile: jest.fn(),
|
||||
spawn: jest.fn(),
|
||||
@ -78,9 +82,9 @@ describe('canonical video source preservation', () => {
|
||||
expect(source).toContain('uploadFileToS3,')
|
||||
expect(source).toContain('getS3KeyFromUrl,')
|
||||
expect(source).toContain('deleteFromS3,')
|
||||
expect(source).toContain("uploadFileToS3(previewPath, preview540FileName, 'video/mp4')")
|
||||
expect(source).toContain("uploadFileToS3(clipPath, clipFileName, 'video/mp4')")
|
||||
expect(source).toContain("uploadFileToS3(coverPath, coverFileName, 'image/jpeg')")
|
||||
expect(source).toContain("uploadFileToS3(previewPath, preview540FileName, 'video/mp4', undefined, options.protectedMaterialId)")
|
||||
expect(source).toContain("uploadFileToS3(clipPath, clipFileName, 'video/mp4', undefined, options.protectedMaterialId)")
|
||||
expect(source).toContain("uploadFileToS3(coverPath, coverFileName, 'image/jpeg', undefined, options.protectedMaterialId)")
|
||||
expect(source).not.toMatch(/readFile\(temp(?:540|Clip|Cover)Path\)/)
|
||||
})
|
||||
|
||||
|
||||
@ -764,8 +764,10 @@ ${helper}`
|
||||
expect(script).toContain('20260813_add_material_custody_department')
|
||||
expect(script).toContain('20260813_add_organization_units_and_employment_state')
|
||||
expect(script).toContain('20260813_add_user_employee_binding')
|
||||
expect(dockerfile).toContain('/app/prisma/migrations/20251118000000_add_upload_id_to_materials/migration.sql')
|
||||
expect(dockerfile).toContain('COPY --from=builder --chown=root:root /app/prisma/migrations/20251118000000_add_upload_id_to_materials')
|
||||
expect(dockerfile).toContain("const dir='/app/prisma/migrations'")
|
||||
expect(dockerfile).toContain("path.join(dir,entry.name,'migration.sql')")
|
||||
expect(dockerfile).toContain('!st.isFile()||st.size===0')
|
||||
expect(dockerfile).toContain('COPY --from=builder --chown=root:root /app/prisma/migrations ./prisma/migrations')
|
||||
expect(script).toContain('finished_at IS NOT NULL AND rolled_back_at IS NULL')
|
||||
expect(script).toContain('traffic was not switched')
|
||||
})
|
||||
|
||||
@ -76,13 +76,14 @@ beforeEach(() => {
|
||||
|
||||
describe('小壹交付单调修订防倒退与可选内部资产', () => {
|
||||
test('较旧的 baseRevisionId、deliveredAt 或 clientRevision 被拒绝且不覆盖当前修订', async () => {
|
||||
jest.mocked(prisma.deliveryRevision.findUnique).mockImplementation(async (args: any) => {
|
||||
const findRevision = prisma.deliveryRevision.findUnique as jest.Mock
|
||||
findRevision.mockImplementation(async (args: Parameters<typeof prisma.deliveryRevision.findUnique>[0]) => {
|
||||
if (args?.where?.ownerId_requestId_kind) return null
|
||||
if (args?.where?.id === 'rev-newer') {
|
||||
return {
|
||||
id: 'rev-newer',
|
||||
snapshot: { clientMonotonic: { deliveredAt: 2000, clientRevision: 5 } },
|
||||
} as any
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
@ -30,8 +30,6 @@ export async function getOptimalChunkSize(): Promise<number> {
|
||||
? 20 * 1024 * 1024
|
||||
: 10 * 1024 * 1024
|
||||
|
||||
console.log(`[ChunkConfig] 检测到${network.isInternal ? '内网' : '公网'}访问,使用 ${formatChunkSize(chunkSize)} 分片`)
|
||||
|
||||
return chunkSize
|
||||
}
|
||||
|
||||
@ -44,7 +42,6 @@ export function getChunkSizeSync(): number {
|
||||
const chunkSize = network.isInternal
|
||||
? 20 * 1024 * 1024
|
||||
: 10 * 1024 * 1024
|
||||
console.log(`[ChunkConfig] 使用 ${formatChunkSize(chunkSize)} 分片(同步)`)
|
||||
return chunkSize
|
||||
}
|
||||
|
||||
@ -112,8 +109,6 @@ export async function getOptimalConcurrency(): Promise<number> {
|
||||
// 确保在1-2范围内
|
||||
concurrency = Math.max(1, Math.min(2, concurrency))
|
||||
|
||||
console.log(`[ChunkConfig] 检测到${network.isInternal ? '内网' : '公网'}访问,使用 ${concurrency} 个并发(1~2范围)`)
|
||||
|
||||
return concurrency
|
||||
}
|
||||
|
||||
@ -171,10 +166,6 @@ export function adjustConcurrencyBySpeed(currentConcurrency: number, currentSpee
|
||||
newConcurrency = Math.min(3, currentConcurrency + 1)
|
||||
}
|
||||
|
||||
if (newConcurrency !== currentConcurrency) {
|
||||
console.log(`[ChunkConfig] 动态调整并发: ${currentConcurrency} → ${newConcurrency} (当前速度: ${speedMBps.toFixed(2)}MB/s)`)
|
||||
}
|
||||
|
||||
return newConcurrency
|
||||
}
|
||||
|
||||
|
||||
@ -220,11 +220,7 @@ async function uploadChunk(
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const startTime = Date.now()
|
||||
let uploadStartTime = 0
|
||||
let firstByteTime = 0
|
||||
let lastProgressTime = 0
|
||||
let lastProgressLoaded = 0
|
||||
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
|
||||
@ -242,60 +238,15 @@ async function uploadChunk(
|
||||
xhr.setRequestHeader('X-Chunk-Size', chunk.size.toString())
|
||||
Object.entries(options.requestHeaders || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value))
|
||||
|
||||
// 记录开始上传时间
|
||||
xhr.upload.onloadstart = () => {
|
||||
uploadStartTime = Date.now()
|
||||
const prepareTime = uploadStartTime - startTime
|
||||
console.log(`[ChunkUpload] 🚀 Chunk ${chunkIndex} 开始上传 (准备耗时: ${prepareTime}ms)`)
|
||||
}
|
||||
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) {
|
||||
// 记录第一个字节发送时间
|
||||
if (firstByteTime === 0 && event.loaded > 0) {
|
||||
firstByteTime = Date.now()
|
||||
const firstByteDelay = firstByteTime - uploadStartTime
|
||||
console.log(`[ChunkUpload] 📤 Chunk ${chunkIndex} 首字节发送: ${firstByteDelay}ms`)
|
||||
}
|
||||
|
||||
options.onChunkProgress?.(event.loaded, event.total)
|
||||
|
||||
// 每秒输出一次进度和速度
|
||||
const now = Date.now()
|
||||
if (now - lastProgressTime >= 1000) {
|
||||
const elapsed = (now - uploadStartTime) / 1000
|
||||
const speed = event.loaded / elapsed / 1024 / 1024
|
||||
const instantSpeed = (event.loaded - lastProgressLoaded) / ((now - lastProgressTime) / 1000) / 1024 / 1024
|
||||
console.log(`[ChunkUpload] 📊 Chunk ${chunkIndex} 进度: ${(event.loaded/event.total*100).toFixed(1)}%, 平均速度: ${speed.toFixed(2)}MB/s, 瞬时速度: ${instantSpeed.toFixed(2)}MB/s`)
|
||||
lastProgressTime = now
|
||||
lastProgressLoaded = event.loaded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
xhr.onload = () => {
|
||||
options.onRequest?.(null)
|
||||
const totalTime = Date.now() - startTime
|
||||
const uploadTime = Date.now() - uploadStartTime
|
||||
const serverTime = totalTime - uploadTime
|
||||
|
||||
console.log(`[ChunkUpload] ✅ Chunk ${chunkIndex} 完成:`, {
|
||||
总耗时: `${totalTime}ms`,
|
||||
上传耗时: `${uploadTime}ms (${(uploadTime/totalTime*100).toFixed(1)}%)`,
|
||||
服务器处理: `${serverTime}ms (${(serverTime/totalTime*100).toFixed(1)}%)`,
|
||||
大小: `${(chunk.size / 1024 / 1024).toFixed(2)}MB`,
|
||||
平均速度: `${(chunk.size / 1024 / 1024 / (uploadTime / 1000)).toFixed(2)}MB/s`
|
||||
})
|
||||
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
try {
|
||||
const response = JSON.parse(xhr.responseText)
|
||||
if (response.serverProcessTime) {
|
||||
console.log(`[ChunkUpload] 🖥️ Chunk ${chunkIndex} 服务器详细耗时: ${response.serverProcessTime}ms`)
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略JSON解析错误
|
||||
}
|
||||
resolve()
|
||||
} else if (xhr.status === 404) {
|
||||
// 会话不存在或已过期,抛出特殊错误以便重新初始化
|
||||
@ -543,7 +494,6 @@ async function runChunkUpload(
|
||||
await saveUploadState(state)
|
||||
} else {
|
||||
// 恢复上传
|
||||
console.log(`[ChunkUpload] 恢复上传: ${state.uploadedChunks.size}/${totalChunks} 块已上传`)
|
||||
// 用最新metadata覆盖旧值(以便完成时使用最新表单信息)
|
||||
state.metadata = metadata
|
||||
await saveUploadState(state)
|
||||
@ -690,8 +640,6 @@ async function runChunkUpload(
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[ChunkUpload] 开始并发上传: ${pendingChunks.length}个chunk待上传,${CONCURRENT_CHUNKS}个并发`)
|
||||
|
||||
// 会话过期标志(用于协调所有worker)
|
||||
let sessionExpired = false
|
||||
let reinitPromise: Promise<void> | null = null
|
||||
@ -701,7 +649,6 @@ async function runChunkUpload(
|
||||
while (pendingChunks.length > 0) {
|
||||
// 检查取消状态
|
||||
if (isCancelled?.()) {
|
||||
console.log('[ChunkUpload] Worker 检测到取消信号,停止上传')
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
@ -720,7 +667,6 @@ async function runChunkUpload(
|
||||
while (!success && retries < maxRetries) {
|
||||
// 每次重试前检查取消状态
|
||||
if (isCancelled?.()) {
|
||||
console.log('[ChunkUpload] Worker 检测到取消信号,停止上传')
|
||||
throw new Error('上传已取消')
|
||||
}
|
||||
|
||||
@ -760,7 +706,6 @@ async function runChunkUpload(
|
||||
completedBytes += chunkSizeBytes
|
||||
updateProgress(completedBytes + getInFlightBytes())
|
||||
|
||||
console.log(`[ChunkUpload] Chunk ${chunkIndex}/${totalChunks} 完成,剩余 ${pendingChunks.length} 个`)
|
||||
} catch (error) {
|
||||
inFlightChunkBytes.delete(chunkIndex)
|
||||
updateProgress(completedBytes + getInFlightBytes())
|
||||
@ -778,7 +723,6 @@ async function runChunkUpload(
|
||||
await deleteUploadState(fileId).catch(() => {})
|
||||
// 调用后端清理 API 删除服务器临时文件
|
||||
if (state.uploadId) {
|
||||
console.log('[ChunkUpload] 取消上传,调用后端清理临时文件...')
|
||||
fetch('/api/materials/upload/cleanup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@ -793,7 +737,6 @@ async function runChunkUpload(
|
||||
if (isNonRetryableUploadError(error)) {
|
||||
await deleteUploadState(fileId).catch(() => {})
|
||||
if (state.uploadId) {
|
||||
console.log('[ChunkUpload] 上传分片失败且不可重试,调用后端清理临时文件...')
|
||||
fetch('/api/materials/upload/cleanup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@ -817,7 +760,6 @@ async function runChunkUpload(
|
||||
|
||||
// 如果已经有其他worker在处理,等待它完成
|
||||
if (reinitPromise) {
|
||||
console.log(`[ChunkUpload] 等待其他worker完成会话刷新...`)
|
||||
await reinitPromise
|
||||
continue
|
||||
}
|
||||
@ -839,7 +781,6 @@ async function runChunkUpload(
|
||||
const refreshResult = await refreshResponse.json()
|
||||
|
||||
if (refreshResult.success) {
|
||||
console.log(`[ChunkUpload] ✅ 会话刷新成功,保留 ${state.uploadedChunks.size} 个已上传分片,继续上传`)
|
||||
sessionExpired = false
|
||||
// 不清空 uploadedChunks,保留进度
|
||||
return
|
||||
@ -869,7 +810,6 @@ async function runChunkUpload(
|
||||
for (let i = 0; i < totalChunks; i++) {
|
||||
pendingChunks.push(i)
|
||||
}
|
||||
console.log(`[ChunkUpload] ✅ 会话重新初始化成功,重新开始上传`)
|
||||
sessionExpired = false
|
||||
return
|
||||
}
|
||||
@ -915,7 +855,6 @@ async function runChunkUpload(
|
||||
|
||||
// 如果设置了skipComplete,分片上传完成后立即返回,不调用completeUpload
|
||||
if (skipComplete) {
|
||||
console.log('[ChunkUpload] 分片上传完成,跳过complete处理(将在后台异步处理)')
|
||||
if (!retainStateOnSkipComplete) {
|
||||
try {
|
||||
await deleteUploadState(fileId)
|
||||
|
||||
@ -391,8 +391,6 @@ async function createOrUpdateUserSession(
|
||||
)
|
||||
}
|
||||
|
||||
console.log('创建新用户(使用钉钉姓名):', displayName)
|
||||
|
||||
let emailToUse = userInfo.email || generateRandomEmail()
|
||||
const emailExists = await prisma.user.findUnique({ where: { email: emailToUse } })
|
||||
if (emailExists) {
|
||||
@ -417,9 +415,7 @@ async function createOrUpdateUserSession(
|
||||
})
|
||||
|
||||
needCompleteProfile = true
|
||||
console.log('用户创建成功:', user.id)
|
||||
} else {
|
||||
console.log('更新现有用户:', user.username)
|
||||
user = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
@ -574,8 +570,6 @@ async function resolveDingtalkUserForSession(
|
||||
)
|
||||
}
|
||||
|
||||
console.log('创建新用户(使用钉钉姓名):', displayName)
|
||||
|
||||
// 评分通知只需要一个与钉钉唯一值绑定的受限身份。若素材库里已有同名账号,
|
||||
// 不能自动合并,也不能因为 username 唯一约束把外部人员挡在评分入口外。
|
||||
// 为该受限身份生成不可用于普通登录的内部用户名,展示名仍使用钉钉返回姓名。
|
||||
@ -620,7 +614,6 @@ async function resolveDingtalkUserForSession(
|
||||
throw new Error('您的账号尚未激活,请联系管理员激活后再登录')
|
||||
}
|
||||
} else {
|
||||
console.log('更新现有用户:', user.username)
|
||||
user = await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: {
|
||||
@ -699,17 +692,13 @@ export async function authorizeDingtalkH5UserForNextAuth(
|
||||
allowRestrictedPerformanceAccess?: boolean
|
||||
},
|
||||
) {
|
||||
console.log('开始钉钉H5免登NextAuth登录流程')
|
||||
const appSource = options?.appSource || 'login'
|
||||
|
||||
const appAccessToken = await getAppAccessToken(appSource)
|
||||
console.log('获取应用访问令牌成功')
|
||||
|
||||
const userId = await getUserIdByH5AuthCode(code, appAccessToken)
|
||||
console.log('通过免登码获取userId成功:', userId)
|
||||
|
||||
const userInfo = await getUserInfo(userId, appAccessToken)
|
||||
console.log('获取用户信息成功:', userInfo.name)
|
||||
|
||||
return resolveDingtalkUserForSession(userId, userInfo, options?.clientIp || null, {
|
||||
allowRestrictedPerformanceAccess: options?.allowRestrictedPerformanceAccess === true,
|
||||
@ -721,7 +710,6 @@ export async function loginDingtalkUserByOAuthCode(
|
||||
code: string,
|
||||
options?: { appSource?: DingtalkLoginAppSource },
|
||||
) {
|
||||
console.log('开始钉钉OAuth登录流程')
|
||||
const appSource = options?.appSource || 'login'
|
||||
|
||||
const tokenData = await getUserAccessToken(code, appSource)
|
||||
@ -733,18 +721,13 @@ export async function loginDingtalkUserByOAuthCode(
|
||||
)
|
||||
}
|
||||
|
||||
console.log('获取用户访问令牌成功')
|
||||
const appAccessToken = await getAppAccessToken(appSource)
|
||||
console.log('获取应用访问令牌成功')
|
||||
|
||||
const unionId = await getUnionId(tokenData.accessToken)
|
||||
console.log('获取unionId成功:', unionId)
|
||||
|
||||
const userId = await getUserIdByUnionId(unionId, appAccessToken)
|
||||
console.log('获取userId成功:', userId)
|
||||
|
||||
const userInfo = await getUserInfo(userId, appAccessToken)
|
||||
console.log('获取用户信息成功:', userInfo.name)
|
||||
|
||||
return createOrUpdateUserSession(request, userId, userInfo)
|
||||
}
|
||||
@ -754,17 +737,13 @@ export async function loginDingtalkUserByH5AuthCode(
|
||||
code: string,
|
||||
options?: { appSource?: DingtalkLoginAppSource },
|
||||
) {
|
||||
console.log('开始钉钉H5免登流程')
|
||||
const appSource = options?.appSource || 'login'
|
||||
|
||||
const appAccessToken = await getAppAccessToken(appSource)
|
||||
console.log('获取应用访问令牌成功')
|
||||
|
||||
const userId = await getUserIdByH5AuthCode(code, appAccessToken)
|
||||
console.log('通过免登码获取userId成功:', userId)
|
||||
|
||||
const userInfo = await getUserInfo(userId, appAccessToken)
|
||||
console.log('获取用户信息成功:', userInfo.name)
|
||||
|
||||
return createOrUpdateUserSession(request, userId, userInfo, {
|
||||
cookieSameSite: 'none',
|
||||
|
||||
@ -132,10 +132,6 @@ export async function ensureEnoughDiskSpace(
|
||||
)
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[DiskSpace] Disk space check passed for ${operation}: ` +
|
||||
`need ${formatBytes(requiredBytes)}, available ${formatBytes(space.available)} (${space.usePercent}% used)`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -78,9 +78,6 @@ export async function compressImage(
|
||||
URL.revokeObjectURL(img.src)
|
||||
|
||||
if (blob) {
|
||||
console.log(
|
||||
`[前端压缩] ${file.name}: ${(file.size / 1024).toFixed(2)}KB -> ${(blob.size / 1024).toFixed(2)}KB (${width}x${height} -> ${newWidth}x${newHeight})`
|
||||
)
|
||||
resolve(blob)
|
||||
} else {
|
||||
reject(new Error('图片压缩失败'))
|
||||
@ -138,4 +135,3 @@ export async function compressImages(
|
||||
|
||||
return compressedFiles
|
||||
}
|
||||
|
||||
|
||||
@ -132,8 +132,6 @@ export async function processImage(
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
console.log(`图片处理完成: ${metadata.width}x${metadata.height} -> ${width}x${height}, ${(buffer.length / 1024).toFixed(2)}KB -> ${(processedBuffer.length / 1024).toFixed(2)}KB, 质量: ${quality}`)
|
||||
|
||||
return processedBuffer
|
||||
} catch (error) {
|
||||
console.error('图片处理失败:', error)
|
||||
@ -205,7 +203,6 @@ export async function sliceImage(
|
||||
.toBuffer()
|
||||
}
|
||||
|
||||
console.log(`图片无需切割: ${width}x${height} -> ${outputWidth}x${outputHeight}, 压缩到 ${(processedBuffer.length / 1024).toFixed(2)}KB, 质量: ${quality}`)
|
||||
return [processedBuffer]
|
||||
}
|
||||
|
||||
@ -214,7 +211,6 @@ export async function sliceImage(
|
||||
if (sliceCount > IMAGE_PROCESSING_MAX_SLICES) {
|
||||
throw new Error(`图片过长,最多支持 ${IMAGE_PROCESSING_MAX_SLICES} 个切片`)
|
||||
}
|
||||
console.log(`开始切割图片: ${width}x${height} -> ${outputWidth}x${outputHeight}, ${sliceCount}个片段,每片限制${maxSizeKB}KB`)
|
||||
|
||||
// 切割图片
|
||||
for (let i = 0; i < sliceCount; i++) {
|
||||
@ -248,7 +244,6 @@ export async function sliceImage(
|
||||
}
|
||||
|
||||
slices.push(sliceBuffer)
|
||||
console.log(`切割片段 ${i + 1}/${sliceCount}: 高度 ${extractHeight}px, 大小 ${(sliceBuffer.length / 1024).toFixed(2)}KB, 质量: ${quality}`)
|
||||
}
|
||||
|
||||
return slices
|
||||
|
||||
@ -22,8 +22,6 @@ async function executeSafely(sql: string) {
|
||||
export async function ensureMaterialDownloadLogsTable() {
|
||||
if (downloadLogsTableEnsured) return
|
||||
|
||||
console.log('[DownloadLog] Ensuring material_download_logs table and indexes...')
|
||||
|
||||
// 确保 pgcrypto 扩展存在(用于 gen_random_uuid)
|
||||
await executeSafely(`CREATE EXTENSION IF NOT EXISTS "pgcrypto"`)
|
||||
|
||||
@ -55,5 +53,3 @@ export async function ensureMaterialDownloadLogsTable() {
|
||||
downloadLogsTableEnsured = true
|
||||
console.log('[DownloadLog] material_download_logs table ensured.')
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -52,7 +52,6 @@ async function generatePdfPreviewWithSlot(
|
||||
maxHeight: number
|
||||
): Promise<PdfProcessResult> {
|
||||
try {
|
||||
console.log(`[PDF] 开始处理PDF文件: ${pdfFilePath}`)
|
||||
|
||||
// 如果没有提供输出路径,生成唯一的临时文件
|
||||
// 使用 crypto.randomBytes 确保并发上传时不会冲突
|
||||
@ -82,7 +81,6 @@ async function generatePdfPreviewWithSlot(
|
||||
// 提取时使用较大的尺寸,确保有足够的像素用于后续处理
|
||||
// 只指定宽度,高度自动按比例缩放,保持PDF原始长宽比
|
||||
const extractSize = Math.max(maxWidth, maxHeight) * 2
|
||||
console.log(`[PDF] 执行命令: pdftoppm -f 1 -l 1 -scale-to ${extractSize} -jpeg ...`)
|
||||
|
||||
try {
|
||||
// R14修复:添加超时控制 - PDF处理最多10分钟
|
||||
@ -165,8 +163,6 @@ async function generatePdfPreviewWithSlot(
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[PDF] 成功提取PDF第一页,图片大小: ${imageBuffer.length} bytes`)
|
||||
|
||||
// 使用sharp处理图片(保持PDF原始长宽比,只限制最大尺寸,类似3D场景预览图处理)
|
||||
let sharpInstance = sharp(imageBuffer)
|
||||
|
||||
@ -175,12 +171,8 @@ async function generatePdfPreviewWithSlot(
|
||||
const width = metadata.width || 0
|
||||
const height = metadata.height || 0
|
||||
|
||||
console.log(`[PDF] 原始图片尺寸: ${width}x${height}`)
|
||||
console.log(`[PDF] 最大尺寸限制: ${maxWidth}x${maxHeight} (保持长宽比)`)
|
||||
|
||||
// 如果是长图(高度超过maxHeight),先裁剪顶部区域(类似PSD处理)
|
||||
if (height > maxHeight) {
|
||||
console.log(`[PDF] 检测到长图 ${width}x${height},裁剪到顶部${maxHeight}px`)
|
||||
sharpInstance = sharpInstance.extract({
|
||||
left: 0,
|
||||
top: 0,
|
||||
@ -206,8 +198,6 @@ async function generatePdfPreviewWithSlot(
|
||||
const finalWidth = finalMetadata.width || maxWidth
|
||||
const finalHeight = finalMetadata.height || maxHeight
|
||||
|
||||
console.log(`[PDF] 预览图生成成功: ${tempOutputPath} (${finalWidth}x${finalHeight})`)
|
||||
|
||||
// 清理临时文件(pdftoppm生成的文件)
|
||||
try {
|
||||
if (foundPath) {
|
||||
|
||||
@ -58,21 +58,9 @@ export async function processPdfUpload(
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[PDF Upload] PDF file detected, extracting first page as preview...')
|
||||
console.log('[PDF Upload] PDF file path:', pdfFilePath)
|
||||
|
||||
// 提取PDF第一页作为预览图
|
||||
const pdfPreviewResult = await generatePdfPreview(pdfFilePath)
|
||||
|
||||
console.log('[PDF Upload] PDF预览图提取结果:', {
|
||||
success: pdfPreviewResult.success,
|
||||
hasPreviewPath: !!pdfPreviewResult.previewPath,
|
||||
previewPath: pdfPreviewResult.previewPath,
|
||||
error: pdfPreviewResult.error,
|
||||
width: pdfPreviewResult.width,
|
||||
height: pdfPreviewResult.height
|
||||
})
|
||||
|
||||
if (!pdfPreviewResult.success || !pdfPreviewResult.previewPath) {
|
||||
const errorMsg = pdfPreviewResult.error || 'PDF预览图提取失败'
|
||||
console.error('[PDF Upload] ❌ PDF预览图提取失败:', errorMsg)
|
||||
@ -88,8 +76,6 @@ export async function processPdfUpload(
|
||||
const previewFilename = generateUniqueFilename('pdf-preview', '.jpg')
|
||||
const previewUrl = await uploadToS3(previewBuffer, previewFilename, 'image/jpeg', protectedMaterialId)
|
||||
|
||||
console.log('[PDF Upload] PDF preview extracted and uploaded:', previewUrl)
|
||||
|
||||
// 清理临时预览图文件
|
||||
await fs.unlink(pdfPreviewResult.previewPath).catch(() => {})
|
||||
|
||||
|
||||
@ -1208,7 +1208,6 @@ export async function completeProductPackageUpload(input: CompleteProductPackage
|
||||
let commitExpectation: ProductPackageCommitExpectation | null = null
|
||||
let releaseCompletionLock: MaterialUploadStorageLockRelease | null = null
|
||||
let releaseUploadSessionLocks: MaterialUploadStorageLockRelease | null = null
|
||||
const startedAt = Date.now()
|
||||
const assertExecutionCurrent = async () => {
|
||||
if (options?.signal?.aborted) {
|
||||
const reason = options.signal.reason
|
||||
@ -1218,9 +1217,6 @@ export async function completeProductPackageUpload(input: CompleteProductPackage
|
||||
}
|
||||
const reportProgress = async (stage: string, progress: number, message?: string) => {
|
||||
await assertExecutionCurrent()
|
||||
console.log(
|
||||
`[ProductPackage] material=${materialId} stage=${stage} progress=${progress} elapsedMs=${Date.now() - startedAt}`,
|
||||
)
|
||||
try {
|
||||
await options?.onProgress?.({ stage, progress, message })
|
||||
} catch (error) {
|
||||
|
||||
@ -659,8 +659,6 @@ export async function cleanupProductPackageFiles(
|
||||
const result = await deleteFile(fileUrl);
|
||||
if (result.success) {
|
||||
deletedFiles++;
|
||||
const fileType = result.isDirectory ? 'directory' : 'file';
|
||||
console.log(`[Cleanup] Deleted ${fileType}: ${fileUrl}`);
|
||||
} else {
|
||||
failedFiles++;
|
||||
console.error(`[Cleanup] Failed to delete file: ${fileUrl}`, result.error);
|
||||
@ -671,7 +669,6 @@ export async function cleanupProductPackageFiles(
|
||||
const psdDir = path.join(process.cwd(), 'uploads', 'product-package', materialId);
|
||||
try {
|
||||
await fs.rm(psdDir, { recursive: true, force: true });
|
||||
console.log(`[Cleanup] Deleted PSD directory: ${psdDir}`);
|
||||
} catch (err: any) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
console.warn(`[Cleanup] Failed to delete PSD directory: ${psdDir}`, err);
|
||||
|
||||
@ -11,7 +11,6 @@ try {
|
||||
const canvas = require('canvas')
|
||||
if (canvas && canvas.createCanvas) {
|
||||
initializeCanvas(canvas.createCanvas)
|
||||
console.log('[PSD] Canvas initialized successfully')
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('[PSD] Canvas not available, using fallback method')
|
||||
@ -43,8 +42,6 @@ export async function generatePsdPreview(
|
||||
// 读取PSD文件
|
||||
const psdBuffer = await fs.readFile(psdFilePath)
|
||||
|
||||
console.log(`[PSD] 开始解析PSD文件,大小: ${psdBuffer.length} bytes`)
|
||||
|
||||
// 解析PSD - 不跳过合成图像数据
|
||||
const psd = readPsd(psdBuffer, {
|
||||
skipLayerImageData: true, // 跳过图层数据
|
||||
@ -59,8 +56,6 @@ export async function generatePsdPreview(
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[PSD] 解析成功,尺寸: ${psd.width}x${psd.height}`)
|
||||
|
||||
// 获取PSD的宽高
|
||||
const width = psd.width || 0
|
||||
const height = psd.height || 0
|
||||
@ -81,7 +76,6 @@ export async function generatePsdPreview(
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[PSD] 找到合成图像数据: ${psd.imageData.width}x${psd.imageData.height}`)
|
||||
const imageData = psd.imageData
|
||||
|
||||
// 确保有图像数据
|
||||
@ -92,8 +86,6 @@ export async function generatePsdPreview(
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[PSD] 图像数据大小: ${imageData.data.length} bytes`)
|
||||
|
||||
// 将PSD图像数据转换为Buffer
|
||||
const rawBuffer = Buffer.from(imageData.data)
|
||||
|
||||
@ -108,7 +100,6 @@ export async function generatePsdPreview(
|
||||
|
||||
// 如果是长图(高度超过maxHeight),先裁剪顶部区域
|
||||
if (imageData.height > maxHeight) {
|
||||
console.log(`[PSD] 检测到长图 ${imageData.width}x${imageData.height},裁剪到顶部${maxHeight}px`)
|
||||
sharpInstance = sharpInstance.extract({
|
||||
left: 0,
|
||||
top: 0,
|
||||
@ -129,8 +120,6 @@ export async function generatePsdPreview(
|
||||
})
|
||||
.toFile(outputPath)
|
||||
|
||||
console.log(`[PSD] 预览图生成成功: ${outputPath}`)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
previewPath: outputPath,
|
||||
@ -177,4 +166,3 @@ export function hasPsdExtension(filename: string): boolean {
|
||||
lowerName.endsWith('.tiff') ||
|
||||
lowerName.endsWith('.psb')
|
||||
}
|
||||
|
||||
|
||||
@ -153,18 +153,13 @@ export async function syncStoredUploadFileToRemote(
|
||||
const localStat = await stat(localFilePath)
|
||||
const expectedFileSize = expectedSize || localStat.size
|
||||
const remoteDir = path.posix.dirname(remotePath)
|
||||
const sizeMiB = (expectedFileSize / 1024 / 1024).toFixed(2)
|
||||
|
||||
console.log(
|
||||
`[RemoteUploadSync] 准备同步 ${storedPath} -> ${config.target}:${remotePath} (${sizeMiB} MiB)`,
|
||||
)
|
||||
await execFileWithRetry(
|
||||
'ssh',
|
||||
[...SSH_NON_INTERACTIVE_ARGS, config.target, `mkdir -p ${shellQuote(remoteDir)}`],
|
||||
{ timeout: REMOTE_SYNC_SSH_TIMEOUT_MS },
|
||||
`创建远程目录 ${remoteDir}`,
|
||||
)
|
||||
console.log(`[RemoteUploadSync] 开始复制 ${storedPath} (${sizeMiB} MiB)`)
|
||||
await execFileWithRetry(
|
||||
'scp',
|
||||
['-q', ...SSH_NON_INTERACTIVE_ARGS, localFilePath, `${config.target}:${remotePath}`],
|
||||
|
||||
@ -197,8 +197,6 @@ export async function uploadToS3(
|
||||
const normalizedFileName = fileName.startsWith('/') ? fileName.slice(1) : fileName
|
||||
const key = `${normalizedPath}${normalizedFileName}`
|
||||
|
||||
console.log(`[S3] Uploading file: key=${key}, size=${file.length}, contentType=${contentType}`)
|
||||
|
||||
const command = new PutObjectCommand({
|
||||
Bucket: process.env.S3_BUCKET!,
|
||||
Key: key,
|
||||
@ -210,7 +208,6 @@ export async function uploadToS3(
|
||||
try {
|
||||
await s3Client.send(command)
|
||||
const url = `${process.env.S3_PUBLIC_DOMAIN}/${key}`
|
||||
console.log(`[S3] Uploaded successfully: url=${url}`)
|
||||
return url
|
||||
} catch (error) {
|
||||
// S3上传失败会自动重试(maxAttempts: 10),这里只记录日志
|
||||
@ -304,8 +301,6 @@ export async function downloadFromS3(fileUrl: string): Promise<Buffer> {
|
||||
const key = getS3KeyFromUrl(fileUrl)
|
||||
const bucket = process.env.S3_BUCKET!
|
||||
|
||||
console.log(`[S3] Downloading file: bucket=${bucket}, key=${key}`)
|
||||
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
Key: key,
|
||||
@ -320,7 +315,6 @@ export async function downloadFromS3(fileUrl: string): Promise<Buffer> {
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
const buffer = Buffer.concat(chunks)
|
||||
console.log(`[S3] Downloaded successfully: size=${buffer.length}`)
|
||||
return buffer
|
||||
}
|
||||
|
||||
|
||||
@ -424,7 +424,7 @@ export async function createZipFromFiles(
|
||||
files: Array<{ path: string; name: string; size: number }>,
|
||||
materialId: string,
|
||||
productModel: string,
|
||||
materialType: string,
|
||||
_materialType: string,
|
||||
zipType: string = 'all', // 'main', 'sku', 'detail', 'all'
|
||||
authorName?: string, // 作者名(上传人姓名)
|
||||
categoryName?: string, // 店铺名
|
||||
@ -458,9 +458,6 @@ export async function createZipFromFiles(
|
||||
const zipFilePath = path.join(uploadsDir, zipFileName);
|
||||
const relativeZipPath = buildStoredUploadPath('materials', zipFileName);
|
||||
|
||||
console.log(`[Zip] Creating ${zipType} zip file for ${materialType}:`, zipFilePath);
|
||||
console.log(`[Zip] Files count:`, files.length);
|
||||
|
||||
const inspected = await inspectSafeZipEntries(
|
||||
files.map((file) => ({ path: file.path, name: file.name })),
|
||||
);
|
||||
@ -480,7 +477,6 @@ export async function createZipFromFiles(
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log(`[Zip] ${zipType} zip file created successfully: ${fileSize} bytes`);
|
||||
return {
|
||||
filePath: relativeZipPath,
|
||||
fileName: zipFileName,
|
||||
@ -496,7 +492,7 @@ export async function createZipFromZips(
|
||||
zipFiles: Array<{ path: string; name: string }>,
|
||||
materialId: string,
|
||||
productModel: string,
|
||||
materialType: string,
|
||||
_materialType: string,
|
||||
timeoutMs: number = 60000,
|
||||
compressionLevel: number = 9,
|
||||
): Promise<{ filePath: string; fileName: string; fileSize: number }> {
|
||||
@ -515,9 +511,6 @@ export async function createZipFromZips(
|
||||
const zipFilePath = path.join(uploadsDir, zipFileName);
|
||||
const relativeZipPath = buildStoredUploadPath('materials', zipFileName);
|
||||
|
||||
console.log(`[Zip] Creating all.zip for ${materialType}:`, zipFilePath);
|
||||
console.log(`[Zip] Zip files count:`, zipFiles.length);
|
||||
|
||||
const inspected = await inspectSafeZipEntries(
|
||||
zipFiles.map((file) => ({
|
||||
path: path.isAbsolute(file.path) ? file.path : resolveStoredUploadPath(file.path),
|
||||
@ -540,7 +533,6 @@ export async function createZipFromZips(
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log(`[Zip] all.zip created successfully: ${fileSize} bytes`);
|
||||
return {
|
||||
filePath: relativeZipPath,
|
||||
fileName: zipFileName,
|
||||
@ -554,7 +546,7 @@ export async function createZipFromZips(
|
||||
*/
|
||||
export async function generatePreviewImages(
|
||||
uploadIds: Array<{ uploadId: string; fileName: string; filePath?: string }>,
|
||||
materialType: string,
|
||||
_materialType: string,
|
||||
compressOptions?: {
|
||||
maxWidth?: number;
|
||||
maxHeight?: number;
|
||||
@ -581,9 +573,6 @@ export async function generatePreviewImages(
|
||||
// 合并压缩参数
|
||||
const options = { ...defaultOptions, ...compressOptions };
|
||||
|
||||
console.log(`[Preview] Generating ${uploadIds.length} preview images for ${materialType}...`);
|
||||
console.log(`[Preview] Compress options:`, options);
|
||||
|
||||
for (let i = 0; i < uploadIds.length; i++) {
|
||||
const item = uploadIds[i];
|
||||
try {
|
||||
@ -631,7 +620,6 @@ export async function generatePreviewImages(
|
||||
uploadedPreviewUrls.push(previewUrl);
|
||||
onPreviewUploaded?.(previewUrl);
|
||||
|
||||
console.log(`[Preview] Generated preview ${i + 1}/${uploadIds.length}:`, previewUrl);
|
||||
} catch (err) {
|
||||
const error = `生成预览图失败 ${item.fileName}: ${err instanceof Error ? err.message : String(err)}`;
|
||||
console.error(`[Preview] ${error}`);
|
||||
@ -651,7 +639,6 @@ export async function generatePreviewImages(
|
||||
throw new Error(`预览图数量不匹配:期望 ${uploadIds.length} 张,实际生成 ${uploadedPreviewUrls.length} 张`);
|
||||
}
|
||||
|
||||
console.log(`[Preview] Successfully generated all ${uploadedPreviewUrls.length} preview images`);
|
||||
return uploadedPreviewUrls;
|
||||
}
|
||||
|
||||
@ -705,16 +692,13 @@ export async function cleanupOnError(
|
||||
deleteMaterial = true,
|
||||
deleteMaterialCondition?: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
console.log('[Cleanup] Starting error cleanup...');
|
||||
|
||||
// 清理已上传的S3预览图
|
||||
if (uploadedPreviewUrls.length > 0) {
|
||||
console.log(`[Cleanup] Cleaning up ${uploadedPreviewUrls.length} S3 preview images...`);
|
||||
for (const fileUrl of uploadedPreviewUrls) {
|
||||
try {
|
||||
if (fileUrl.startsWith('uploads/materials/')) await deleteFileIfUnreferenced(fileUrl);
|
||||
else await deleteFromS3(fileUrl);
|
||||
console.log(`[Cleanup] Deleted S3 file: ${fileUrl}`);
|
||||
} catch (cleanupError) {
|
||||
console.error(`[Cleanup] Failed to delete S3 file ${fileUrl}:`, cleanupError);
|
||||
}
|
||||
@ -724,7 +708,6 @@ export async function cleanupOnError(
|
||||
// 清理本地zip文件(支持单个或多个)
|
||||
if (zipFilePaths) {
|
||||
const paths = Array.isArray(zipFilePaths) ? zipFilePaths : [zipFilePaths];
|
||||
console.log(`[Cleanup] Cleaning up ${paths.length} local zip files...`);
|
||||
for (const zipFilePath of paths) {
|
||||
try {
|
||||
await deleteStoredUploadFileFromRemote(zipFilePath);
|
||||
@ -735,7 +718,6 @@ export async function cleanupOnError(
|
||||
try {
|
||||
const fullPath = resolveStoredUploadPath(zipFilePath);
|
||||
await unlink(fullPath);
|
||||
console.log(`[Cleanup] Deleted local zip file: ${fullPath}`);
|
||||
} catch (cleanupError) {
|
||||
console.error('[Cleanup] Failed to delete local zip file:', cleanupError);
|
||||
}
|
||||
@ -762,23 +744,19 @@ export async function cleanupOnError(
|
||||
const result = await prisma.material.deleteMany({
|
||||
where: { id: materialId, ...deleteMaterialCondition } as any,
|
||||
});
|
||||
if (result.count === 1) {
|
||||
console.log(`[Cleanup] Deleted conditionally claimed material record: ${materialId}`);
|
||||
} else {
|
||||
if (result.count !== 1) {
|
||||
console.warn(`[Cleanup] Skipped material deletion because claim state changed: ${materialId}`);
|
||||
}
|
||||
} else {
|
||||
await prisma.material.delete({
|
||||
where: { id: materialId },
|
||||
});
|
||||
console.log(`[Cleanup] Deleted material record: ${materialId}`);
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
console.error('[Cleanup] Failed to delete material record:', cleanupError);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[Cleanup] Error cleanup completed');
|
||||
}
|
||||
|
||||
/**
|
||||
@ -793,7 +771,6 @@ export async function saveAssets(
|
||||
await applySimpleTaskMaterialAssets(tx, materialId, previewUrls, zipInfo);
|
||||
});
|
||||
|
||||
console.log(`[Database] Saved ${previewUrls.length + (zipInfo ? 1 : 0)} asset records`);
|
||||
}
|
||||
|
||||
async function applySimpleTaskMaterialAssets(
|
||||
@ -885,9 +862,6 @@ export async function saveTaskMaterialAssetsAndComplete(input: {
|
||||
});
|
||||
invalidateMaterialFacetsCache();
|
||||
|
||||
console.log(
|
||||
`[Database] Atomically completed task material with ${input.previewUrls.length + (input.zipInfo ? 1 : 0)} assets`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1089,9 +1063,6 @@ export async function saveProductPackageAssets(
|
||||
? await applyAssets(options.transaction)
|
||||
: await prisma.$transaction(applyAssets);
|
||||
|
||||
if (!options?.transaction) {
|
||||
console.log(`[Database] Saved ${assetRecords.length + createdSkuPreviewAssets.length} asset records for product package`);
|
||||
}
|
||||
return { createdSkuPreviewAssets };
|
||||
}
|
||||
|
||||
@ -1141,7 +1112,6 @@ export async function saveProductPackageAssetsAndComplete(input: {
|
||||
},
|
||||
});
|
||||
|
||||
console.log('[Database] Atomically completed product package');
|
||||
invalidateMaterialFacetsCache();
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
@ -162,7 +162,6 @@ export async function runCleanup(): Promise<{
|
||||
skippedUnavailable: number
|
||||
}> {
|
||||
if (isCleanupRunning) {
|
||||
console.log('[TempCleanup] 清理任务正在运行,跳过')
|
||||
return emptyRunResult()
|
||||
}
|
||||
|
||||
@ -179,7 +178,6 @@ export async function runCleanup(): Promise<{
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error?.code === 'ENOENT') {
|
||||
console.log('[TempCleanup] temp 目录不存在,跳过清理')
|
||||
return result
|
||||
}
|
||||
throw error
|
||||
@ -187,7 +185,6 @@ export async function runCleanup(): Promise<{
|
||||
|
||||
const dirs = await readdir(tempDir)
|
||||
const now = Date.now()
|
||||
console.log(`[TempCleanup] 检查 ${dirs.length} 个目录...`)
|
||||
|
||||
for (const uploadId of dirs) {
|
||||
if (!SAFE_UPLOAD_ID_PATTERN.test(uploadId)) {
|
||||
@ -335,7 +332,6 @@ export async function cleanExpiredXiaoyiUpload(uploadId: string, dryRun = true)
|
||||
|
||||
export function startCleanupScheduler(): void {
|
||||
if (cleanupTimer) {
|
||||
console.log('[TempCleanup] 定时任务已在运行')
|
||||
return
|
||||
}
|
||||
|
||||
@ -436,7 +432,6 @@ async function executeSafeCleanup(
|
||||
if (directoryToDelete?.exists) {
|
||||
await rm(directoryToDelete.path, { recursive: true, force: true })
|
||||
}
|
||||
console.log(`[TempCleanup] 已安全清理上传会话: ${uploadId}`)
|
||||
return successResult(
|
||||
'deleted',
|
||||
(directoryToDelete?.deletedFiles || 0) + (assembledFileToDelete ? 1 : 0),
|
||||
|
||||
@ -98,7 +98,6 @@ export async function saveUploadSession(
|
||||
// 使用SETEX设置键值并指定过期时间
|
||||
await redis.setex(key, EXPIRE_TIME, JSON.stringify(data))
|
||||
|
||||
console.log(`[Redis] 保存上传会话: ${uploadId}, 过期时间: ${EXPIRE_TIME}秒`)
|
||||
} catch (error) {
|
||||
console.error(`[Redis] 保存上传会话失败: ${uploadId}`, error)
|
||||
throw error
|
||||
@ -139,7 +138,6 @@ export async function deleteUploadSession(uploadId: string): Promise<void> {
|
||||
try {
|
||||
const key = `${KEY_PREFIX}${uploadId}`
|
||||
await redis.del(key)
|
||||
console.log(`[Redis] 删除上传会话: ${uploadId}`)
|
||||
} catch (error) {
|
||||
console.error(`[Redis] 删除上传会话失败: ${uploadId}`, error)
|
||||
throw error
|
||||
@ -163,7 +161,6 @@ export async function updateChunk(
|
||||
session.chunks.set(chunkIndex, chunkPath)
|
||||
await saveUploadSession(uploadId, session)
|
||||
|
||||
console.log(`[Redis] 更新块信息: ${uploadId}, 块 ${chunkIndex}`)
|
||||
} catch (error) {
|
||||
console.error(`[Redis] 更新块信息失败: ${uploadId}, 块 ${chunkIndex}`, error)
|
||||
throw error
|
||||
@ -218,7 +215,6 @@ export async function refreshSessionTTL(uploadId: string): Promise<void> {
|
||||
try {
|
||||
const key = `${KEY_PREFIX}${uploadId}`
|
||||
await redis.expire(key, EXPIRE_TIME)
|
||||
console.log(`[Redis] 刷新会话过期时间: ${uploadId}`)
|
||||
} catch (error) {
|
||||
console.error(`[Redis] 刷新会话过期时间失败: ${uploadId}`, error)
|
||||
throw error
|
||||
@ -234,7 +230,6 @@ export async function refreshUploadSession(uploadId: string): Promise<boolean> {
|
||||
const key = `${KEY_PREFIX}${uploadId}`
|
||||
const exists = await redis.expire(key, EXPIRE_TIME)
|
||||
if (exists === 1) {
|
||||
console.log(`[Redis] 刷新上传会话成功: ${uploadId}, TTL: ${EXPIRE_TIME}秒`)
|
||||
return true
|
||||
} else {
|
||||
console.warn(`[Redis] 刷新上传会话失败,会话不存在: ${uploadId}`)
|
||||
@ -254,7 +249,6 @@ export async function setCompletedSessionTTL(uploadId: string): Promise<void> {
|
||||
const key = `${KEY_PREFIX}${uploadId}`
|
||||
const COMPLETED_TTL = 60 // 1分钟
|
||||
await redis.expire(key, COMPLETED_TTL)
|
||||
console.log(`[Redis] 已完成会话,TTL 缩短为 1 分钟: ${uploadId}`)
|
||||
} catch (error) {
|
||||
console.error(`[Redis] 设置已完成会话 TTL 失败: ${uploadId}`, error)
|
||||
throw error
|
||||
@ -334,4 +328,3 @@ redis.on('reconnecting', () => {
|
||||
|
||||
// 导出Redis实例(用于其他操作)
|
||||
export { redis }
|
||||
|
||||
|
||||
@ -284,7 +284,6 @@ if (!USE_REDIS || !redisModule) {
|
||||
|
||||
keysToDelete.forEach(key => {
|
||||
memorySessions.delete(key)
|
||||
console.log(`[UploadSessions] 清理过期会话: ${key}`)
|
||||
})
|
||||
|
||||
if (keysToDelete.length > 0) {
|
||||
@ -618,7 +617,6 @@ export async function getUploadedFile(
|
||||
return null
|
||||
}
|
||||
|
||||
console.log(`[Upload Session] Assembled file: ${outputPath} (${outputStats.size} bytes)`)
|
||||
return outputPath
|
||||
} catch (error) {
|
||||
// mergeUploadChunksAtomically 只会清理自己唯一的 partial;这里不能删除
|
||||
@ -768,7 +766,6 @@ export async function refreshUploadSession(uploadId: string): Promise<boolean> {
|
||||
const session = memorySessions.get(uploadId)
|
||||
if (session) {
|
||||
session.createdAt = Date.now()
|
||||
console.log(`[MemoryMap] 刷新上传会话成功: ${uploadId}`)
|
||||
return true
|
||||
}
|
||||
console.warn(`[MemoryMap] 刷新上传会话失败,会话不存在: ${uploadId}`)
|
||||
|
||||
@ -146,12 +146,10 @@ async function downloadRemoteToTemp(
|
||||
if (isS3PublicUrl(remoteUrl)) {
|
||||
let stream
|
||||
try {
|
||||
console.log(`[VideoProcessor] Fetching S3 object: ${remoteUrl}`)
|
||||
stream = await getS3ObjectStream(getS3KeyFromUrl(remoteUrl))
|
||||
if (!stream.body) {
|
||||
throw new Error('Failed to get video stream from S3: stream body is null')
|
||||
}
|
||||
console.log(`[VideoProcessor] S3 stream obtained, contentLength: ${stream.contentLength}`)
|
||||
} catch (error: any) {
|
||||
const errorMsg = error?.message || String(error)
|
||||
console.error(`[VideoProcessor] S3 download error: ${errorMsg}`)
|
||||
@ -181,7 +179,6 @@ async function downloadRemoteToTemp(
|
||||
`Temp video file too large: ${fileStat.size} bytes (max ${TRANSCODE_CONFIG.maxTempFileSize})`
|
||||
)
|
||||
}
|
||||
console.log(`[VideoProcessor] S3 file written to: ${tempPath}, size=${fileStat.size} bytes`)
|
||||
} catch (error: any) {
|
||||
const errorMsg = error?.message || String(error)
|
||||
console.error(`[VideoProcessor] File write error: ${errorMsg}`)
|
||||
@ -630,7 +627,6 @@ export async function processVideoTranscode(
|
||||
let sourcePath: string
|
||||
// 1. 处理输入视频(S3 URL 或本地路径)
|
||||
if (isHttpUrl(inputPath)) {
|
||||
console.log('[VideoProcessor] Downloading remote video...')
|
||||
onProgress?.(5, 'preview')
|
||||
await downloadRemoteToTemp(inputPath, remoteInputPath, abortSignal)
|
||||
sourcePath = remoteInputPath
|
||||
@ -638,7 +634,6 @@ export async function processVideoTranscode(
|
||||
} else {
|
||||
// canonical 本地源文件直接以只读输入交给 FFmpeg,不复制、不移动、不删除。
|
||||
const localFilePath = resolveLocalVideoPath(inputPath)
|
||||
console.log('[VideoProcessor] Checking local video file:', localFilePath)
|
||||
try {
|
||||
await access(localFilePath)
|
||||
const sourceStat = await stat(localFilePath)
|
||||
@ -655,11 +650,9 @@ export async function processVideoTranscode(
|
||||
}
|
||||
|
||||
// 2. 获取视频时长
|
||||
console.log('[VideoProcessor] Getting video duration...')
|
||||
const duration = await getVideoDuration(sourcePath, abortSignal)
|
||||
|
||||
// 3. 转码为预览视频(分辨率可配置)
|
||||
console.log(`[VideoProcessor] Transcoding to ${TRANSCODE_CONFIG.previewResolution}P preview...`)
|
||||
await transcodeToPreview(sourcePath, previewPath, (progress) => {
|
||||
// 预览转码进度:10% - 50%
|
||||
onProgress?.(10 + Math.round(progress * 0.4), 'preview')
|
||||
@ -668,11 +661,9 @@ export async function processVideoTranscode(
|
||||
onProgress?.(55, 'preview') // 上传开始
|
||||
const preview540Url = await uploadFileToS3(previewPath, preview540FileName, 'video/mp4', undefined, options.protectedMaterialId)
|
||||
uploadedUrls.push(preview540Url)
|
||||
console.log(`[VideoProcessor] ${TRANSCODE_CONFIG.previewResolution}P preview uploaded:`, preview540Url)
|
||||
onProgress?.(60, 'clip') // 预览完成,开始片段
|
||||
|
||||
// 4. 生成预览片段(时长可配置)
|
||||
console.log(`[VideoProcessor] Generating ${TRANSCODE_CONFIG.clipDuration}s clip...`)
|
||||
await generateClip(sourcePath, clipPath, (progress) => {
|
||||
// 片段转码进度:60% - 80%
|
||||
onProgress?.(60 + Math.round(progress * 0.2), 'clip')
|
||||
@ -681,21 +672,16 @@ export async function processVideoTranscode(
|
||||
onProgress?.(85, 'clip') // 上传开始
|
||||
const clipUrl = await uploadFileToS3(clipPath, clipFileName, 'video/mp4', undefined, options.protectedMaterialId)
|
||||
uploadedUrls.push(clipUrl)
|
||||
console.log(`[VideoProcessor] ${TRANSCODE_CONFIG.clipDuration}s clip uploaded:`, clipUrl)
|
||||
onProgress?.(90, 'cover') // 片段完成,开始封面
|
||||
|
||||
// 5. 截取封面图(仅在需要时)
|
||||
let coverUrl: string | null = null
|
||||
if (needsCoverImage) {
|
||||
console.log('[VideoProcessor] Extracting cover image...')
|
||||
await extractCoverImage(sourcePath, coverPath, abortSignal)
|
||||
const coverFileName = `video-cover-${materialId}-${outputIdentity}.jpg`
|
||||
onProgress?.(95, 'cover') // 上传开始
|
||||
coverUrl = await uploadFileToS3(coverPath, coverFileName, 'image/jpeg', undefined, options.protectedMaterialId)
|
||||
uploadedUrls.push(coverUrl)
|
||||
console.log('[VideoProcessor] Cover image uploaded:', coverUrl)
|
||||
} else {
|
||||
console.log('[VideoProcessor] Skipping cover image extraction (user already uploaded)')
|
||||
}
|
||||
onProgress?.(100, 'cover') // 完成
|
||||
|
||||
@ -717,4 +703,3 @@ export async function processVideoTranscode(
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -316,7 +316,6 @@ export async function executeTranscodeTask(
|
||||
let outputDisposition: 'none' | 'pending' | 'cleaned' | 'preserve' | 'committed' = 'none'
|
||||
|
||||
try {
|
||||
console.log(`[Transcode] Starting task for material ${materialId} (attempt ${attempt}/${MAX_TRANSCODE_RETRIES})`)
|
||||
|
||||
const latestMaterial = await prisma.material.findUnique({
|
||||
where: { id: materialId },
|
||||
@ -362,7 +361,6 @@ export async function executeTranscodeTask(
|
||||
needsCoverImage: coverStillNeeded,
|
||||
abortSignal,
|
||||
onProgress: (progress, stage) => {
|
||||
console.log(`[Transcode] Material ${materialId} - ${stage}: ${progress}%`)
|
||||
void transcodeQueue.updateProgress(materialId, leaseToken, progress, stage)
|
||||
.catch((error) => console.error(`[Transcode] Failed to persist progress for ${materialId}:`, error))
|
||||
},
|
||||
@ -390,7 +388,6 @@ export async function executeTranscodeTask(
|
||||
}
|
||||
outputDisposition = 'committed'
|
||||
|
||||
console.log(`[Transcode] Task completed for material ${materialId}`)
|
||||
return
|
||||
} catch (error) {
|
||||
if (attemptResult && outputDisposition === 'pending') {
|
||||
@ -465,7 +462,6 @@ async function validateVideoFile(videoSourceUrl: string): Promise<boolean> {
|
||||
|
||||
const localFilePath = resolveLocalVideoPath(videoSourceUrl)
|
||||
await access(localFilePath)
|
||||
console.log(`[TranscodeTask] Video source is ready: ${localFilePath}`)
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('[TranscodeTask] Video source is not readable', {
|
||||
@ -490,12 +486,7 @@ export async function enqueueVideoTranscodeTask(
|
||||
throw new Error(USER_TRANSCODE_FAILURE_MESSAGE)
|
||||
}
|
||||
|
||||
console.log(`[TranscodeTask] 📝 Enqueuing transcode task: materialId=${materialId}, videoSourceUrl=${videoSourceUrl}, needsCoverImage=${needsCoverImage}`)
|
||||
|
||||
// 只等待数据库持久化入队,不等待 ffmpeg;失败需要反馈给调用方,不能静默丢任务。
|
||||
await transcodeQueue.add(materialId, videoSourceUrl, needsCoverImage, executeTranscodeTask)
|
||||
|
||||
console.log(`[TranscodeTask] ✅ Transcode task enqueued successfully (fire-and-forget): materialId=${materialId}`)
|
||||
}
|
||||
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user