|
| 1 | +import type { ParsedMail, Source } from "mailparser"; |
| 2 | +import { simpleParser } from "mailparser"; |
| 3 | +import type { NextRequest } from "next/server"; |
| 4 | +import { NextResponse } from "next/server"; |
| 5 | + |
| 6 | +import prisma from "@calcom/prisma"; |
| 7 | + |
| 8 | +import { env } from "../../../env.mjs"; |
| 9 | +import { fetchAvailability } from "../../../tools/getAvailability"; |
| 10 | +import { fetchEventTypes } from "../../../tools/getEventTypes"; |
| 11 | +import getHostFromHeaders from "../../../utils/host"; |
| 12 | +import now from "../../../utils/now"; |
| 13 | +import sendEmail from "../../../utils/sendEmail"; |
| 14 | +import { verifyParseKey } from "../../../utils/verifyParseKey"; |
| 15 | + |
| 16 | +/** |
| 17 | + * Verifies email signature and app authorization, |
| 18 | + * then hands off to booking agent. |
| 19 | + */ |
| 20 | +export const POST = async (request: NextRequest) => { |
| 21 | + const verified = verifyParseKey(request.url); |
| 22 | + |
| 23 | + if (!verified) { |
| 24 | + return new NextResponse("Unauthorized", { status: 401 }); |
| 25 | + } |
| 26 | + |
| 27 | + const formData = await request.formData(); |
| 28 | + const body = Object.fromEntries(formData); |
| 29 | + |
| 30 | + // body.dkim looks like {@domain-com.22222222.gappssmtp.com : pass} |
| 31 | + const signature = (body.dkim as string).includes(" : pass"); |
| 32 | + |
| 33 | + const envelope = JSON.parse(body.envelope as string); |
| 34 | + |
| 35 | + const aiEmail = envelope.to[0]; |
| 36 | + |
| 37 | + // Parse email from mixed MIME type |
| 38 | + const parsed: ParsedMail = await simpleParser(body.email as Source); |
| 39 | + |
| 40 | + if (!parsed.text && !parsed.subject) { |
| 41 | + return new NextResponse("Email missing text and subject", { status: 400 }); |
| 42 | + } |
| 43 | + |
| 44 | + const user = await prisma.user.findUnique({ |
| 45 | + select: { |
| 46 | + email: true, |
| 47 | + id: true, |
| 48 | + credentials: { |
| 49 | + select: { |
| 50 | + appId: true, |
| 51 | + key: true, |
| 52 | + }, |
| 53 | + }, |
| 54 | + }, |
| 55 | + where: { email: envelope.from }, |
| 56 | + }); |
| 57 | + |
| 58 | + if (!signature || !user?.email || !user?.id) { |
| 59 | + await sendEmail({ |
| 60 | + subject: `Re: ${body.subject}`, |
| 61 | + text: "Sorry, you are not authorized to use this service. Please verify your email address and try again.", |
| 62 | + to: user?.email || "", |
| 63 | + from: aiEmail, |
| 64 | + }); |
| 65 | + |
| 66 | + return new NextResponse(); |
| 67 | + } |
| 68 | + |
| 69 | + const credential = user.credentials.find((c) => c.appId === env.APP_ID)?.key; |
| 70 | + |
| 71 | + // User has not installed the app from the app store. Direct them to install it. |
| 72 | + if (!(credential as { apiKey: string })?.apiKey) { |
| 73 | + const url = env.APP_URL; |
| 74 | + |
| 75 | + await sendEmail({ |
| 76 | + html: `Thanks for using Cal AI! To get started, the app must be installed. <a href=${url} target="_blank">Click this link</a> to install it.`, |
| 77 | + subject: `Re: ${body.subject}`, |
| 78 | + text: `Thanks for using Cal AI! To get started, the app must be installed. Click this link to install the Cal AI app: ${url}`, |
| 79 | + to: envelope.from, |
| 80 | + from: aiEmail, |
| 81 | + }); |
| 82 | + |
| 83 | + return new NextResponse("ok"); |
| 84 | + } |
| 85 | + |
| 86 | + const { apiKey } = credential as { apiKey: string }; |
| 87 | + |
| 88 | + // Pre-fetch data relevant to most bookings. |
| 89 | + const [eventTypes, availability] = await Promise.all([ |
| 90 | + fetchEventTypes({ |
| 91 | + apiKey, |
| 92 | + }), |
| 93 | + fetchAvailability({ |
| 94 | + apiKey, |
| 95 | + userId: user.id, |
| 96 | + dateFrom: now, |
| 97 | + dateTo: now, |
| 98 | + }), |
| 99 | + ]); |
| 100 | + |
| 101 | + if ("error" in availability) { |
| 102 | + await sendEmail({ |
| 103 | + subject: `Re: ${body.subject}`, |
| 104 | + text: "Sorry, there was an error fetching your availability. Please try again.", |
| 105 | + to: user.email, |
| 106 | + from: aiEmail, |
| 107 | + }); |
| 108 | + console.error(availability.error); |
| 109 | + return new NextResponse("Error fetching availability. Please try again.", { status: 400 }); |
| 110 | + } |
| 111 | + |
| 112 | + if ("error" in eventTypes) { |
| 113 | + await sendEmail({ |
| 114 | + subject: `Re: ${body.subject}`, |
| 115 | + text: "Sorry, there was an error fetching your event types. Please try again.", |
| 116 | + to: user.email, |
| 117 | + from: aiEmail, |
| 118 | + }); |
| 119 | + console.error(eventTypes.error); |
| 120 | + return new NextResponse("Error fetching event types. Please try again.", { status: 400 }); |
| 121 | + } |
| 122 | + |
| 123 | + const { timeZone, workingHours } = availability; |
| 124 | + |
| 125 | + const appHost = getHostFromHeaders(request.headers); |
| 126 | + |
| 127 | + // Hand off to long-running agent endpoint to handle the email. (don't await) |
| 128 | + fetch(`${appHost}/api/agent?parseKey=${env.PARSE_KEY}`, { |
| 129 | + body: JSON.stringify({ |
| 130 | + apiKey, |
| 131 | + userId: user.id, |
| 132 | + message: parsed.text, |
| 133 | + subject: parsed.subject, |
| 134 | + replyTo: aiEmail, |
| 135 | + user: { |
| 136 | + email: user.email, |
| 137 | + eventTypes, |
| 138 | + timeZone, |
| 139 | + workingHours, |
| 140 | + }, |
| 141 | + }), |
| 142 | + headers: { |
| 143 | + "Content-Type": "application/json", |
| 144 | + }, |
| 145 | + method: "POST", |
| 146 | + }); |
| 147 | + |
| 148 | + await new Promise((r) => setTimeout(r, 1000)); |
| 149 | + |
| 150 | + return new NextResponse("ok"); |
| 151 | +}; |
0 commit comments