Webex integration (#7651)

* start webex app creation

* webex integration wip

* fix lint errors

* fix lint errors

* add webex env vars in appStore.example

* webex app wip

* fix lint errors

* edit webex oauth scopes

* add location in webex app config

* add site url placeholder and regex in webex config location

* debug translateEvent

* fix utc formatting for event start time, add test boilerplate for webex, add envs

* fix location and datetime formatting

* get correct videoCredentials for deleteMeeting

* Move webex specific readme content to webex README

* Fix app not visible in app-store

* Delete setup route

* add webex icon

* delete prev icon

* webex api fix

* add app screenshots

* Revert tests changes as they dont run

* Use config instead of hardcoding vales

* Update README

* Remove all env variables related to WEBEX app. They can be added through settings->admin->apps interface

* update from origin

* fix icon path

* update webex readme

* Update yarn.lock

* update webex readme

* Remove unnecessary URL from webex

* revert changes in cancel booking handler

* simply webex zod schemas, logs for debugging

---------

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-05-11 07:14:32 +00:00
1 parent 067b77faf1
commit e2cfd0d1d1
31 files changed
+912 -86

No files matched your search

@@ -24,6 +24,7 @@ import { appKeysSchema as tandemvideo_zod_ts } from "./tandemvideo/zod";
import { appKeysSchema as booking_pages_tag_zod_ts } from "./templates/booking-pages-tag/zod";
import { appKeysSchema as event_type_app_card_zod_ts } from "./templates/event-type-app-card/zod";
import { appKeysSchema as vital_zod_ts } from "./vital/zod";
import { appKeysSchema as webex_zod_ts } from "./webex/zod";
import { appKeysSchema as wordpress_zod_ts } from "./wordpress/zod";
import { appKeysSchema as zapier_zod_ts } from "./zapier/zod";
import { appKeysSchema as zoho_bigin_zod_ts } from "./zoho-bigin/zod";
@@ -53,6 +54,7 @@ export const appKeysSchemas = {
"booking-pages-tag": booking_pages_tag_zod_ts,
"event-type-app-card": event_type_app_card_zod_ts,
vital: vital_zod_ts,
webex: webex_zod_ts,
wordpress: wordpress_zod_ts,
zapier: zapier_zod_ts,
"zoho-bigin": zoho_bigin_zod_ts,
@@ -55,6 +55,7 @@ import typeform_config_json from "./typeform/config.json";
import vimcal_config_json from "./vimcal/config.json";
import { metadata as vital__metadata_ts } from "./vital/_metadata";
import weather_in_your_calendar_config_json from "./weather_in_your_calendar/config.json";
import webex_config_json from "./webex/config.json";
import whatsapp_config_json from "./whatsapp/config.json";
import whereby_config_json from "./whereby/config.json";
import { metadata as wipemycalother__metadata_ts } from "./wipemycalother/_metadata";
@@ -118,6 +119,7 @@ export const appStoreMetadata = {
vimcal: vimcal_config_json,
vital: vital__metadata_ts,
weather_in_your_calendar: weather_in_your_calendar_config_json,
webex: webex_config_json,
whatsapp: whatsapp_config_json,
whereby: whereby_config_json,
wipemycalother: wipemycalother__metadata_ts,
@@ -24,6 +24,7 @@ import { appDataSchema as tandemvideo_zod_ts } from "./tandemvideo/zod";
import { appDataSchema as booking_pages_tag_zod_ts } from "./templates/booking-pages-tag/zod";
import { appDataSchema as event_type_app_card_zod_ts } from "./templates/event-type-app-card/zod";
import { appDataSchema as vital_zod_ts } from "./vital/zod";
import { appDataSchema as webex_zod_ts } from "./webex/zod";
import { appDataSchema as wordpress_zod_ts } from "./wordpress/zod";
import { appDataSchema as zapier_zod_ts } from "./zapier/zod";
import { appDataSchema as zoho_bigin_zod_ts } from "./zoho-bigin/zod";
@@ -53,6 +54,7 @@ export const appDataSchemas = {
"booking-pages-tag": booking_pages_tag_zod_ts,
"event-type-app-card": event_type_app_card_zod_ts,
vital: vital_zod_ts,
webex: webex_zod_ts,
wordpress: wordpress_zod_ts,
zapier: zapier_zod_ts,
"zoho-bigin": zoho_bigin_zod_ts,
@@ -55,6 +55,7 @@ export const apiHandlers = {
vimcal: import("./vimcal/api"),
vital: import("./vital/api"),
weather_in_your_calendar: import("./weather_in_your_calendar/api"),
webex: import("./webex/api"),
whatsapp: import("./whatsapp/api"),
whereby: import("./whereby/api"),
wipemycalother: import("./wipemycalother/api"),
+1
View File
@@ -21,6 +21,7 @@ const appStore = {
vital: () => import("./vital"),
zoomvideo: () => import("./zoomvideo"),
wipemycalother: () => import("./wipemycalother"),
webexvideo: () => import("./webex"),
giphy: () => import("./giphy"),
zapier: () => import("./zapier"),
exchange2013calendar: () => import("./exchange2013calendar"),
+9
View File
@@ -0,0 +1,9 @@
---
items:
- 1.jpeg
- 2.jpeg
- 3.jpeg
- 4.jpeg
---
{DESCRIPTION}
+14
View File
@@ -0,0 +1,14 @@
### Obtaining Webex Client ID and Secret
1. Create a [Webex](https://www.webex.com/) acount, if you don't already have one.
2. Go to [Webex for Developers](https://developer.webex.com/) and sign into to your Webex account. (Note: If you're creating a new account, create it on [Webex](https://www.webex.com/), not on [Webex for Developers](https://developer.webex.com/))
3. On the upper right, click the profile icon and go to ["My Webex Apps"](https://developer.webex.com/my-apps)
4. Click on "Create a New App" and select ["Integration"](https://developer.webex.com/my-apps/new/integration)
5. Choose "No" for "Will this use a mobile SDK?"
6. Give your app a name.
7. Upload an icon or choose one of the default icons.
8. Give your app a short description.
9. Set the Redirect URI as `<Cal.com URL>/api/integrations/webex/callback` replacing Cal.com URL with the URI at which your application runs.
10. Select the following scopes: "meeting:schedules_read", "meeting:schedules_write".
11. Click "Add Integration".
12. Copy the Client ID and Client Secret and add these while enabling the app through Settings -> Admin -> Apps interface
+39
View File
@@ -0,0 +1,39 @@
import type { NextApiRequest } from "next";
import { stringify } from "querystring";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { defaultHandler, defaultResponder } from "@calcom/lib/server";
import prisma from "@calcom/prisma";
import config from "../config.json";
import { getWebexAppKeys } from "../lib/getWebexAppKeys";
async function handler(req: NextApiRequest) {
// Get user
await prisma.user.findFirstOrThrow({
where: {
id: req.session?.user?.id,
},
select: {
id: true,
},
});
const { client_id } = await getWebexAppKeys();
/** @link https://developer.webex.com/docs/integrations#requesting-permission */
const params = {
response_type: "code",
client_id,
redirect_uri: `${WEBAPP_URL}/api/integrations/${config.slug}/callback`,
scope: "spark:kms meeting:schedules_read meeting:schedules_write", //should be "A space-separated list of scopes being requested by your integration"
state: "",
};
const query = stringify(params).replaceAll("+", "%20");
const url = `https://webexapis.com/v1/authorize?${query}`;
return { url };
}
export default defaultHandler({
GET: Promise.resolve({ default: defaultResponder(handler) }),
});
+99
View File
@@ -0,0 +1,99 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { WEBAPP_URL } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import getInstalledAppPath from "../../_utils/getInstalledAppPath";
import config from "../config.json";
import { getWebexAppKeys } from "../lib/getWebexAppKeys";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code } = req.query;
const { client_id, client_secret } = await getWebexAppKeys();
/** @link https://developer.webex.com/docs/integrations#getting-an-access-token **/
const redirectUri = encodeURI(`${WEBAPP_URL}/api/integrations/${config.slug}/callback`);
const authHeader = "Basic " + Buffer.from(client_id + ":" + client_secret).toString("base64");
const result = await fetch(
"https://webexapis.com/v1/access_token?grant_type=authorization_code&client_id" +
client_id +
"&client_secret=" +
client_secret +
"&code=" +
code +
"&redirect_uri=" +
redirectUri,
{
method: "POST",
headers: {
Authorization: authHeader,
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
if (result.status !== 200) {
let errorMessage = "Something is wrong with Webex API";
try {
const responseBody = await result.json();
errorMessage = responseBody.error;
} catch (e) {}
res.status(400).json({ message: errorMessage });
return;
}
const responseBody = await result.json();
if (responseBody.error) {
res.status(400).json({ message: responseBody.error });
return;
}
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
const userId = req.session?.user.id;
if (!userId) {
return res.status(404).json({ message: "No user found" });
}
/**
* With this we take care of no duplicate webex key for a single user
* when creating a video room we only do findFirst so the if they have more than 1
* others get ignored
* */
const existingCredentialWebexVideo = await prisma.credential.findMany({
select: {
id: true,
},
where: {
type: config.type,
userId: req.session?.user.id,
appId: config.slug,
},
});
// Making sure we only delete webex_video
const credentialIdsToDelete = existingCredentialWebexVideo.map((item) => item.id);
if (credentialIdsToDelete.length > 0) {
await prisma.credential.deleteMany({ where: { id: { in: credentialIdsToDelete }, userId } });
}
await prisma.user.update({
where: {
id: req.session?.user.id,
},
data: {
credentials: {
create: {
type: config.type,
key: responseBody,
appId: config.slug,
},
},
},
});
res.redirect(getInstalledAppPath({ variant: config.variant, slug: config.slug }));
}
+2
View File
@@ -0,0 +1,2 @@
export { default as add } from "./add";
export { default as callback } from "./callback";
+25
View File
@@ -0,0 +1,25 @@
{
"/*": "Don't modify slug - If required, do it using cli edit command",
"name": "Webex",
"title": "Webex",
"slug": "webex",
"type": "webex_video",
"imageSrc": "/icon.ico",
"logo": "/icon.ico",
"url": "https://cal.com/apps/webex",
"variant": "conferencing",
"categories": ["video"],
"publisher": "Cal.com, Inc.",
"email": "[email protected]",
"description": "Create meetings with Cisco Webex",
"appData": {
"location": {
"linkType": "dynamic",
"type": "integrations:webex_video",
"label": "Webex"
}
},
"isTemplate": false,
"__createdUsingCli": true,
"__template": "basic"
}
+2
View File
@@ -0,0 +1,2 @@
export * as api from "./api";
export * as lib from "./lib";
@@ -0,0 +1,304 @@
import { z } from "zod";
import dayjs from "@calcom/dayjs";
import prisma from "@calcom/prisma";
import type { Credential } from "@calcom/prisma/client";
import type { CalendarEvent } from "@calcom/types/Calendar";
import type { CredentialPayload } from "@calcom/types/Credential";
import type { PartialReference } from "@calcom/types/EventManager";
import type { VideoApiAdapter, VideoCallData } from "@calcom/types/VideoApiAdapter";
import { getWebexAppKeys } from "./getWebexAppKeys";
/** @link https://developer.webex.com/docs/meetings **/
const webexEventResultSchema = z.object({
id: z.string(),
webLink: z.string(),
siteUrl: z.string(),
password: z.string().optional().default(""),
});
export type WebexEventResult = z.infer<typeof webexEventResultSchema>;
/** @link https://developer.webex.com/docs/api/v1/meetings/create-a-meeting */
export const webexMeetingSchema = z.object({
start: z.date(),
end: z.date(),
});
/** @link https://developer.webex.com/docs/api/v1/meetings/list-meetings */
export const webexMeetingsSchema = z.object({
items: z.array(webexMeetingSchema),
});
/** @link https://developer.webex.com/docs/integrations#getting-an-access-token */
const webexTokenSchema = z.object({
scope: z.literal("spark:kms meeting:schedules_read meeting:schedules_write"),
token_type: z.literal("Bearer"),
access_token: z.string(),
expires_in: z.number().optional(),
refresh_token: z.string(),
refresh_token_expires_in: z.number(),
expiry_date: z.number(),
});
type WebexToken = z.infer<typeof webexTokenSchema>;
const isTokenValid = (token: WebexToken) => token.expiry_date < Date.now();
/** @link https://developer.webex.com/docs/integrations#using-the-refresh-token */
const webexRefreshedTokenSchema = z.object({
scope: z.literal("spark:kms meeting:schedules_read meeting:schedules_write"),
token_type: z.literal("Bearer"),
access_token: z.string(),
expires_in: z.number().optional(),
refresh_token: z.string(),
refresh_token_expires_in: z.number(),
});
const webexAuth = (credential: CredentialPayload) => {
const refreshAccessToken = async (refreshToken: string) => {
const { client_id, client_secret } = await getWebexAppKeys();
const response = await fetch("https://webexapis.com/v1/access_token", {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: client_id,
client_secret: client_secret,
refresh_token: refreshToken,
}),
});
const responseBody = await handleWebexResponse(response, credential.id);
if (responseBody.error) {
if (responseBody.error === "invalid_grant") {
return Promise.reject(new Error("Invalid grant for Cal.com webex app"));
}
}
// We check the if the new credentials matches the expected response structure
const parsedToken = webexRefreshedTokenSchema.safeParse(responseBody);
if (!parsedToken.success) {
return Promise.reject(new Error("Invalid refreshed tokens were returned"));
}
const newTokens = parsedToken.data;
const oldCredential = await prisma.credential.findUniqueOrThrow({ where: { id: credential.id } });
const parsedKey = webexTokenSchema.safeParse(oldCredential.key);
if (!parsedKey.success) {
return Promise.reject(new Error("Invalid credentials were saved in the DB"));
}
const key = parsedKey.data;
key.access_token = newTokens.access_token;
key.refresh_token = newTokens.refresh_token;
// set expiry date as offset from current time.
if (newTokens.expires_in) {
key.expiry_date = Math.round(Date.now() + newTokens.expires_in * 1000);
}
// Store new tokens in database.
await prisma.credential.update({ where: { id: credential.id }, data: { key } });
return newTokens.access_token;
};
return {
getToken: async () => {
let credentialKey: WebexToken | null = null;
try {
credentialKey = webexTokenSchema.parse(credential.key);
} catch (error) {
return Promise.reject("Webex credential keys parsing error");
}
return !isTokenValid(credentialKey)
? Promise.resolve(credentialKey.access_token)
: refreshAccessToken(credentialKey.refresh_token);
},
};
};
const WebexVideoApiAdapter = (credential: CredentialPayload): VideoApiAdapter => {
//TODO implement translateEvent for recurring events
const translateEvent = (event: CalendarEvent) => {
//To convert the Cal's CalendarEvent type to a webex meeting type
/** @link https://developer.webex.com/docs/api/v1/meetings/create-a-meeting */
//Required params - title, start, end
return {
title: event.title,
start: dayjs(event.startTime).utc().format(),
end: dayjs(event.endTime).utc().format(),
recurrence: event.recurrence, //Follows RFC 2445 https://www.ietf.org/rfc/rfc2445.txt, TODO check if needs conversion
// timezone: event.organizer.timeZone, // Comment this out for now
agenda: event.description,
enableJoinBeforeHost: true, //this is true in zoom's api, do we need it here?
invitees: event.attendees.map((attendee) => ({
email: attendee.email,
})),
sendEmail: true,
};
};
const fetchWebexApi = async (endpoint: string, options?: RequestInit) => {
const auth = webexAuth(credential);
const accessToken = await auth.getToken();
console.log("result of accessToken in fetchWebexApi", accessToken);
console.log("createMeeting options in fetchWebexApi", options);
const response = await fetch(`https://webexapis.com/v1/${endpoint}`, {
method: "GET",
...options,
headers: {
Authorization: "Bearer " + accessToken,
...options?.headers,
},
});
const responseBody = await handleWebexResponse(response, credential.id);
return responseBody;
};
return {
getAvailability: async () => {
try {
const responseBody = await fetchWebexApi("meetings");
const data = webexMeetingsSchema.passthrough().parse(responseBody);
return data.items.map((meeting) => ({
start: meeting.start,
end: meeting.end,
}));
} catch (err) {
console.error(err);
return [];
}
},
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
/** @link https://developer.webex.com/docs/api/v1/meetings/create-a-meeting */
try {
console.log("Creating meeting", event);
console.log("meting body", translateEvent(event));
console.log("request body in createMeeting", JSON.stringify(translateEvent(event)));
const response = await fetchWebexApi("meetings", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
});
console.log("Webex create meeting response", response);
if (response.error) {
if (response.error === "invalid_grant") {
await invalidateCredential(credential.id);
return Promise.reject(new Error("Invalid grant for Cal.com webex app"));
}
}
const result = webexEventResultSchema.parse(response);
if (result.id && result.webLink) {
return {
type: "webex_video",
id: result.id.toString(),
password: result.password || "",
url: result.webLink,
};
}
throw new Error("Failed to create meeting. Response is " + JSON.stringify(result));
} catch (err) {
console.error(err);
throw new Error("Unexpected error");
}
},
deleteMeeting: async (uid: string): Promise<void> => {
/** @link https://developer.webex.com/docs/api/v1/meetings/delete-a-meeting */
try {
const response = await fetchWebexApi(`meetings/${uid}`, {
method: "DELETE",
});
console.log("Webex delete meeting response", response);
if (response.error) {
if (response.error === "invalid_grant") {
await invalidateCredential(credential.id);
return Promise.reject(new Error("Invalid grant for Cal.com webex app"));
}
}
return Promise.resolve();
} catch (err) {
return Promise.reject(new Error("Failed to delete meeting"));
}
},
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
/** @link https://developer.webex.com/docs/api/v1/meetings/update-a-meeting */
try {
const response = await fetchWebexApi(`meetings/${bookingRef.uid}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
});
if (response.error) {
if (response.error === "invalid_grant") {
await invalidateCredential(credential.id);
return Promise.reject(new Error("Invalid grant for Cal.com webex app"));
}
}
const result = webexEventResultSchema.parse(response);
if (result.id && result.webLink) {
return {
type: "webex_video",
id: bookingRef.meetingId as string,
password: result.password || "",
url: result.webLink,
};
}
throw new Error("Failed to create meeting. Response is " + JSON.stringify(result));
} catch (err) {
console.error(err);
throw new Error("Unexpected error");
}
},
};
};
const handleWebexResponse = async (response: Response, credentialId: Credential["id"]) => {
let _response = response.clone();
const responseClone = response.clone();
if (_response.headers.get("content-encoding") === "gzip") {
const responseString = await response.text();
_response = JSON.parse(responseString);
}
if (!response.ok || (response.status < 200 && response.status >= 300)) {
const responseBody = await _response.json();
if ((response && response.status === 124) || responseBody.error === "invalid_grant") {
await invalidateCredential(credentialId);
}
throw Error(response.statusText);
}
// handle 204 response code with empty response (causes crash otherwise as "" is invalid JSON)
if (response.status === 204) {
return;
}
return responseClone.json();
};
const invalidateCredential = async (credentialId: Credential["id"]) => {
const credential = await prisma.credential.findUnique({
where: {
id: credentialId,
},
});
if (credential) {
await prisma.credential.update({
where: {
id: credentialId,
},
data: {
invalid: true,
},
});
}
};
export default WebexVideoApiAdapter;
@@ -0,0 +1,13 @@
import { z } from "zod";
import getAppKeysFromSlug from "../../_utils/getAppKeysFromSlug";
const webexAppKeysSchema = z.object({
client_id: z.string(),
client_secret: z.string(),
});
export const getWebexAppKeys = async () => {
const appKeys = await getAppKeysFromSlug("webex");
return webexAppKeysSchema.parse(appKeys);
};
+2
View File
@@ -0,0 +1,2 @@
export { getWebexAppKeys } from "./getWebexAppKeys";
export { default as VideoApiAdapter } from "./VideoApiAdapter";
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"name": "@calcom/webex",
"version": "0.0.0",
"main": "./index.ts",
"dependencies": {
"@calcom/lib": "*"
},
"devDependencies": {
"@calcom/types": "*"
},
"description": "Create meetings with Cisco Webex"
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 332 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 391 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+8
View File
@@ -0,0 +1,8 @@
import { z } from "zod";
export const appDataSchema = z.object({});
export const appKeysSchema = z.object({
client_id: z.string().min(64),
client_secret: z.string().min(64),
});
@@ -20,7 +20,7 @@ const zoomEventResultSchema = z.object({
export type ZoomEventResult = z.infer<typeof zoomEventResultSchema>;
// @TODO: add link to the docs
/** @link https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/meetings */
export const zoomMeetingsSchema = z.object({
next_page_token: z.string(),
page_count: z.number(),
+1
View File
@@ -142,6 +142,7 @@ const updateMeeting = async (
const deleteMeeting = async (credential: CredentialPayload, uid: string): Promise<unknown> => {
if (credential) {
const videoAdapter = (await getVideoAdapters([credential]))[0];
logger.debug("videoAdapter inside deleteMeeting", { credential, uid });
// There are certain video apps with no video adapter defined. e.g. riverby,whereby
if (videoAdapter) {
return videoAdapter.deleteMeeting(uid);
@@ -18,6 +18,7 @@ import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
import sendPayload from "@calcom/features/webhooks/lib/sendPayload";
import { isPrismaObjOrUndefined, parseRecurringEvent } from "@calcom/lib";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { handleRefundError } from "@calcom/lib/payment/handleRefundError";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
@@ -503,6 +504,7 @@ async function handler(req: CustomRequest) {
);
if (videoCredential) {
logger.debug("videoCredential inside cancel booking handler", videoCredential);
apiDeletes.push(deleteMeeting(videoCredential, uid));
}
}
+148
View File
@@ -0,0 +1,148 @@
// This file was generated by a custom prisma generator, do not edit manually.
export const SchedulingType = {
ROUND_ROBIN: "ROUND_ROBIN",
COLLECTIVE: "COLLECTIVE",
MANAGED: "MANAGED",
} as const;
export type SchedulingType = (typeof SchedulingType)[keyof typeof SchedulingType];
export const PeriodType = {
UNLIMITED: "UNLIMITED",
ROLLING: "ROLLING",
RANGE: "RANGE",
} as const;
export type PeriodType = (typeof PeriodType)[keyof typeof PeriodType];
export const IdentityProvider = {
CAL: "CAL",
GOOGLE: "GOOGLE",
SAML: "SAML",
} as const;
export type IdentityProvider = (typeof IdentityProvider)[keyof typeof IdentityProvider];
export const UserPermissionRole = {
USER: "USER",
ADMIN: "ADMIN",
} as const;
export type UserPermissionRole = (typeof UserPermissionRole)[keyof typeof UserPermissionRole];
export const MembershipRole = {
MEMBER: "MEMBER",
ADMIN: "ADMIN",
OWNER: "OWNER",
} as const;
export type MembershipRole = (typeof MembershipRole)[keyof typeof MembershipRole];
export const BookingStatus = {
CANCELLED: "CANCELLED",
ACCEPTED: "ACCEPTED",
REJECTED: "REJECTED",
PENDING: "PENDING",
} as const;
export type BookingStatus = (typeof BookingStatus)[keyof typeof BookingStatus];
export const EventTypeCustomInputType = {
TEXT: "TEXT",
TEXTLONG: "TEXTLONG",
NUMBER: "NUMBER",
BOOL: "BOOL",
RADIO: "RADIO",
PHONE: "PHONE",
} as const;
export type EventTypeCustomInputType =
(typeof EventTypeCustomInputType)[keyof typeof EventTypeCustomInputType];
export const ReminderType = {
PENDING_BOOKING_CONFIRMATION: "PENDING_BOOKING_CONFIRMATION",
} as const;
export type ReminderType = (typeof ReminderType)[keyof typeof ReminderType];
export const PaymentOption = {
ON_BOOKING: "ON_BOOKING",
HOLD: "HOLD",
} as const;
export type PaymentOption = (typeof PaymentOption)[keyof typeof PaymentOption];
export const WebhookTriggerEvents = {
BOOKING_CREATED: "BOOKING_CREATED",
BOOKING_RESCHEDULED: "BOOKING_RESCHEDULED",
BOOKING_CANCELLED: "BOOKING_CANCELLED",
FORM_SUBMITTED: "FORM_SUBMITTED",
MEETING_ENDED: "MEETING_ENDED",
} as const;
export type WebhookTriggerEvents = (typeof WebhookTriggerEvents)[keyof typeof WebhookTriggerEvents];
export const AppCategories = {
calendar: "calendar",
messaging: "messaging",
other: "other",
payment: "payment",
video: "video",
web3: "web3",
automation: "automation",
analytics: "analytics",
} as const;
export type AppCategories = (typeof AppCategories)[keyof typeof AppCategories];
export const WorkflowTriggerEvents = {
BEFORE_EVENT: "BEFORE_EVENT",
EVENT_CANCELLED: "EVENT_CANCELLED",
NEW_EVENT: "NEW_EVENT",
AFTER_EVENT: "AFTER_EVENT",
RESCHEDULE_EVENT: "RESCHEDULE_EVENT",
} as const;
export type WorkflowTriggerEvents = (typeof WorkflowTriggerEvents)[keyof typeof WorkflowTriggerEvents];
export const WorkflowActions = {
EMAIL_HOST: "EMAIL_HOST",
EMAIL_ATTENDEE: "EMAIL_ATTENDEE",
SMS_ATTENDEE: "SMS_ATTENDEE",
SMS_NUMBER: "SMS_NUMBER",
EMAIL_ADDRESS: "EMAIL_ADDRESS",
} as const;
export type WorkflowActions = (typeof WorkflowActions)[keyof typeof WorkflowActions];
export const TimeUnit = {
DAY: "DAY",
HOUR: "HOUR",
MINUTE: "MINUTE",
} as const;
export type TimeUnit = (typeof TimeUnit)[keyof typeof TimeUnit];
export const WorkflowTemplates = {
REMINDER: "REMINDER",
CUSTOM: "CUSTOM",
} as const;
export type WorkflowTemplates = (typeof WorkflowTemplates)[keyof typeof WorkflowTemplates];
export const WorkflowMethods = {
EMAIL: "EMAIL",
SMS: "SMS",
} as const;
export type WorkflowMethods = (typeof WorkflowMethods)[keyof typeof WorkflowMethods];
export const FeatureType = {
RELEASE: "RELEASE",
EXPERIMENT: "EXPERIMENT",
OPERATIONAL: "OPERATIONAL",
KILL_SWITCH: "KILL_SWITCH",
PERMISSION: "PERMISSION",
} as const;
export type FeatureType = (typeof FeatureType)[keyof typeof FeatureType];
@@ -212,6 +212,13 @@
"type": "zohocrm_other_calendar",
"isTemplate": false
},
{
"dirName": "webex",
"categories": ["video"],
"slug": "webex",
"type": "webex_video",
"isTemplate": false
},
{
"dirName": "cron",
"categories": ["calendar"],
+8 -6
View File
@@ -1,12 +1,14 @@
import { z } from "zod";
import type { AnyRouter } from "@trpc/server";
import * as trpcNext from "@calcom/trpc/server/adapters/next";
import { createContext as createTrpcContext } from "@calcom/trpc/server/createContext";
import type { AnyRouter } from "@trpc/server";
/**
* Creates an API handler executed by Next.js.
*/
export function createNextApiHandler(router: AnyRouter, isPublic: boolean = false) {
export function createNextApiHandler(router: AnyRouter, isPublic = false) {
return trpcNext.createNextApiHandler({
router,
/**
@@ -57,11 +59,11 @@ export function createNextApiHandler(router: AnyRouter, isPublic: boolean = fals
if (isPublic && paths) {
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
const cacheRules = {
"session": `no-cache`,
"i18n": `no-cache`,
session: `no-cache`,
i18n: `no-cache`,
// Revalidation time here should be 1 second, per https://github.com/calcom/cal.com/pull/6823#issuecomment-1423215321
"slots.getSchedule": `no-cache`, // FIXME
"cityTimezones": `max-age=${ONE_DAY_IN_SECONDS}, stale-while-revalidate`,
cityTimezones: `max-age=${ONE_DAY_IN_SECONDS}, stale-while-revalidate`,
} as const;
const matchedPath = paths.find((v) => v in cacheRules) as keyof typeof cacheRules;
@@ -71,4 +73,4 @@ export function createNextApiHandler(router: AnyRouter, isPublic: boolean = fals
return defaultHeaders;
},
});
};
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { NextApiHandler } from "next";
import { Session } from "next-auth";
import type { NextApiHandler } from "next";
import type { Session } from "next-auth";
import { Credential } from "@calcom/prisma/client";
import type { Credential } from "@calcom/prisma/client";
export type AppDeclarativeHandler = {
appType: string;