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
228 lines
7.7 KiB
TypeScript
228 lines
7.7 KiB
TypeScript
import { createLogger } from '@sim/logger'
|
|
import { getErrorMessage } from '@sim/utils/errors'
|
|
import { type NextRequest, NextResponse } from 'next/server'
|
|
import { gmailDraftContract } from '@/lib/api/contracts/tools/google'
|
|
import { parseRequest } from '@/lib/api/server'
|
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
import { generateRequestId } from '@/lib/core/utils/request'
|
|
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
|
import { processFilesToUserFiles } 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'
|
|
import {
|
|
base64UrlEncode,
|
|
buildMimeMessage,
|
|
buildSimpleEmailMessage,
|
|
fetchThreadingHeaders,
|
|
} from '@/tools/gmail/utils'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
const logger = createLogger('GmailDraftAPI')
|
|
|
|
const GMAIL_API_BASE = 'https://gmail.googleapis.com/gmail/v1/users/me'
|
|
|
|
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 Gmail draft attempt: ${authResult.error}`)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: authResult.error || 'Authentication required',
|
|
},
|
|
{ status: 401 }
|
|
)
|
|
}
|
|
|
|
const userId = authResult.userId
|
|
logger.info(`[${requestId}] Authenticated Gmail draft request via ${authResult.authType}`, {
|
|
userId,
|
|
})
|
|
|
|
const parsed = await parseRequest(gmailDraftContract, request, {})
|
|
if (!parsed.success) return parsed.response
|
|
const validatedData = parsed.data.body
|
|
|
|
logger.info(`[${requestId}] Creating Gmail draft`, {
|
|
to: validatedData.to,
|
|
subject: validatedData.subject || '',
|
|
hasAttachments: !!(validatedData.attachments && validatedData.attachments.length > 0),
|
|
attachmentCount: validatedData.attachments?.length || 0,
|
|
})
|
|
|
|
const threadingHeaders = validatedData.replyToMessageId
|
|
? await fetchThreadingHeaders(validatedData.replyToMessageId, validatedData.accessToken)
|
|
: {}
|
|
|
|
const originalMessageId = threadingHeaders.messageId
|
|
const originalReferences = threadingHeaders.references
|
|
const originalSubject = threadingHeaders.subject
|
|
|
|
let rawMessage: string | undefined
|
|
|
|
if (validatedData.attachments && validatedData.attachments.length > 0) {
|
|
const rawAttachments = validatedData.attachments
|
|
logger.info(`[${requestId}] Processing ${rawAttachments.length} attachment(s)`)
|
|
|
|
const attachments = processFilesToUserFiles(rawAttachments, requestId, logger)
|
|
|
|
if (attachments.length === 0) {
|
|
logger.warn(`[${requestId}] No valid attachments found after processing`)
|
|
} else {
|
|
const totalSize = attachments.reduce((sum, file) => sum + file.size, 0)
|
|
const maxSize = 25 * 1024 * 1024 // 25MB
|
|
|
|
if (totalSize > maxSize) {
|
|
const sizeMB = (totalSize / (1024 * 1024)).toFixed(2)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Total attachment size (${sizeMB}MB) exceeds Gmail's limit of 25MB`,
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const accessResults = await Promise.all(
|
|
attachments.map((file) => assertToolFileAccess(file.key, userId, requestId, logger))
|
|
)
|
|
const denied = accessResults.find((r) => r !== null)
|
|
if (denied) return denied
|
|
|
|
let resolved: Array<{ buffer: Buffer; contentType: string }>
|
|
try {
|
|
resolved = await Promise.all(
|
|
attachments.map(async (file) => {
|
|
logger.info(
|
|
`[${requestId}] Downloading attachment: ${file.name} (${file.size} bytes)`
|
|
)
|
|
return await downloadServableFileFromStorage(file, requestId, logger)
|
|
})
|
|
)
|
|
} catch (error) {
|
|
const notReady = docNotReadyResponse(error)
|
|
if (notReady) return notReady
|
|
logger.error(`[${requestId}] Failed to download an attachment:`, error)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Failed to download attachment: ${getErrorMessage(error, 'Unknown error')}`,
|
|
},
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
|
|
const resolvedTotal = resolved.reduce((sum, r) => sum + r.buffer.length, 0)
|
|
if (resolvedTotal > maxSize) {
|
|
const sizeMB = (resolvedTotal / (1024 * 1024)).toFixed(2)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Total attachment size (${sizeMB}MB) exceeds Gmail's limit of 25MB`,
|
|
},
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
const attachmentBuffers = attachments.map((file, i) => ({
|
|
filename: file.name,
|
|
mimeType: resolved[i].contentType || file.type || 'application/octet-stream',
|
|
content: resolved[i].buffer,
|
|
}))
|
|
|
|
const mimeMessage = buildMimeMessage({
|
|
to: validatedData.to,
|
|
cc: validatedData.cc ?? undefined,
|
|
bcc: validatedData.bcc ?? undefined,
|
|
subject: validatedData.subject || originalSubject || '',
|
|
body: validatedData.body,
|
|
contentType: validatedData.contentType || 'text',
|
|
inReplyTo: originalMessageId,
|
|
references: originalReferences,
|
|
attachments: attachmentBuffers,
|
|
})
|
|
|
|
logger.info(`[${requestId}] Built MIME message for draft (${mimeMessage.length} bytes)`)
|
|
rawMessage = base64UrlEncode(mimeMessage)
|
|
}
|
|
}
|
|
|
|
if (!rawMessage) {
|
|
rawMessage = buildSimpleEmailMessage({
|
|
to: validatedData.to,
|
|
cc: validatedData.cc,
|
|
bcc: validatedData.bcc,
|
|
subject: validatedData.subject || originalSubject,
|
|
body: validatedData.body,
|
|
contentType: validatedData.contentType || 'text',
|
|
inReplyTo: originalMessageId,
|
|
references: originalReferences,
|
|
})
|
|
}
|
|
|
|
const draftMessage: { raw: string; threadId?: string } = { raw: rawMessage }
|
|
|
|
if (validatedData.threadId) {
|
|
draftMessage.threadId = validatedData.threadId
|
|
}
|
|
|
|
const gmailResponse = await fetch(`${GMAIL_API_BASE}/drafts`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
message: draftMessage,
|
|
}),
|
|
})
|
|
|
|
if (!gmailResponse.ok) {
|
|
const errorText = await gmailResponse.text()
|
|
logger.error(`[${requestId}] Gmail API error:`, errorText)
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: `Gmail API error: ${gmailResponse.statusText}`,
|
|
},
|
|
{ status: gmailResponse.status }
|
|
)
|
|
}
|
|
|
|
const data = await gmailResponse.json()
|
|
|
|
logger.info(`[${requestId}] Draft created successfully`, { draftId: data.id })
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
output: {
|
|
content: 'Email drafted successfully',
|
|
metadata: {
|
|
id: data.id,
|
|
message: {
|
|
id: data.message?.id,
|
|
threadId: data.message?.threadId,
|
|
labelIds: data.message?.labelIds,
|
|
},
|
|
},
|
|
},
|
|
})
|
|
} catch (error) {
|
|
logger.error(`[${requestId}] Error creating Gmail draft:`, error)
|
|
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: getErrorMessage(error, 'Internal server error'),
|
|
},
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
})
|