88 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server'
import { getAuthenticatedUploadUserId } from '@/lib/upload-auth'
import {
isSafeUploadId,
refreshOwnedUploadSession,
UploadSessionStoreUnavailableError,
} from '@/lib/upload-sessions'
// Configure route
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
/**
* 刷新上传会话API
* 用于会话过期后恢复上传,不清空已上传的分片记录
*
* POST /api/materials/upload/refresh
* Body: { uploadId: string }
*
* 返回:
* - success: true/false
* - uploadId: string
* - ttl: number (秒)
*/
export async function POST(req: NextRequest) {
console.log(`[RefreshSession] 收到会话刷新请求 at ${new Date().toISOString()}`)
try {
// 验证用户身份
const userId = await getAuthenticatedUploadUserId(req)
if (!userId) {
console.log(`[RefreshSession] 用户未登录`)
return NextResponse.json({ error: '请先登录' }, { status: 401 })
}
// 解析请求参数
const { uploadId } = await req.json()
if (typeof uploadId !== 'string' || !uploadId.trim()) {
console.log(`[RefreshSession] 缺少uploadId参数`)
return NextResponse.json(
{ error: '缺少uploadId参数' },
{ status: 400 }
)
}
const normalizedUploadId = uploadId.trim()
if (!isSafeUploadId(normalizedUploadId)) {
return NextResponse.json({ error: 'uploadId 格式无效' }, { status: 400 })
}
console.log(`[RefreshSession] 尝试刷新会话: ${normalizedUploadId}, 用户: ${userId}`)
// 刷新会话TTL;Redis 键已过期时允许从当前用户的 meta.json 安全重建。
const result = await refreshOwnedUploadSession(normalizedUploadId, userId)
if (result !== 'refreshed') {
console.log(`[RefreshSession] 会话不存在或不属于当前用户: ${normalizedUploadId}`)
return NextResponse.json(
{ error: '会话不存在或已过期' },
{ status: 404 }
)
}
console.log(`[RefreshSession] 会话刷新成功: ${normalizedUploadId}, TTL: 4小时`)
return NextResponse.json({
success: true,
uploadId: normalizedUploadId,
ttl: 4 * 60 * 60 // 4小时(秒)
})
} catch (error) {
console.error('[RefreshSession] 刷新会话失败:', error)
if (error instanceof UploadSessionStoreUnavailableError) {
return NextResponse.json(
{
error: '上传会话服务暂时不可用,已保留上传进度,请稍后重试',
code: 'UPLOAD_SESSION_STORE_UNAVAILABLE',
},
{ status: 503, headers: { 'Retry-After': '3' } },
)
}
return NextResponse.json(
{ error: '刷新会话失败' },
{ status: 500 }
)
}
}