forked from agentic-review-benchmarks/cal.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsendPayload.ts
More file actions
335 lines (294 loc) · 9.12 KB
/
sendPayload.ts
File metadata and controls
335 lines (294 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { createHmac } from "node:crypto";
import { compile } from "handlebars";
import type { TGetTranscriptAccessLink } from "@calcom/app-store/dailyvideo/zod";
import { getHumanReadableLocationValue } from "@calcom/app-store/locations";
import type { WebhookSubscriber, PaymentData } from "@calcom/features/webhooks/lib/dto/types";
import { DelegationCredentialErrorPayloadType } from "@calcom/features/webhooks/lib/dto/types";
import { getUTCOffsetByTimezone } from "@calcom/lib/dayjs";
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
// Minimal webhook shape for sending payloads (subset of WebhookSubscriber)
type WebhookForPayload = Pick<WebhookSubscriber, "subscriberUrl" | "appId" | "payloadTemplate" | "version">;
type ContentType = "application/json" | "application/x-www-form-urlencoded";
export type EventTypeInfo = {
eventTitle?: string | null;
eventDescription?: string | null;
requiresConfirmation?: boolean | null;
price?: number | null;
currency?: string | null;
length?: number | null;
};
export type UTCOffset = {
utcOffset?: number | null;
};
export type WithUTCOffsetType<T> = T & {
user?: Person & UTCOffset;
} & {
organizer?: Person & UTCOffset;
} & {
attendees?: (Person & UTCOffset)[];
};
export type BookingNoShowUpdatedPayload = {
message: string;
bookingUid: string;
bookingId?: number;
attendees: { email: string; noShow: boolean }[];
};
export type TranscriptionGeneratedPayload = {
downloadLinks?: {
transcription: TGetTranscriptAccessLink["transcription"];
recording: string;
};
};
export type OOOEntryPayloadType = {
oooEntry: {
id: number;
start: string;
end: string;
createdAt: string;
updatedAt: string;
notes: string | null;
reason: {
emoji?: string;
reason?: string;
};
reasonId: number;
user: {
id: number;
name: string | null;
username: string | null;
timeZone: string;
email: string;
};
toUser: {
id: number;
name?: string | null;
username?: string | null;
timeZone?: string;
email?: string;
} | null;
uuid: string;
};
};
export type EventPayloadType = CalendarEvent &
TranscriptionGeneratedPayload &
EventTypeInfo & {
uid?: string | null;
metadata?: { [key: string]: string | number | boolean | null };
bookingId?: number;
status?: string;
smsReminderNumber?: string;
rescheduleId?: number;
rescheduleUid?: string;
rescheduleStartTime?: string;
rescheduleEndTime?: string;
downloadLink?: string;
paymentId?: number;
rescheduledBy?: string;
cancelledBy?: string;
paymentData?: PaymentData;
requestReschedule?: boolean;
};
export type WebhookPayloadType =
| EventPayloadType
| OOOEntryPayloadType
| BookingNoShowUpdatedPayload
| DelegationCredentialErrorPayloadType;
type WebhookDataType = WebhookPayloadType & { triggerEvent: string; createdAt: string };
function addUTCOffset(data: WebhookPayloadType): WithUTCOffsetType<WebhookPayloadType> {
if (isEventPayload(data)) {
if (data.organizer?.timeZone) {
(data.organizer as Person & UTCOffset).utcOffset = getUTCOffsetByTimezone(
data.organizer.timeZone,
data.startTime
);
}
if (data.attendees?.length) {
(data.attendees as (Person & UTCOffset)[]).forEach((attendee) => {
attendee.utcOffset = getUTCOffsetByTimezone(attendee.timeZone, data.startTime);
});
}
}
return data as WithUTCOffsetType<WebhookPayloadType>;
}
function getZapierPayload(data: WithUTCOffsetType<EventPayloadType & { createdAt: string }>): string {
const attendees = (data.attendees as (Person & UTCOffset)[]).map((attendee) => {
return {
name: attendee.name,
email: attendee.email,
timeZone: attendee.timeZone,
utcOffset: attendee.utcOffset,
};
});
const t = data.organizer.language.translate;
const location = getHumanReadableLocationValue(data.location || "", t);
const body = {
uid: data.uid,
title: data.title,
description: data.description,
customInputs: data.customInputs,
responses: data.responses,
userFieldsResponses: data.userFieldsResponses,
startTime: data.startTime,
endTime: data.endTime,
location: location,
status: data.status,
cancellationReason: data.cancellationReason,
user: {
username: data.organizer.username,
usernameInOrg: data.organizer.usernameInOrg,
name: data.organizer.name,
email: data.organizer.email,
timeZone: data.organizer.timeZone,
utcOffset: data.organizer.utcOffset,
locale: data.organizer.locale,
},
eventType: {
title: data.eventTitle,
description: data.eventDescription,
requiresConfirmation: data.requiresConfirmation,
price: data.price,
currency: data.currency,
length: data.length,
},
attendees: attendees,
createdAt: data.createdAt,
metadata: {
videoCallUrl: data.metadata?.videoCallUrl,
},
};
return JSON.stringify(body);
}
function applyTemplate(
template: string,
data: WebhookDataType | Record<string, unknown>,
contentType: ContentType
) {
const compiled = compile(template)(data).replace(/"/g, '"');
if (contentType === "application/json") {
return JSON.stringify(jsonParse(compiled));
}
return compiled;
}
export function jsonParse(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch {
// don't do anything.
}
return false;
}
export function isOOOEntryPayload(data: WebhookPayloadType): data is OOOEntryPayloadType {
return "oooEntry" in data;
}
export function isNoShowPayload(data: WebhookPayloadType): data is BookingNoShowUpdatedPayload {
return "message" in data && "bookingUid" in data;
}
export function isDelegationCredentialErrorPayload(
data: WebhookPayloadType
): data is DelegationCredentialErrorPayloadType {
return "error" in data && "credential" in data && "user" in data;
}
export function isEventPayload(data: WebhookPayloadType): data is EventPayloadType {
return !isNoShowPayload(data) && !isOOOEntryPayload(data) && !isDelegationCredentialErrorPayload(data);
}
const sendPayload = async (
secretKey: string | null,
triggerEvent: string,
createdAt: string,
webhook: WebhookForPayload,
data: WebhookPayloadType
) => {
const { appId, payloadTemplate: template } = webhook;
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
data = addUTCOffset(data);
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (isEventPayload(data)) {
data.description = data.description || data.additionalNotes;
if (appId === "zapier") {
body = getZapierPayload({ ...data, createdAt });
}
}
if (body === undefined) {
if (
template &&
(isOOOEntryPayload(data) ||
isEventPayload(data) ||
isNoShowPayload(data) ||
isDelegationCredentialErrorPayload(data))
) {
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
}
return _sendPayload(secretKey, webhook, body, contentType);
};
export const sendGenericWebhookPayload = async ({
secretKey,
triggerEvent,
createdAt,
webhook,
data,
rootData,
}: {
secretKey: string | null;
triggerEvent: string;
createdAt: string;
webhook: WebhookForPayload;
data: Record<string, unknown>;
rootData?: Record<string, unknown>;
}) => {
const { payloadTemplate: template } = webhook;
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
const defaultPayload = {
// Added rootData props first so that using the known(i.e. triggerEvent, createdAt, payload) properties in rootData doesn't override the known properties
...rootData,
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
};
let body: string;
if (template) {
body = applyTemplate(template, defaultPayload, contentType);
} else {
body = JSON.stringify(defaultPayload);
}
return _sendPayload(secretKey, webhook, body, contentType);
};
export const createWebhookSignature = (params: { secret?: string | null; body: string }) =>
params.secret
? createHmac("sha256", params.secret).update(`${params.body}`).digest("hex")
: "no-secret-provided";
const _sendPayload = async (
secretKey: string | null,
webhook: WebhookForPayload,
body: string,
contentType: "application/json" | "application/x-www-form-urlencoded"
) => {
const { subscriberUrl, version } = webhook;
if (!subscriberUrl || !body) {
throw new Error("Missing required elements to send webhook payload.");
}
const response = await fetch(subscriberUrl, {
method: "POST",
headers: {
"Content-Type": contentType,
"X-Cal-Signature-256": createWebhookSignature({ secret: secretKey, body }),
"X-Cal-Webhook-Version": version,
},
redirect: "manual",
body,
});
return {
ok: response.ok,
status: response.status,
};
};
export default sendPayload;