d25d482dc2
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
130 lines
4.8 KiB
TypeScript
130 lines
4.8 KiB
TypeScript
import { createLogger } from '@sim/logger'
|
|
import { getErrorMessage } from '@sim/utils/errors'
|
|
import { type NextRequest, NextResponse } from 'next/server'
|
|
import { dropboxUploadContract } from '@/lib/api/contracts/storage-transfer'
|
|
import { parseRequest } from '@/lib/api/server'
|
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
import { generateRequestId } from '@/lib/core/utils/request'
|
|
import { httpHeaderSafeJson } from '@/lib/core/utils/validation'
|
|
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
|
import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils'
|
|
import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
|
import { docNotReadyResponse } from '@/lib/uploads/utils/servable-file-response'
|
|
import { assertToolFileAccess } from '@/app/api/files/authorization'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
const logger = createLogger('DropboxUploadAPI')
|
|
|
|
export const POST = withRouteHandler(async (request: NextRequest) => {
|
|
const requestId = generateRequestId()
|
|
|
|
try {
|
|
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
|
|
if (!authResult.success || !authResult.userId) {
|
|
logger.warn(`[${requestId}] Unauthorized Dropbox upload attempt: ${authResult.error}`)
|
|
return NextResponse.json(
|
|
{ success: false, error: authResult.error || 'Authentication required' },
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
logger.info(`[${requestId}] Authenticated Dropbox upload request via ${authResult.authType}`)
|
|
|
|
const parsed = await parseRequest(dropboxUploadContract, request, {})
|
|
if (!parsed.success) return parsed.response
|
|
const validatedData = parsed.data.body
|
|
|
|
let fileBuffer: Buffer
|
|
let fileName: string
|
|
|
|
// Prefer UserFile input, fall back to legacy base64 string
|
|
if (validatedData.file) {
|
|
// Process UserFile input
|
|
const userFiles = processFilesToUserFiles(
|
|
[validatedData.file as RawFileInput],
|
|
requestId,
|
|
logger
|
|
)
|
|
|
|
if (userFiles.length === 0) {
|
|
return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 })
|
|
}
|
|
|
|
const userFile = userFiles[0]
|
|
logger.info(`[${requestId}] Downloading file: ${userFile.name} (${userFile.size} bytes)`)
|
|
|
|
const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger)
|
|
if (denied) return denied
|
|
try {
|
|
const result = await downloadServableFileFromStorage(userFile, requestId, logger)
|
|
fileBuffer = result.buffer
|
|
} catch (error) {
|
|
const notReady = docNotReadyResponse(error)
|
|
if (notReady) return notReady
|
|
return NextResponse.json(
|
|
{ success: false, error: getErrorMessage(error, 'Failed to download file') },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
fileName = userFile.name
|
|
} else if (validatedData.fileContent) {
|
|
// Legacy: base64 string input (backwards compatibility)
|
|
logger.info(`[${requestId}] Using legacy base64 content input`)
|
|
fileBuffer = Buffer.from(validatedData.fileContent, 'base64')
|
|
fileName = validatedData.fileName || 'file'
|
|
} else {
|
|
return NextResponse.json({ success: false, error: 'File is required' }, { status: 400 })
|
|
}
|
|
|
|
// Determine final path
|
|
let finalPath = validatedData.path
|
|
if (finalPath.endsWith('/')) {
|
|
finalPath = `${finalPath}${fileName}`
|
|
}
|
|
|
|
logger.info(`[${requestId}] Uploading to Dropbox: ${finalPath} (${fileBuffer.length} bytes)`)
|
|
|
|
const dropboxApiArg = {
|
|
path: finalPath,
|
|
mode: validatedData.mode || 'add',
|
|
autorename: validatedData.autorename ?? false,
|
|
mute: validatedData.mute ?? false,
|
|
}
|
|
|
|
const response = await fetch('https://content.dropboxapi.com/2/files/upload', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
'Content-Type': 'application/octet-stream',
|
|
'Dropbox-API-Arg': httpHeaderSafeJson(dropboxApiArg),
|
|
},
|
|
body: new Uint8Array(fileBuffer),
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
if (!response.ok) {
|
|
const errorMessage = data.error_summary || data.error?.message || 'Failed to upload file'
|
|
logger.error(`[${requestId}] Dropbox API error:`, { status: response.status, data })
|
|
return NextResponse.json({ success: false, error: errorMessage }, { status: response.status })
|
|
}
|
|
|
|
logger.info(`[${requestId}] File uploaded successfully to ${data.path_display}`)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
output: {
|
|
file: data,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
logger.error(`[${requestId}] Unexpected error:`, error)
|
|
return NextResponse.json(
|
|
{ success: false, error: getErrorMessage(error, 'Unknown error') },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
})
|