* patch applied

* patch applied

* We shouldn't pollute global css

* Build fixes

* Updates typings

* WIP extracting zoom to package

* Revert "Upgrades next to 12.1 (#1895)" (#1903)

This reverts commit ede0e98e1f.

* Tweak/gitignore prisma zod (#1905)

* Extracts ignored createEventTypeBaseInput

* Adds postinstall script

* Revert "Tweak/gitignore prisma zod (#1905)" (#1906)

This reverts commit 15bfeb30d7.

* Eslint fixes (#1898)

* Eslint fixes

* Docs build fixes

* Upgrade to next 12.1 (#1904)

* Upgrades next to 12.1

* Fixes build

* Updaters e2e test pipelines

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>

* Fix URL by removing slash and backslash (#1733)

* Fix URl by removing slash and backslash

* Implement slugify

* Add data type

* Fixing folder structure

* Solve zod-utils conflict

* Build fixes (#1929)

* Build fixes

* Fixes type error

* WIP

* Conflict fixes

* Removes unused file

* TODO

* WIP

* Type fixes

* Linting

* WIP

* Moved App definition to types

* WIP

* WIP

* WIP

* WIP WIP

* Renamed zoomvideo app

* Import fix

* Daily.co app (#2022)

* Daily.co app

* Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts

Co-authored-by: Omar López <[email protected]>

* Update packages/app-store/dailyvideo/lib/VideoApiAdapter.ts

Co-authored-by: Omar López <[email protected]>

* Missing deps for newly added contants to lib

Co-authored-by: Omar López <[email protected]>

* WIP

* WIP

* WIP

* Daily fixes

* Updated type info

* Slack Oauth integration - api route ideas

* Adds getLocationOptions

* Type fixes

* Adds location option for daily video

* Revert "Slack Oauth integration - api route ideas"

This reverts commit 35ffa78e929339c4badb98cdab4e4b953ecc7cca.

* Slack Oauth + verify sig

* Revert "Slack Oauth + verify sig"

This reverts commit ee95795e0f0ae6d06be4e0a423afb8c315d9af7d.

* Huddle01 migration to app store (#2038)

* Jitsi Video App migration

* Removing uneeded dependencies

* Missed unused reference

* Missing dependency

`@calcom/lib` is needed in the `locationOption.ts` file

* Huddle01 migration to app store

* Jitsi Video App migration (#2027)

* Jitsi Video App migration

* Removing uneeded dependencies

* Missed unused reference

* Missing dependency

`@calcom/lib` is needed in the `locationOption.ts` file

Co-authored-by: Omar López <[email protected]>

* Monorepo/app store MS Teams Integration (#2080)

* Create teamsvideo package

* Remove zoom specific refrences

* Add teams video files

* Rename to office365_video

* Add call back to add crednetial type office365_teams

* Rename to office_video to match type

* Add MS Teams as a location option

* Rename files

* Add teams reponse interface and create meeting

* Comment out Daily imports

* Add check for Teams integration

* Add token checking functions

* Change template to create event rather than meeting

* Add comment to test between create link and event

* Add teams URL to booking

* Ask for just onlineMeeting permission

* Add MS Teams logo

* Add message to have an enterprise account

* Remove comments

* Comment back hasDailyIntegration

* Comment back daily credentials

* Update link to MS Graph section of README

* Move API calls to package

Co-authored-by: Omar López <[email protected]>

* Re-adds missing module for transpiling

* Adds email as required field for app store metadata

* WIP: migrates tandem to app store

* Cleanup

* Migrates tandem api routes to app store

* Fixes tandem api handlers

* Big WIP WIP

* Build fixes

* WIP

* Fixes annoying circular dependency bug

I've spent a whole day on this....

* Location option cleanup

* Type fixes

* Update EventManager.ts

* Update CalendarManager.ts

* Moves CalendarService back to lib

* Moves apple calendar to App Store

* Cleanup

* More cleanup

* Migrates apple calendar

* Returns all connected calendars credentials

* No tsx needed in calcom/lib

* Update auth.ts

* Reordering

* Update i18n.utils.ts

* WIP: Google Meet

* Type fixes

* Type fixes

* Cleanup

* Update LinkIconButton.tsx

* Update TrialBanner.tsx

* Cleanup

* Cleanup

* Type fixes

* Update _appRegistry.ts

* Update fonts.css

* Update CalEventParser.ts

* Delete yarn.lock.rej

* Update eslint-preset.js

* Delete zoom.tsx

* Type fixes

* Migrates caldav to app store

* Cleanup

* Type fixes

* Adds caldav to app store

* Test fixes

* Updates integration tests

* Moar test fixes

* Redirection fixes

* Redirection fixes

* Update timeFormat.ts

* Update booking-pages.test.ts

* Connect button fixes

* Fix empty item

* Cal fixes andrea (#2234)

* Fixes #2178

* Fixes #2178

* Update apps/web/components/availability/Schedule.tsx

* Update apps/web/components/availability/Schedule.tsx

Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>

* added meta viewport to disable zoom on input focus on mobile (#2238)

* Update lint.yml (#2211)

Co-authored-by: Peer Richelsen <[email protected]>

* Fix prisma client bundle makes app slow (#2237)

Co-authored-by: Omar López <[email protected]>

* Slider fixes

* Removed unused code

* Full Shell when unauthed

* App sidebar responsive fixes

* Adds dynamic install button

* Fix for duplicate connected calendars

* Various fixes

* Display notification on app delete

* Reuse connect button

* Adds CalDav button

* Deprecates ConnectIntegration

* Simplify install button

* Adds Google Calendar connect button

* Adds Office 365 Install button

* Migrates Stripe to App Store

* Zoom Install Button (#2244)

* Fix minor css, app image load from static path

* Fix app logos remote img src (#2252)

* Adds missing exports

* Cleanup

* Disables install button for globally enabled apps

* Update EventManager.ts

* Stripe fixes

* Disables example app

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Juan Esteban Nieto Cifuentes <[email protected]>
Co-authored-by: Leo Giovanetti <[email protected]>
Co-authored-by: Sean Brydon <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Bailey Pumfleet <[email protected]>
Co-authored-by: Syed Ali Shahbaz <[email protected]>
Co-authored-by: andreaestefania12 <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Demian Caldelas <[email protected]>
Co-authored-by: Alan <[email protected]>
This commit is contained in:
242 files changed
+4322 -2260

No files matched your search

-114
View File
@@ -1,114 +0,0 @@
import { Person } from "ics";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { getIntegrationName } from "@lib/integrations";
import { BASE_URL } from "./config/constants";
import { CalendarEvent } from "./integrations/calendar/interfaces/Calendar";
const translator = short();
// The odd indentation in this file is necessary because otherwise the leading tabs will be applied into the event description.
export const getWhat = (calEvent: CalendarEvent) => {
return `
${calEvent.organizer.language.translate("what")}:
${calEvent.type}
`;
};
export const getWhen = (calEvent: CalendarEvent) => {
return `
${calEvent.organizer.language.translate("invitee_timezone")}:
${calEvent.attendees[0].timeZone}
`;
};
export const getWho = (calEvent: CalendarEvent) => {
const attendees = calEvent.attendees
.map((attendee) => {
return `
${attendee?.name || calEvent.organizer.language.translate("guest")}
${attendee.email}
`;
})
.join("");
const organizer = `
${calEvent.organizer.name} - ${calEvent.organizer.language.translate("organizer")}
${calEvent.organizer.email}
`;
return `
${calEvent.organizer.language.translate("who")}:
${organizer + attendees}
`;
};
export const getAdditionalNotes = (calEvent: CalendarEvent) => {
return `
${calEvent.organizer.language.translate("additional_notes")}:
${calEvent.description}
`;
};
export const getLocation = (calEvent: CalendarEvent) => {
let providerName = calEvent.location ? getIntegrationName(calEvent.location) : "";
if (calEvent.location && calEvent.location.includes("integrations:")) {
const location = calEvent.location.split(":")[1];
providerName = location[0].toUpperCase() + location.slice(1);
}
if (calEvent.videoCallData) {
return calEvent.videoCallData.url;
}
if (calEvent.additionInformation?.hangoutLink) {
return calEvent.additionInformation.hangoutLink;
}
return providerName || calEvent.location || "";
};
export const getManageLink = (calEvent: CalendarEvent) => {
return `
${calEvent.organizer.language.translate("need_to_reschedule_or_cancel")}
${getCancelLink(calEvent)}
`;
};
export const getUid = (calEvent: CalendarEvent): string => {
return calEvent.uid ?? translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
};
export const getCancelLink = (calEvent: CalendarEvent): string => {
return BASE_URL + "/cancel/" + getUid(calEvent);
};
export const getRichDescription = (calEvent: CalendarEvent, attendee?: Person) => {
// Only the original attendee can make changes to the event
// Guests cannot
if (attendee && attendee === calEvent.attendees[0]) {
return `
${getWhat(calEvent)}
${getWhen(calEvent)}
${getWho(calEvent)}
${calEvent.organizer.language.translate("where")}:
${getLocation(calEvent)}
${getAdditionalNotes(calEvent)}
`.trim();
}
return `
${getWhat(calEvent)}
${getWhen(calEvent)}
${getWho(calEvent)}
${calEvent.organizer.language.translate("where")}:
${getLocation(calEvent)}
${getAdditionalNotes(calEvent)}
${getManageLink(calEvent)}
`.trim();
};
+2 -6
View File
@@ -1,6 +1,2 @@
export const BASE_URL = process.env.BASE_URL || `https://${process.env.VERCEL_URL}`;
export const WEBSITE_URL = process.env.NEXT_PUBLIC_APP_URL || "https://cal.com";
export const IS_PRODUCTION = process.env.NODE_ENV === "production";
export const TRIAL_LIMIT_DAYS = 14;
export const HOSTED_CAL_FEATURES = process.env.HOSTED_CAL_FEATURES || BASE_URL === "https://app.cal.com";
export const NEXT_PUBLIC_BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || `https://${process.env.VERCEL_URL}`;
// TODO: Remove this file once everything is imported from `@calcom/lib`
export * from "@calcom/lib/constants";
-42
View File
@@ -1,42 +0,0 @@
import crypto from "crypto";
const ALGORITHM = "aes256";
const INPUT_ENCODING = "utf8";
const OUTPUT_ENCODING = "hex";
const IV_LENGTH = 16; // AES blocksize
/**
*
* @param text Value to be encrypted
* @param key Key used to encrypt value must be 32 bytes for AES256 encryption algorithm
*
* @returns Encrypted value using key
*/
export const symmetricEncrypt = function (text: string, key: string) {
const _key = Buffer.from(key, "latin1");
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, _key, iv);
let ciphered = cipher.update(text, INPUT_ENCODING, OUTPUT_ENCODING);
ciphered += cipher.final(OUTPUT_ENCODING);
const ciphertext = iv.toString(OUTPUT_ENCODING) + ":" + ciphered;
return ciphertext;
};
/**
*
* @param text Value to decrypt
* @param key Key used to decrypt value must be 32 bytes for AES256 encryption algorithm
*/
export const symmetricDecrypt = function (text: string, key: string) {
const _key = Buffer.from(key, "latin1");
const components = text.split(":");
const iv_from_ciphertext = Buffer.from(components.shift() || "", OUTPUT_ENCODING);
const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext);
let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING);
deciphered += decipher.final(INPUT_ENCODING);
return deciphered;
};
+2 -1
View File
@@ -1,3 +1,5 @@
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
import AttendeeAwaitingPaymentEmail from "@lib/emails/templates/attendee-awaiting-payment-email";
import AttendeeCancelledEmail from "@lib/emails/templates/attendee-cancelled-email";
import AttendeeDeclinedEmail from "@lib/emails/templates/attendee-declined-email";
@@ -12,7 +14,6 @@ import OrganizerRequestReminderEmail from "@lib/emails/templates/organizer-reque
import OrganizerRescheduledEmail from "@lib/emails/templates/organizer-rescheduled-email";
import OrganizerScheduledEmail from "@lib/emails/templates/organizer-scheduled-email";
import TeamInviteEmail, { TeamInvite } from "@lib/emails/templates/team-invite-email";
import { CalendarEvent, Person } from "@lib/integrations/calendar/interfaces/Calendar";
export const sendScheduledEmails = async (calEvent: CalendarEvent) => {
const emailsToSend: Promise<unknown>[] = [];
@@ -4,7 +4,7 @@ import timezone from "dayjs/plugin/timezone";
import toArray from "dayjs/plugin/toArray";
import utc from "dayjs/plugin/utc";
import { getCancelLink } from "@lib/CalEventParser";
import { getCancelLink } from "@calcom/lib/CalEventParser";
import AttendeeScheduledEmail from "./attendee-scheduled-email";
import {
@@ -6,11 +6,11 @@ import utc from "dayjs/plugin/utc";
import { createEvent, DateArray } from "ics";
import nodemailer from "nodemailer";
import { getAppName } from "@calcom/app-store/utils";
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import type { Person, CalendarEvent } from "@calcom/types/Calendar";
import { getCancelLink, getRichDescription } from "@lib/CalEventParser";
import { getIntegrationName } from "@lib/integrations";
import { CalendarEvent, Person } from "@lib/integrations/calendar/interfaces/Calendar";
import { serverConfig } from "@lib/serverConfig";
import {
@@ -309,7 +309,7 @@ ${getRichDescription(this.calEvent)}
}
protected getLocation(): string {
let providerName = this.calEvent.location ? getIntegrationName(this.calEvent.location) : "";
let providerName = this.calEvent.location ? getAppName(this.calEvent.location) : "";
if (this.calEvent.location && this.calEvent.location.includes("integrations:")) {
const location = this.calEvent.location.split(":")[1];
@@ -4,7 +4,7 @@ import timezone from "dayjs/plugin/timezone";
import toArray from "dayjs/plugin/toArray";
import utc from "dayjs/plugin/utc";
import { getCancelLink } from "@lib/CalEventParser";
import { getCancelLink } from "@calcom/lib/CalEventParser";
import {
emailHead,
@@ -6,11 +6,11 @@ import utc from "dayjs/plugin/utc";
import { createEvent, DateArray, Person } from "ics";
import nodemailer from "nodemailer";
import { getAppName } from "@calcom/app-store/utils";
import { getCancelLink, getRichDescription } from "@calcom/lib/CalEventParser";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import type { CalendarEvent } from "@calcom/types/Calendar";
import { getCancelLink, getRichDescription } from "@lib/CalEventParser";
import { getIntegrationName } from "@lib/integrations";
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
import { serverConfig } from "@lib/serverConfig";
import {
@@ -300,7 +300,7 @@ ${getRichDescription(this.calEvent)}
}
protected getLocation(): string {
let providerName = this.calEvent.location ? getIntegrationName(this.calEvent.location) : "";
let providerName = this.calEvent.location ? getAppName(this.calEvent.location) : "";
if (this.calEvent.location && this.calEvent.location.includes("integrations:")) {
const location = this.calEvent.location.split(":")[1];
-364
View File
@@ -1,364 +0,0 @@
import { Credential, DestinationCalendar } from "@prisma/client";
import async from "async";
import merge from "lodash/merge";
import { v5 as uuidv5 } from "uuid";
import { FAKE_DAILY_CREDENTIAL } from "@lib/integrations/Daily/DailyVideoApiAdapter";
import { FAKE_HUDDLE_CREDENTIAL } from "@lib/integrations/Huddle01/Huddle01VideoApiAdapter";
import { FAKE_JITSI_CREDENTIAL } from "@lib/integrations/Jitsi/JitsiVideoApiAdapter";
import { createEvent, updateEvent } from "@lib/integrations/calendar/CalendarManager";
import { AdditionInformation, CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
import { LocationType } from "@lib/location";
import prisma from "@lib/prisma";
import { createMeeting, updateMeeting, VideoCallData } from "@lib/videoClient";
export type Event = AdditionInformation & VideoCallData;
export interface EventResult {
type: string;
success: boolean;
uid: string;
createdEvent?: Event;
updatedEvent?: Event | Event[];
originalEvent: CalendarEvent;
}
export interface CreateUpdateResult {
results: Array<EventResult>;
referencesToCreate: Array<PartialReference>;
}
export interface PartialBooking {
id: number;
references: Array<PartialReference>;
}
export interface PartialReference {
id?: number;
type: string;
uid: string;
meetingId?: string | null;
meetingPassword?: string | null;
meetingUrl?: string | null;
}
export const isZoom = (location: string): boolean => {
return location === "integrations:zoom";
};
export const isDaily = (location: string): boolean => {
return location === "integrations:daily";
};
export const isHuddle01 = (location: string): boolean => {
return location === "integrations:huddle01";
};
export const isTandem = (location: string): boolean => {
return location === "integrations:tandem";
};
export const isJitsi = (location: string): boolean => {
return location === "integrations:jitsi";
};
export const isDedicatedIntegration = (location: string): boolean => {
return (
isZoom(location) || isDaily(location) || isHuddle01(location) || isTandem(location) || isJitsi(location)
);
};
export const getLocationRequestFromIntegration = (location: string) => {
if (
location === LocationType.GoogleMeet.valueOf() ||
location === LocationType.Zoom.valueOf() ||
location === LocationType.Daily.valueOf() ||
location === LocationType.Jitsi.valueOf() ||
location === LocationType.Huddle01.valueOf() ||
location === LocationType.Tandem.valueOf()
) {
const requestId = uuidv5(location, uuidv5.URL);
return {
conferenceData: {
createRequest: {
requestId: requestId,
},
},
location,
};
}
return null;
};
export const processLocation = (event: CalendarEvent): CalendarEvent => {
// If location is set to an integration location
// Build proper transforms for evt object
// Extend evt object with those transformations
if (event.location?.includes("integration")) {
const maybeLocationRequestObject = getLocationRequestFromIntegration(event.location);
event = merge(event, maybeLocationRequestObject);
}
return event;
};
type EventManagerUser = {
credentials: Credential[];
destinationCalendar: DestinationCalendar | null;
};
export default class EventManager {
calendarCredentials: Credential[];
videoCredentials: Credential[];
/**
* Takes an array of credentials and initializes a new instance of the EventManager.
*
* @param credentials
*/
constructor(user: EventManagerUser) {
this.calendarCredentials = user.credentials.filter((cred) => cred.type.endsWith("_calendar"));
this.videoCredentials = user.credentials.filter((cred) => cred.type.endsWith("_video"));
//for Daily.co video, temporarily pushes a credential for the daily-video-client
const hasDailyIntegration = process.env.DAILY_API_KEY;
if (hasDailyIntegration) {
this.videoCredentials.push(FAKE_DAILY_CREDENTIAL);
}
this.videoCredentials.push(FAKE_HUDDLE_CREDENTIAL);
this.videoCredentials.push(FAKE_JITSI_CREDENTIAL);
}
/**
* Takes a CalendarEvent and creates all necessary integration entries for it.
* When a video integration is chosen as the event's location, a video integration
* event will be scheduled for it as well.
*
* @param event
*/
public async create(event: CalendarEvent): Promise<CreateUpdateResult> {
const evt = processLocation(event);
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
const results: Array<EventResult> = [];
// If and only if event type is a dedicated meeting, create a dedicated video meeting.
if (isDedicated) {
const result = await this.createVideoEvent(evt);
if (result.createdEvent) {
evt.videoCallData = result.createdEvent;
}
results.push(result);
}
// Create the calendar event with the proper video call data
results.push(...(await this.createAllCalendarEvents(evt)));
const referencesToCreate: Array<PartialReference> = results.map((result: EventResult) => {
return {
type: result.type,
uid: result.createdEvent?.id.toString() ?? "",
meetingId: result.createdEvent?.id.toString(),
meetingPassword: result.createdEvent?.password,
meetingUrl: result.createdEvent?.url,
};
});
return {
results,
referencesToCreate,
};
}
/**
* Takes a calendarEvent and a rescheduleUid and updates the event that has the
* given uid using the data delivered in the given CalendarEvent.
*
* @param event
*/
public async update(event: CalendarEvent, rescheduleUid: string): Promise<CreateUpdateResult> {
const evt = processLocation(event);
if (!rescheduleUid) {
throw new Error("You called eventManager.update without an `rescheduleUid`. This should never happen.");
}
// Get details of existing booking.
const booking = await prisma.booking.findFirst({
where: {
uid: rescheduleUid,
},
select: {
id: true,
references: {
select: {
id: true,
type: true,
uid: true,
meetingId: true,
meetingPassword: true,
meetingUrl: true,
},
},
destinationCalendar: true,
},
});
if (!booking) {
throw new Error("booking not found");
}
const isDedicated = evt.location ? isDedicatedIntegration(evt.location) : null;
const results: Array<EventResult> = [];
// If and only if event type is a dedicated meeting, update the dedicated video meeting.
if (isDedicated) {
const result = await this.updateVideoEvent(evt, booking);
const [updatedEvent] = Array.isArray(result.updatedEvent) ? result.updatedEvent : [result.updatedEvent];
if (updatedEvent) {
evt.videoCallData = updatedEvent;
evt.location = updatedEvent.url;
}
results.push(result);
}
// Update all calendar events.
results.push(...(await this.updateAllCalendarEvents(evt, booking)));
// Now we can delete the old booking and its references.
const bookingReferenceDeletes = prisma.bookingReference.deleteMany({
where: {
bookingId: booking.id,
},
});
const attendeeDeletes = prisma.attendee.deleteMany({
where: {
bookingId: booking.id,
},
});
const bookingDeletes = prisma.booking.delete({
where: {
id: booking.id,
},
});
// Wait for all deletions to be applied.
await Promise.all([bookingReferenceDeletes, attendeeDeletes, bookingDeletes]);
return {
results,
referencesToCreate: [...booking.references],
};
}
/**
* Creates event entries for all calendar integrations given in the credentials.
* When noMail is true, no mails will be sent. This is used when the event is
* a video meeting because then the mail containing the video credentials will be
* more important than the mails created for these bare calendar events.
*
* When the optional uid is set, it will be used instead of the auto generated uid.
*
* @param event
* @param noMail
* @private
*/
private async createAllCalendarEvents(event: CalendarEvent): Promise<Array<EventResult>> {
/** Can I use destinationCalendar here? */
/* How can I link a DC to a cred? */
if (event.destinationCalendar) {
const destinationCalendarCredentials = this.calendarCredentials.filter(
(c) => c.type === event.destinationCalendar?.integration
);
return Promise.all(destinationCalendarCredentials.map(async (c) => await createEvent(c, event)));
}
/**
* Not ideal but, if we don't find a destination calendar,
* fallback to the first connected calendar
*/
const [credential] = this.calendarCredentials;
if (!credential) {
return [];
}
return [await createEvent(credential, event)];
}
/**
* Checks which video integration is needed for the event's location and returns
* credentials for that - if existing.
* @param event
* @private
*/
private getVideoCredential(event: CalendarEvent): Credential | undefined {
if (!event.location) {
return undefined;
}
const integrationName = event.location.replace("integrations:", "");
return this.videoCredentials.find((credential: Credential) => credential.type.includes(integrationName));
}
/**
* Creates a video event entry for the selected integration location.
*
* When optional uid is set, it will be used instead of the auto generated uid.
*
* @param event
* @private
*/
private createVideoEvent(event: CalendarEvent): Promise<EventResult> {
const credential = this.getVideoCredential(event);
if (credential) {
return createMeeting(credential, event);
} else {
return Promise.reject("No suitable credentials given for the requested integration name.");
}
}
/**
* Updates the event entries for all calendar integrations given in the credentials.
* When noMail is true, no mails will be sent. This is used when the event is
* a video meeting because then the mail containing the video credentials will be
* more important than the mails created for these bare calendar events.
*
* @param event
* @param booking
* @private
*/
private updateAllCalendarEvents(
event: CalendarEvent,
booking: PartialBooking
): Promise<Array<EventResult>> {
return async.mapLimit(this.calendarCredentials, 5, async (credential: Credential) => {
const bookingRefUid = booking
? booking.references.filter((ref) => ref.type === credential.type)[0]?.uid
: null;
return updateEvent(credential, event, bookingRefUid);
});
}
/**
* Updates a single video event.
*
* @param event
* @param booking
* @private
*/
private updateVideoEvent(event: CalendarEvent, booking: PartialBooking) {
const credential = this.getVideoCredential(event);
if (credential) {
const bookingRef = booking ? booking.references.filter((ref) => ref.type === credential.type)[0] : null;
return updateMeeting(credential, event, bookingRef);
} else {
return Promise.reject("No suitable credentials given for the requested integration name.");
}
}
}
+19
View File
@@ -0,0 +1,19 @@
import { useState, useEffect } from "react";
const useMediaQuery = (query: string) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
window.addEventListener("resize", listener);
return () => window.removeEventListener("resize", listener);
}, [matches, query]);
return matches;
};
export default useMediaQuery;
-34
View File
@@ -1,34 +0,0 @@
export function getIntegrationName(name: string) {
switch (name) {
case "google_calendar":
return "Google Calendar";
case "office365_calendar":
return "Office 365 Calendar";
case "zoom_video":
return "Zoom";
case "caldav_calendar":
return "CalDav Server";
case "stripe_payment":
return "Stripe";
case "apple_calendar":
return "Apple Calendar";
case "daily_video":
return "Daily";
case "jitsi_video":
return "Jitsi Meet";
case "huddle01_video":
return "Huddle01";
case "tandem_video":
return "Tandem";
}
}
export function getIntegrationType(name: string): string {
if (name.endsWith("_calendar")) {
return "Calendar";
}
if (name.endsWith("_payment")) {
return "Payment";
}
return "Unknown";
}
@@ -1,159 +0,0 @@
import { Credential } from "@prisma/client";
import { handleErrorsJson } from "@calcom/lib/errors";
import { BASE_URL } from "@lib/config/constants";
import { PartialReference } from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
import { CalendarEvent } from "../calendar/interfaces/Calendar";
export interface DailyReturnType {
/** Long UID string ie: 987b5eb5-d116-4a4e-8e2c-14fcb5710966 */
id: string;
/** Not a real name, just a random generated string ie: "ePR84NQ1bPigp79dDezz" */
name: string;
api_created: boolean;
privacy: "private" | "public";
/** https://api-demo.daily.co/ePR84NQ1bPigp79dDezz */
url: string;
created_at: string;
config: {
nbf: number;
exp: number;
enable_chat: boolean;
enable_knocking: boolean;
enable_prejoin_ui: boolean;
enable_new_call_ui: boolean;
};
}
export interface DailyEventResult {
id: string;
name: string;
api_created: boolean;
privacy: string;
url: string;
created_at: string;
config: Record<string, unknown>;
}
export interface DailyVideoCallData {
type: string;
id: string;
password: string;
url: string;
}
type DailyKey = {
apikey: string;
};
export const FAKE_DAILY_CREDENTIAL: Credential = {
id: +new Date().getTime(),
type: "daily_video",
key: { apikey: process.env.DAILY_API_KEY },
userId: +new Date().getTime(),
};
const DailyVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
const dailyApiToken = (credential.key as DailyKey).apikey;
function postToDailyAPI(endpoint: string, body: Record<string, any>) {
return fetch("https://api.daily.co/v1" + endpoint, {
method: "POST",
headers: {
Authorization: "Bearer " + dailyApiToken,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
}
async function createOrUpdateMeeting(endpoint: string, event: CalendarEvent): Promise<VideoCallData> {
if (!event.uid) {
throw new Error("We need need the booking uid to create the Daily reference in DB");
}
const response = await postToDailyAPI(endpoint, translateEvent(event));
const dailyEvent: DailyReturnType = await handleErrorsJson(response);
const res = await postToDailyAPI("/meeting-tokens", {
properties: { room_name: dailyEvent.name, is_owner: true },
});
const meetingToken: { token: string } = await handleErrorsJson(res);
await prisma.dailyEventReference.create({
data: {
dailyurl: dailyEvent.url,
dailytoken: meetingToken.token,
booking: {
connect: {
uid: event.uid,
},
},
},
});
return Promise.resolve({
type: "daily_video",
id: dailyEvent.name,
password: "",
url: BASE_URL + "/video/" + event.uid,
});
}
const translateEvent = (event: CalendarEvent) => {
// Documentation at: https://docs.daily.co/reference#list-rooms
// added a 1 hour buffer for room expiration
const exp = Math.round(new Date(event.endTime).getTime() / 1000) + 60 * 60;
const scalePlan = process.env.DAILY_SCALE_PLAN;
if (scalePlan === "true") {
return {
privacy: "public",
properties: {
enable_new_call_ui: true,
enable_prejoin_ui: true,
enable_knocking: true,
enable_screenshare: true,
enable_chat: true,
exp: exp,
enable_recording: "local",
},
};
}
return {
privacy: "public",
properties: {
enable_new_call_ui: true,
enable_prejoin_ui: true,
enable_knocking: true,
enable_screenshare: true,
enable_chat: true,
exp: exp,
},
};
};
return {
/** Daily doesn't need to return busy times, so we return empty */
getAvailability: () => {
return Promise.resolve([]);
},
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> =>
createOrUpdateMeeting("/rooms", event),
deleteMeeting: async (uid: string): Promise<void> => {
await fetch("https://api.daily.co/v1/rooms/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + dailyApiToken,
},
}).then(handleErrorsJson);
return Promise.resolve();
},
updateMeeting: (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> =>
createOrUpdateMeeting("/rooms/" + bookingRef.uid, event),
};
};
export default DailyVideoApiAdapter;
@@ -1,49 +0,0 @@
import { Credential } from "@prisma/client";
import { handleErrorsJson } from "@calcom/lib/errors";
import { PartialReference } from "@lib/events/EventManager";
import { randomString } from "@lib/random";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
export const FAKE_HUDDLE_CREDENTIAL: Credential = {
id: +new Date().getTime(),
type: "huddle01_video",
key: { apikey: randomString(12) },
userId: +new Date().getTime(),
};
const Huddle01VideoApiAdapter = (): VideoApiAdapter => {
return {
getAvailability: () => {
return Promise.resolve([]);
},
createMeeting: async (): Promise<VideoCallData> => {
const res = await fetch(
"https://wpss2zlpb9.execute-api.us-east-1.amazonaws.com/new-meeting?utmCampaign=cal.com&utmSource=partner&utmMedium=calendar"
);
const { url } = await handleErrorsJson(res);
return Promise.resolve({
type: "huddle01_video",
id: randomString(21),
password: "",
url,
});
},
deleteMeeting: async (): Promise<void> => {
Promise.resolve();
},
updateMeeting: (bookingRef: PartialReference): Promise<VideoCallData> => {
return Promise.resolve({
type: "huddle01_video",
id: bookingRef.meetingId as string,
password: bookingRef.meetingPassword as string,
url: bookingRef.meetingUrl as string,
});
},
};
};
export default Huddle01VideoApiAdapter;
@@ -1,43 +0,0 @@
import { Credential } from "@prisma/client";
import { v4 as uuidv4 } from "uuid";
import { PartialReference } from "@lib/events/EventManager";
import { randomString } from "@lib/random";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
export const FAKE_JITSI_CREDENTIAL: Credential = {
id: +new Date().getTime(),
type: "jitsi_video",
key: { apikey: randomString(12) },
userId: +new Date().getTime(),
};
const JitsiVideoApiAdapter = (): VideoApiAdapter => {
return {
getAvailability: () => {
return Promise.resolve([]);
},
createMeeting: async (): Promise<VideoCallData> => {
const meetingID = uuidv4();
return Promise.resolve({
type: "jitsi_video",
id: meetingID,
password: "",
url: "https://meet.jit.si/cal/" + meetingID,
});
},
deleteMeeting: async (): Promise<void> => {
Promise.resolve();
},
updateMeeting: (bookingRef: PartialReference): Promise<VideoCallData> => {
return Promise.resolve({
type: "jitsi_video",
id: bookingRef.meetingId as string,
password: bookingRef.meetingPassword as string,
url: bookingRef.meetingUrl as string,
});
},
};
};
export default JitsiVideoApiAdapter;
@@ -1,144 +0,0 @@
import { Credential } from "@prisma/client";
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
import { PartialReference } from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
import { CalendarEvent } from "../calendar/interfaces/Calendar";
interface TandemToken {
expires_in?: number;
expiry_date: number;
refresh_token: string;
token_type: "Bearer";
access_token: string;
}
const client_id = process.env.TANDEM_CLIENT_ID as string;
const client_secret = process.env.TANDEM_CLIENT_SECRET as string;
const TANDEM_BASE_URL = process.env.TANDEM_BASE_URL as string;
const tandemAuth = (credential: Credential) => {
const credentialKey = credential.key as unknown as TandemToken;
const isTokenValid = (token: TandemToken) => token && token.access_token && token.expiry_date < Date.now();
const refreshAccessToken = (refreshToken: string) => {
fetch(`${TANDEM_BASE_URL}/api/v1/oauth/v2/token`, {
method: "POST",
body: new URLSearchParams({
client_id,
client_secret,
code: refreshToken,
}),
})
.then(handleErrorsJson)
.then(async (responseBody) => {
// set expiry date as offset from current time.
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
// Store new tokens in database.
await prisma.credential.update({
where: {
id: credential.id,
},
data: {
key: responseBody,
},
});
credentialKey.expiry_date = responseBody.expiry_date;
credentialKey.access_token = responseBody.access_token;
credentialKey.refresh_token = responseBody.refresh_token;
return credentialKey.access_token;
});
};
return {
getToken: () =>
!isTokenValid(credentialKey)
? Promise.resolve(credentialKey.access_token)
: refreshAccessToken(credentialKey.refresh_token),
};
};
const TandemVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
const auth = tandemAuth(credential);
const _parseDate = (date: string) => {
return Date.parse(date) / 1000;
};
const _translateEvent = (event: CalendarEvent, param: string): string => {
return JSON.stringify({
[param]: {
title: event.title,
starts_at: _parseDate(event.startTime),
ends_at: _parseDate(event.endTime),
description: event.description || "",
conference_solution: "tandem",
type: 3,
},
});
};
const _translateResult = (result: { data: { id: string; event_link: string } }) => {
return {
type: "tandem_video",
id: result.data.id as string,
password: "",
url: result.data.event_link,
};
};
return {
/** Tandem doesn't need to return busy times, so we return empty */
getAvailability: () => {
return Promise.resolve([]);
},
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
const result = await fetch(`${TANDEM_BASE_URL}/api/v1/meetings`, {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: _translateEvent(event, "meeting"),
}).then(handleErrorsJson);
return Promise.resolve(_translateResult(result));
},
deleteMeeting: async (uid: string): Promise<void> => {
const accessToken = await auth.getToken();
await fetch(`${TANDEM_BASE_URL}/api/v1/meetings/${uid}`, {
method: "DELETE",
headers: {
Authorization: "Bearer " + accessToken,
},
}).then(handleErrorsRaw);
return Promise.resolve();
},
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
const result = await fetch(`${TANDEM_BASE_URL}/api/v1/meetings/${bookingRef.meetingId}`, {
method: "PUT",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: _translateEvent(event, "updates"),
}).then(handleErrorsJson);
return Promise.resolve(_translateResult(result));
},
};
};
export default TandemVideoApiAdapter;
@@ -1,233 +0,0 @@
import { Credential } from "@prisma/client";
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
import { PartialReference } from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import { VideoApiAdapter, VideoCallData } from "@lib/videoClient";
import { CalendarEvent } from "../calendar/interfaces/Calendar";
/** @link https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate */
export interface ZoomEventResult {
password: string;
created_at: string;
duration: number;
host_id: string;
id: number;
join_url: string;
settings: {
alternative_hosts: string;
approval_type: number;
audio: string;
auto_recording: string;
close_registration: boolean;
cn_meeting: boolean;
enforce_login: boolean;
enforce_login_domains: string;
global_dial_in_countries: string[];
global_dial_in_numbers: {
city: string;
country: string;
country_name: string;
number: string;
type: string;
}[];
breakout_room: {
enable: boolean;
rooms: {
name: string;
participants: string[];
}[];
host_video: boolean;
in_meeting: boolean;
join_before_host: boolean;
mute_upon_entry: boolean;
participant_video: boolean;
registrants_confirmation_email: boolean;
use_pmi: boolean;
waiting_room: boolean;
watermark: boolean;
registrants_email_notification: boolean;
};
start_time: string;
start_url: string;
status: string;
timezone: string;
topic: string;
type: number;
uuid: string;
};
}
interface ZoomToken {
scope: "meeting:write";
expiry_date: number;
expires_in?: number; // deprecated, purely for backwards compatibility; superseeded by expiry_date.
token_type: "bearer";
access_token: string;
refresh_token: string;
}
const zoomAuth = (credential: Credential) => {
const credentialKey = credential.key as unknown as ZoomToken;
const isTokenValid = (token: ZoomToken) =>
token && token.token_type && token.access_token && (token.expires_in || token.expiry_date) < Date.now();
const authHeader =
"Basic " +
Buffer.from(process.env.ZOOM_CLIENT_ID + ":" + process.env.ZOOM_CLIENT_SECRET).toString("base64");
const refreshAccessToken = (refreshToken: string) =>
fetch("https://zoom.us/oauth/token", {
method: "POST",
headers: {
Authorization: authHeader,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
refresh_token: refreshToken,
grant_type: "refresh_token",
}),
})
.then(handleErrorsJson)
.then(async (responseBody) => {
// set expiry date as offset from current time.
responseBody.expiry_date = Math.round(Date.now() + responseBody.expires_in * 1000);
delete responseBody.expires_in;
// Store new tokens in database.
await prisma.credential.update({
where: {
id: credential.id,
},
data: {
key: responseBody,
},
});
credentialKey.expiry_date = responseBody.expiry_date;
credentialKey.access_token = responseBody.access_token;
return credentialKey.access_token;
});
return {
getToken: () =>
!isTokenValid(credentialKey)
? Promise.resolve(credentialKey.access_token)
: refreshAccessToken(credentialKey.refresh_token),
};
};
const ZoomVideoApiAdapter = (credential: Credential): VideoApiAdapter => {
const auth = zoomAuth(credential);
const translateEvent = (event: CalendarEvent) => {
// Documentation at: https://marketplace.zoom.us/docs/api-reference/zoom-api/meetings/meetingcreate
return {
topic: event.title,
type: 2, // Means that this is a scheduled meeting
start_time: event.startTime,
duration: (new Date(event.endTime).getTime() - new Date(event.startTime).getTime()) / 60000,
//schedule_for: "string", TODO: Used when scheduling the meeting for someone else (needed?)
timezone: event.attendees[0].timeZone,
//password: "string", TODO: Should we use a password? Maybe generate a random one?
agenda: event.description,
settings: {
host_video: true,
participant_video: true,
cn_meeting: false, // TODO: true if host meeting in China
in_meeting: false, // TODO: true if host meeting in India
join_before_host: true,
mute_upon_entry: false,
watermark: false,
use_pmi: false,
approval_type: 2,
audio: "both",
auto_recording: "none",
enforce_login: false,
registrants_email_notification: true,
},
};
};
return {
getAvailability: () => {
return auth
.getToken()
.then(
// TODO Possibly implement pagination for cases when there are more than 300 meetings already scheduled.
(accessToken) =>
fetch("https://api.zoom.us/v2/users/me/meetings?type=scheduled&page_size=300", {
method: "get",
headers: {
Authorization: "Bearer " + accessToken,
},
})
.then(handleErrorsJson)
.then((responseBody) => {
return responseBody.meetings.map((meeting: { start_time: string; duration: number }) => ({
start: meeting.start_time,
end: new Date(
new Date(meeting.start_time).getTime() + meeting.duration * 60000
).toISOString(),
}));
})
)
.catch((err) => {
console.error(err);
/* Prevents booking failure when Zoom Token is expired */
return [];
});
},
createMeeting: async (event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
const result = await fetch("https://api.zoom.us/v2/users/me/meetings", {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsJson);
return Promise.resolve({
type: "zoom_video",
id: result.id as string,
password: result.password ?? "",
url: result.join_url,
});
},
deleteMeeting: async (uid: string): Promise<void> => {
const accessToken = await auth.getToken();
await fetch("https://api.zoom.us/v2/meetings/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + accessToken,
},
}).then(handleErrorsRaw);
return Promise.resolve();
},
updateMeeting: async (bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData> => {
const accessToken = await auth.getToken();
await fetch("https://api.zoom.us/v2/meetings/" + bookingRef.uid, {
method: "PATCH",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(translateEvent(event)),
}).then(handleErrorsRaw);
return Promise.resolve({
type: "zoom_video",
id: bookingRef.meetingId as string,
password: bookingRef.meetingPassword as string,
url: bookingRef.meetingUrl as string,
});
},
};
};
export default ZoomVideoApiAdapter;
@@ -1,181 +0,0 @@
import { Credential, SelectedCalendar } from "@prisma/client";
import _ from "lodash";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { getUid } from "@lib/CalEventParser";
import { EventResult } from "@lib/events/EventManager";
import logger from "@lib/logger";
import notEmpty from "@lib/notEmpty";
import { ALL_INTEGRATIONS } from "../getIntegrations";
import { CALENDAR_INTEGRATIONS_TYPES } from "./constants/generals";
import { CalendarServiceType, EventBusyDate } from "./constants/types";
import { Calendar, CalendarEvent } from "./interfaces/Calendar";
import AppleCalendarService from "./services/AppleCalendarService";
import CalDavCalendarService from "./services/CalDavCalendarService";
import GoogleCalendarService from "./services/GoogleCalendarService";
import Office365CalendarService from "./services/Office365CalendarService";
const CALENDARS: Record<string, CalendarServiceType> = {
[CALENDAR_INTEGRATIONS_TYPES.apple]: AppleCalendarService,
[CALENDAR_INTEGRATIONS_TYPES.caldav]: CalDavCalendarService,
[CALENDAR_INTEGRATIONS_TYPES.google]: GoogleCalendarService,
[CALENDAR_INTEGRATIONS_TYPES.office365]: Office365CalendarService,
};
const log = logger.getChildLogger({ prefix: ["CalendarManager"] });
export const getCalendar = (credential: Credential): Calendar | null => {
const { type: calendarType } = credential;
const calendar = CALENDARS[calendarType];
if (!calendar) {
log.warn(`calendar of type ${calendarType} does not implemented`);
return null;
}
return new calendar(credential);
};
export const getCalendarCredentials = (credentials: Array<Omit<Credential, "userId">>, userId: number) => {
const calendarCredentials = credentials
.filter((credential) => credential.type.endsWith("_calendar"))
.flatMap((credential) => {
const integration = ALL_INTEGRATIONS.find((integration) => integration.type === credential.type);
const calendar = getCalendar({
...credential,
userId,
});
return integration && calendar && integration.variant === "calendar"
? [{ integration, credential, calendar }]
: [];
});
return calendarCredentials;
};
export const getConnectedCalendars = async (
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
selectedCalendars: { externalId: string }[]
) => {
const connectedCalendars = await Promise.all(
calendarCredentials.map(async (item) => {
const { calendar, integration, credential } = item;
const credentialId = credential.id;
try {
const cals = await calendar.listCalendars();
const calendars = _(cals)
.map((cal) => ({
...cal,
primary: cal.primary || null,
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
}))
.sortBy(["primary"])
.value();
const primary = calendars.find((item) => item.primary) ?? calendars[0];
if (!primary) {
throw new Error("No primary calendar found");
}
return {
integration,
credentialId,
primary,
calendars,
};
} catch (_error) {
const error = getErrorFromUnknown(_error);
return {
integration,
credentialId,
error: {
message: error.message,
},
};
}
})
);
return connectedCalendars;
};
export const getBusyCalendarTimes = async (
withCredentials: Credential[],
dateFrom: string,
dateTo: string,
selectedCalendars: SelectedCalendar[]
) => {
const calendars = withCredentials
.filter((credential) => credential.type.endsWith("_calendar"))
.map((credential) => getCalendar(credential))
.filter(notEmpty);
let results: EventBusyDate[][] = [];
try {
results = await Promise.all(calendars.map((c) => c.getAvailability(dateFrom, dateTo, selectedCalendars)));
} catch (error) {
log.warn(error);
}
return results.reduce((acc, availability) => acc.concat(availability), []);
};
export const createEvent = async (credential: Credential, calEvent: CalendarEvent): Promise<EventResult> => {
const uid: string = getUid(calEvent);
const calendar = getCalendar(credential);
let success = true;
const creationResult = calendar
? await calendar.createEvent(calEvent).catch((e) => {
log.error("createEvent failed", e, calEvent);
success = false;
return undefined;
})
: undefined;
return {
type: credential.type,
success,
uid,
createdEvent: creationResult,
originalEvent: calEvent,
};
};
export const updateEvent = async (
credential: Credential,
calEvent: CalendarEvent,
bookingRefUid: string | null
): Promise<EventResult> => {
const uid = getUid(calEvent);
const calendar = getCalendar(credential);
let success = true;
const updatedResult =
calendar && bookingRefUid
? await calendar.updateEvent(bookingRefUid, calEvent).catch((e) => {
log.error("updateEvent failed", e, calEvent);
success = false;
return undefined;
})
: undefined;
return {
type: credential.type,
success,
uid,
updatedEvent: updatedResult,
originalEvent: calEvent,
};
};
export const deleteEvent = (credential: Credential, uid: string, event: CalendarEvent): Promise<unknown> => {
const calendar = getCalendar(credential);
if (calendar) {
return calendar.deleteEvent(uid, event);
}
return Promise.resolve({});
};
@@ -1,102 +0,0 @@
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { Alert } from "@calcom/ui/Alert";
import Button from "@calcom/ui/Button";
import {
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogProps,
} from "@calcom/ui/Dialog";
import { Form, TextField } from "@calcom/ui/form/fields";
export const ADD_APPLE_INTEGRATION_FORM_TITLE = "addAppleIntegration";
export function AddAppleIntegrationModal(props: DialogProps) {
const form = useForm({
defaultValues: {
username: "",
password: "",
},
});
const [errorMessage, setErrorMessage] = useState("");
return (
<Dialog {...props}>
<DialogContent>
<DialogHeader
title="Connect to Apple Server"
subtitle={
<>
Generate an app specific password to use with Cal.com at{" "}
<a
className="text-indigo-400"
href="https://appleid.apple.com/account/manage"
target="_blank"
rel="noopener noreferrer">
https://appleid.apple.com/account/manage
</a>
. Your credentials will be stored and encrypted.
</>
}
/>
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/apple/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || "Something went wrong");
} else {
props.onOpenChange?.(false);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<TextField
required
type="text"
{...form.register("username")}
label="Username"
placeholder="rickroll"
/>
<TextField
required
type="password"
{...form.register("password")}
label="Password"
placeholder="•••••••••••••"
autoComplete="password"
/>
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<DialogFooter>
<DialogClose
onClick={() => {
props.onOpenChange?.(false);
}}
asChild>
<Button type="button" color="secondary" tabIndex={-1}>
Cancel
</Button>
</DialogClose>
<Button type="submit" loading={form.formState.isSubmitting}>
Save
</Button>
</DialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -1,168 +0,0 @@
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { Alert } from "@calcom/ui/Alert";
import Button from "@calcom/ui/Button";
import {
DialogHeader,
DialogProps,
Dialog,
DialogContent,
DialogClose,
DialogFooter,
} from "@calcom/ui/Dialog";
import { Form, TextField } from "@calcom/ui/form/fields";
type Props = {
onSubmit: () => void;
};
export const ADD_CALDAV_INTEGRATION_FORM_TITLE = "addCalDav";
export type AddCalDavIntegrationRequest = {
url: string;
username: string;
password: string;
};
export function AddCalDavIntegrationModal(props: DialogProps) {
const form = useForm({
defaultValues: {
url: "",
username: "",
password: "",
},
});
const [errorMessage, setErrorMessage] = useState("");
return (
<Dialog {...props}>
<DialogContent>
<DialogHeader
title="Connect to CalDav Server"
subtitle="Your credentials will be stored and encrypted."
/>
<Form
form={form}
handleSubmit={async (values) => {
setErrorMessage("");
const res = await fetch("/api/integrations/caldav/add", {
method: "POST",
body: JSON.stringify(values),
headers: {
"Content-Type": "application/json",
},
});
const json = await res.json();
if (!res.ok) {
setErrorMessage(json?.message || "Something went wrong");
} else {
props.onOpenChange?.(false);
}
}}>
<fieldset className="space-y-2" disabled={form.formState.isSubmitting}>
<TextField
required
type="text"
{...form.register("url")}
label="Calendar URL"
placeholder="https://example.com/calendar"
/>
<TextField
required
type="text"
{...form.register("username")}
label="Username"
placeholder="rickroll"
/>
<TextField
required
type="password"
{...form.register("password")}
label="Password"
placeholder="•••••••••••••"
autoComplete="password"
/>
</fieldset>
{errorMessage && <Alert severity="error" title={errorMessage} className="my-4" />}
<DialogFooter>
<DialogClose
onClick={() => {
props.onOpenChange?.(false);
}}
asChild>
<Button type="button" color="secondary" tabIndex={-1}>
Cancel
</Button>
</DialogClose>
<Button type="submit" loading={form.formState.isSubmitting}>
Save
</Button>
</DialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
/**
* @deprecated
*/
const AddCalDavIntegration = React.forwardRef<HTMLFormElement, Props>((props, ref) => {
const onSubmit = (event: any) => {
event.preventDefault();
event.stopPropagation();
props.onSubmit();
};
return (
<form id={ADD_CALDAV_INTEGRATION_FORM_TITLE} ref={ref} onSubmit={onSubmit}>
<div className="mb-2">
<label htmlFor="url" className="block text-sm font-medium text-gray-700">
Calendar URL
</label>
<div className="mt-1 flex rounded-md shadow-sm">
<input
required
type="text"
name="url"
id="url"
placeholder="https://example.com/calendar"
className="focus:border-brand block w-full min-w-0 flex-grow rounded-none rounded-r-sm border-gray-300 lowercase focus:ring-black sm:text-sm"
/>
</div>
</div>
<div className="mb-2">
<label htmlFor="username" className="block text-sm font-medium text-gray-700">
Username
</label>
<input
required
type="text"
name="username"
id="username"
placeholder="rickroll"
className="mt-1 block w-full rounded-sm border border-gray-300 px-3 py-2 shadow-sm focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
/>
</div>
<div className="mb-2">
<label htmlFor="password" className="block text-sm font-medium text-gray-700">
Password
</label>
<input
required
type="password"
name="password"
id="password"
placeholder="•••••••••••••"
className="mt-1 block w-full rounded-sm border border-gray-300 px-3 py-2 shadow-sm focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"
/>
</div>
</form>
);
});
AddCalDavIntegration.displayName = "AddCalDavIntegrationForm";
export default AddCalDavIntegration;
@@ -1 +0,0 @@
export const TIMEZONE_FORMAT = "YYYY-MM-DDTHH:mm:ss[Z]";
@@ -1,10 +0,0 @@
export const CALDAV_CALENDAR_TYPE = "caldav";
export const APPLE_CALENDAR_URL = "https://caldav.icloud.com";
export const CALENDAR_INTEGRATIONS_TYPES = {
apple: "apple_calendar",
caldav: "caldav_calendar",
google: "google_calendar",
office365: "office365_calendar",
};
@@ -1,57 +0,0 @@
import dayjs from "dayjs";
import ICAL from "ical.js";
import AppleCalendarService from "../services/AppleCalendarService";
import CalDavCalendarService from "../services/CalDavCalendarService";
import GoogleCalendarService from "../services/GoogleCalendarService";
import Office365CalendarService from "../services/Office365CalendarService";
export type EventBusyDate = Record<"start" | "end", Date | string>;
export type CalendarServiceType =
| typeof AppleCalendarService
| typeof CalDavCalendarService
| typeof GoogleCalendarService
| typeof Office365CalendarService;
export type NewCalendarEventType = {
uid: string;
id: string;
type: string;
password: string;
url: string;
additionalInfo: Record<string, any>;
};
export type CalendarEventType = {
uid: string;
etag: string;
/** This is the actual caldav event url, not the location url. */
url: string;
summary: string;
description: string;
location: string;
sequence: number;
startDate: Date | dayjs.Dayjs;
endDate: Date | dayjs.Dayjs;
duration: {
weeks: number;
days: number;
hours: number;
minutes: number;
seconds: number;
isNegative: boolean;
};
organizer: string;
attendees: any[][];
recurrenceId: ICAL.Time;
timezone: any;
};
export type BatchResponse = {
responses: SubResponse[];
};
export type SubResponse = {
body: { value: { start: { dateTime: string }; end: { dateTime: string } }[] };
};
@@ -1,81 +0,0 @@
import { DestinationCalendar, SelectedCalendar } from "@prisma/client";
import { TFunction } from "next-i18next";
import { PaymentInfo } from "@ee/lib/stripe/server";
import type { Event } from "@lib/events/EventManager";
import { Ensure } from "@lib/types/utils";
import { VideoCallData } from "@lib/videoClient";
import { NewCalendarEventType } from "../constants/types";
import { ConferenceData } from "./GoogleCalendar";
export type Person = {
name: string;
email: string;
timeZone: string;
language: { translate: TFunction; locale: string };
};
export interface EntryPoint {
entryPointType?: string;
uri?: string;
label?: string;
pin?: string;
accessCode?: string;
meetingCode?: string;
passcode?: string;
password?: string;
}
export interface AdditionInformation {
conferenceData?: ConferenceData;
entryPoints?: EntryPoint[];
hangoutLink?: string;
}
export interface CalendarEvent {
type: string;
title: string;
startTime: string;
endTime: string;
description?: string | null;
team?: {
name: string;
members: string[];
};
location?: string | null;
organizer: Person;
attendees: Person[];
conferenceData?: ConferenceData;
additionInformation?: AdditionInformation;
uid?: string | null;
videoCallData?: VideoCallData;
paymentInfo?: PaymentInfo | null;
destinationCalendar?: DestinationCalendar | null;
cancellationReason?: string | null;
rejectionReason?: string | null;
}
export interface IntegrationCalendar extends Ensure<Partial<SelectedCalendar>, "externalId"> {
primary?: boolean;
name?: string;
}
type EventBusyDate = Record<"start" | "end", Date | string>;
export interface Calendar {
createEvent(event: CalendarEvent): Promise<NewCalendarEventType>;
updateEvent(uid: string, event: CalendarEvent): Promise<Event | Event[]>;
deleteEvent(uid: string, event: CalendarEvent): Promise<unknown>;
getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]>;
listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]>;
}
@@ -1,5 +0,0 @@
import { calendar_v3 } from "googleapis";
export interface ConferenceData {
createRequest?: calendar_v3.Schema$CreateConferenceRequest;
}
@@ -1,10 +0,0 @@
export type BufferedBusyTime = {
start: string;
end: string;
};
export type O365AuthCredentials = {
expiry_date: number;
access_token: string;
refresh_token: string;
};
@@ -1,10 +0,0 @@
import { Credential } from "@prisma/client";
import { APPLE_CALENDAR_URL, CALENDAR_INTEGRATIONS_TYPES } from "../constants/generals";
import CalendarService from "./BaseCalendarService";
export default class AppleCalendarService extends CalendarService {
constructor(credential: Credential) {
super(credential, CALENDAR_INTEGRATIONS_TYPES.apple, APPLE_CALENDAR_URL);
}
}
@@ -1,369 +0,0 @@
import { Credential, Prisma } from "@prisma/client";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import ICAL from "ical.js";
import { createEvent } from "ics";
import {
createAccount,
createCalendarObject,
DAVAccount,
deleteCalendarObject,
fetchCalendarObjects,
fetchCalendars,
getBasicAuthHeaders,
updateCalendarObject,
} from "tsdav";
import { v4 as uuidv4 } from "uuid";
import { getLocation, getRichDescription } from "@lib/CalEventParser";
import { symmetricDecrypt } from "@lib/crypto";
import type { Event } from "@lib/events/EventManager";
import logger from "@lib/logger";
import { TIMEZONE_FORMAT } from "../constants/formats";
import { CALDAV_CALENDAR_TYPE } from "../constants/generals";
import { CalendarEventType, EventBusyDate, NewCalendarEventType } from "../constants/types";
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
import { convertDate, getAttendees, getDuration } from "../utils/CalendarUtils";
dayjs.extend(utc);
dayjs.extend(timezone);
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
export default abstract class BaseCalendarService implements Calendar {
private url = "";
private credentials: Record<string, string> = {};
private headers: Record<string, string> = {};
protected integrationName = "";
private log: typeof logger;
constructor(credential: Credential, integrationName: string, url?: string) {
this.integrationName = integrationName;
const {
username,
password,
url: credentialURL,
} = JSON.parse(symmetricDecrypt(credential.key as string, CALENDSO_ENCRYPTION_KEY));
this.url = url || credentialURL;
this.credentials = { username, password };
this.headers = getBasicAuthHeaders({ username, password });
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
}
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
try {
const calendars = await this.listCalendars(event);
const uid = uuidv4();
// We create local ICS files
const { error, value: iCalString } = createEvent({
uid,
startInputType: "utc",
start: convertDate(event.startTime),
duration: getDuration(event.startTime, event.endTime),
title: event.title,
description: getRichDescription(event),
location: getLocation(event),
organizer: { email: event.organizer.email, name: event.organizer.name },
/** according to https://datatracker.ietf.org/doc/html/rfc2446#section-3.2.1, in a published iCalendar component.
* "Attendees" MUST NOT be present
* `attendees: this.getAttendees(event.attendees),`
*/
});
if (error || !iCalString) throw new Error("Error creating iCalString");
// We create the event directly on iCal
const responses = await Promise.all(
calendars
.filter((c) =>
event.destinationCalendar?.externalId
? c.externalId === event.destinationCalendar.externalId
: true
)
.map((calendar) =>
createCalendarObject({
calendar: {
url: calendar.externalId,
},
filename: `${uid}.ics`,
// according to https://datatracker.ietf.org/doc/html/rfc4791#section-4.1, Calendar object resources contained in calendar collections MUST NOT specify the iCalendar METHOD property.
iCalString: iCalString.replace(/METHOD:[^\r\n]+\r\n/g, ""),
headers: this.headers,
})
)
);
if (responses.some((r) => !r.ok)) {
throw new Error(
`Error creating event: ${(await Promise.all(responses.map((r) => r.text()))).join(", ")}`
);
}
return {
uid,
id: uid,
type: this.integrationName,
password: "",
url: "",
additionalInfo: {},
};
} catch (reason) {
logger.error(reason);
throw reason;
}
}
async updateEvent(uid: string, event: CalendarEvent) {
try {
const events = await this.getEventsByUID(uid);
/** We generate the ICS files */
const { error, value: iCalString } = createEvent({
uid,
startInputType: "utc",
start: convertDate(event.startTime),
duration: getDuration(event.startTime, event.endTime),
title: event.title,
description: getRichDescription(event),
location: getLocation(event),
organizer: { email: event.organizer.email, name: event.organizer.name },
attendees: getAttendees(event.attendees),
});
if (error) {
this.log.debug("Error creating iCalString");
return {
type: event.type,
id: typeof event.uid === "string" ? event.uid : "-1",
password: "",
url: typeof event.location === "string" ? event.location : "-1",
};
}
const eventsToUpdate = events.filter((e) => e.uid === uid);
return Promise.all(
eventsToUpdate.map((e) => {
return updateCalendarObject({
calendarObject: {
url: e.url,
data: iCalString,
etag: e?.etag,
},
headers: this.headers,
});
})
).then((p) => p.map((r) => r.json() as unknown as Event));
} catch (reason) {
this.log.error(reason);
throw reason;
}
}
async deleteEvent(uid: string): Promise<void> {
try {
const events = await this.getEventsByUID(uid);
const eventsToDelete = events.filter((event) => event.uid === uid);
await Promise.all(
eventsToDelete.map((event) => {
return deleteCalendarObject({
calendarObject: {
url: event.url,
etag: event?.etag,
},
headers: this.headers,
});
})
);
} catch (reason) {
this.log.error(reason);
throw reason;
}
}
async getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]> {
const objects = (
await Promise.all(
selectedCalendars
.filter((sc) => ["caldav_calendar", "apple_calendar"].includes(sc.integration ?? ""))
.map((sc) =>
fetchCalendarObjects({
calendar: {
url: sc.externalId,
},
headers: this.headers,
expand: true,
timeRange: {
start: new Date(dateFrom).toISOString(),
end: new Date(dateTo).toISOString(),
},
})
)
)
).flat();
const events = objects
.filter((e) => !!e.data)
.map((object) => {
const jcalData = ICAL.parse(object.data);
const vcalendar = new ICAL.Component(jcalData);
const vevent = vcalendar.getFirstSubcomponent("vevent");
const event = new ICAL.Event(vevent);
return {
start: event.startDate.toJSDate().toISOString(),
end: event.endDate.toJSDate().toISOString(),
};
});
return Promise.resolve(events);
}
async listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]> {
try {
const account = await this.getAccount();
const calendars = await fetchCalendars({
account,
headers: this.headers,
});
return calendars.reduce<IntegrationCalendar[]>((newCalendars, calendar) => {
if (!calendar.components?.includes("VEVENT")) return newCalendars;
newCalendars.push({
externalId: calendar.url,
name: calendar.displayName ?? "",
primary: event?.destinationCalendar?.externalId
? event.destinationCalendar.externalId === calendar.url
: false,
integration: this.integrationName,
});
return newCalendars;
}, []);
} catch (reason) {
logger.error(reason);
throw reason;
}
}
private async getEvents(
calId: string,
dateFrom: string | null,
dateTo: string | null,
objectUrls?: string[] | null
) {
try {
const objects = await fetchCalendarObjects({
calendar: {
url: calId,
},
objectUrls: objectUrls ? objectUrls : undefined,
timeRange:
dateFrom && dateTo
? {
start: dayjs(dateFrom).utc().format(TIMEZONE_FORMAT),
end: dayjs(dateTo).utc().format(TIMEZONE_FORMAT),
}
: undefined,
headers: this.headers,
});
const events = objects
.filter((e) => !!e.data)
.map((object) => {
const jcalData = ICAL.parse(object.data);
const vcalendar = new ICAL.Component(jcalData);
const vevent = vcalendar.getFirstSubcomponent("vevent");
const event = new ICAL.Event(vevent);
const calendarTimezone =
vcalendar.getFirstSubcomponent("vtimezone")?.getFirstPropertyValue("tzid") || "";
const startDate = calendarTimezone
? dayjs.tz(event.startDate.toString(), calendarTimezone)
: new Date(event.startDate.toUnixTime() * 1000);
const endDate = calendarTimezone
? dayjs.tz(event.endDate.toString(), calendarTimezone)
: new Date(event.endDate.toUnixTime() * 1000);
return {
uid: event.uid,
etag: object.etag,
url: object.url,
summary: event.summary,
description: event.description,
location: event.location,
sequence: event.sequence,
startDate,
endDate,
duration: {
weeks: event.duration.weeks,
days: event.duration.days,
hours: event.duration.hours,
minutes: event.duration.minutes,
seconds: event.duration.seconds,
isNegative: event.duration.isNegative,
},
organizer: event.organizer,
attendees: event.attendees.map((a) => a.getValues()),
recurrenceId: event.recurrenceId,
timezone: calendarTimezone,
};
});
return events;
} catch (reason) {
console.error(reason);
throw reason;
}
}
private async getEventsByUID(uid: string): Promise<CalendarEventType[]> {
const events: Prisma.PromiseReturnType<typeof this.getEvents> = [];
const calendars = await this.listCalendars();
for (const cal of calendars) {
const calEvents = await this.getEvents(cal.externalId, null, null, [`${cal.externalId}${uid}.ics`]);
for (const ev of calEvents) {
events.push(ev);
}
}
return events;
}
private async getAccount(): Promise<DAVAccount> {
return createAccount({
account: {
serverUrl: this.url,
accountType: CALDAV_CALENDAR_TYPE,
credentials: this.credentials,
},
headers: this.headers,
});
}
}
@@ -1,10 +0,0 @@
import { Credential } from "@prisma/client";
import { CALENDAR_INTEGRATIONS_TYPES } from "../constants/generals";
import CalendarService from "./BaseCalendarService";
export default class CalDavCalendarService extends CalendarService {
constructor(credential: Credential) {
super(credential, CALENDAR_INTEGRATIONS_TYPES.caldav);
}
}
@@ -1,329 +0,0 @@
import { Credential, Prisma } from "@prisma/client";
import { GetTokenResponse } from "google-auth-library/build/src/auth/oauth2client";
import { Auth, calendar_v3, google } from "googleapis";
import { getLocation, getRichDescription } from "@lib/CalEventParser";
import { CALENDAR_INTEGRATIONS_TYPES } from "@lib/integrations/calendar/constants/generals";
import logger from "@lib/logger";
import prisma from "@lib/prisma";
import { EventBusyDate, NewCalendarEventType } from "../constants/types";
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
import CalendarService from "./BaseCalendarService";
const GOOGLE_API_CREDENTIALS = process.env.GOOGLE_API_CREDENTIALS || "";
export default class GoogleCalendarService implements Calendar {
private url = "";
private integrationName = "";
private auth: { getToken: () => Promise<MyGoogleAuth> };
private log: typeof logger;
constructor(credential: Credential) {
this.integrationName = CALENDAR_INTEGRATIONS_TYPES.google;
this.auth = this.googleAuth(credential);
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
}
private googleAuth = (credential: Credential) => {
const { client_secret, client_id, redirect_uris } = JSON.parse(GOOGLE_API_CREDENTIALS).web;
const myGoogleAuth = new MyGoogleAuth(client_id, client_secret, redirect_uris[0]);
const googleCredentials = credential.key as Auth.Credentials;
myGoogleAuth.setCredentials(googleCredentials);
const isExpired = () => myGoogleAuth.isTokenExpiring();
const refreshAccessToken = () =>
myGoogleAuth
.refreshToken(googleCredentials.refresh_token)
.then((res: GetTokenResponse) => {
const token = res.res?.data;
googleCredentials.access_token = token.access_token;
googleCredentials.expiry_date = token.expiry_date;
return prisma.credential
.update({
where: {
id: credential.id,
},
data: {
key: googleCredentials as Prisma.InputJsonValue,
},
})
.then(() => {
myGoogleAuth.setCredentials(googleCredentials);
return myGoogleAuth;
});
})
.catch((err) => {
this.log.error("Error refreshing google token", err);
return myGoogleAuth;
});
return {
getToken: () => (!isExpired() ? Promise.resolve(myGoogleAuth) : refreshAccessToken()),
};
};
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
return new Promise((resolve, reject) =>
this.auth.getToken().then((myGoogleAuth) => {
const payload: calendar_v3.Schema$Event = {
summary: event.title,
description: getRichDescription(event),
start: {
dateTime: event.startTime,
timeZone: event.organizer.timeZone,
},
end: {
dateTime: event.endTime,
timeZone: event.organizer.timeZone,
},
attendees: event.attendees.map((attendee) => ({
...attendee,
responseStatus: "accepted",
})),
reminders: {
useDefault: true,
},
};
if (event.location) {
payload["location"] = getLocation(event);
}
if (event.conferenceData && event.location === "integrations:google:meet") {
payload["conferenceData"] = event.conferenceData;
}
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.events.insert(
{
auth: myGoogleAuth,
calendarId: event.destinationCalendar?.externalId
? event.destinationCalendar.externalId
: "primary",
requestBody: payload,
conferenceDataVersion: 1,
},
function (err, event) {
if (err || !event?.data) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
return resolve({
uid: "",
...event.data,
id: event.data.id || "",
additionalInfo: {
hangoutLink: event.data.hangoutLink || "",
},
type: "google_calendar",
password: "",
url: "",
});
}
);
})
);
}
async updateEvent(uid: string, event: CalendarEvent): Promise<any> {
return new Promise((resolve, reject) =>
this.auth.getToken().then((myGoogleAuth) => {
const payload: calendar_v3.Schema$Event = {
summary: event.title,
description: getRichDescription(event),
start: {
dateTime: event.startTime,
timeZone: event.organizer.timeZone,
},
end: {
dateTime: event.endTime,
timeZone: event.organizer.timeZone,
},
attendees: event.attendees,
reminders: {
useDefault: true,
},
};
if (event.location) {
payload["location"] = getLocation(event);
}
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.events.update(
{
auth: myGoogleAuth,
calendarId: event.destinationCalendar?.externalId
? event.destinationCalendar.externalId
: "primary",
eventId: uid,
sendNotifications: true,
sendUpdates: "all",
requestBody: payload,
},
function (err, event) {
if (err) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
return resolve(event?.data);
}
);
})
);
}
async deleteEvent(uid: string, event: CalendarEvent): Promise<void> {
return new Promise((resolve, reject) =>
this.auth.getToken().then((myGoogleAuth) => {
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.events.delete(
{
auth: myGoogleAuth,
calendarId: event.destinationCalendar?.externalId
? event.destinationCalendar.externalId
: "primary",
eventId: uid,
sendNotifications: true,
sendUpdates: "all",
},
function (err, event) {
if (err) {
console.error("There was an error contacting google calendar service: ", err);
return reject(err);
}
return resolve(event?.data);
}
);
})
);
}
async getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]> {
return new Promise((resolve, reject) =>
this.auth.getToken().then((myGoogleAuth) => {
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
const selectedCalendarIds = selectedCalendars
.filter((e) => e.integration === this.integrationName)
.map((e) => e.externalId);
if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
// Only calendars of other integrations selected
resolve([]);
return;
}
(selectedCalendarIds.length === 0
? calendar.calendarList
.list()
.then((cals) => cals.data.items?.map((cal) => cal.id).filter(Boolean) || [])
: Promise.resolve(selectedCalendarIds)
)
.then((calsIds) => {
calendar.freebusy.query(
{
requestBody: {
timeMin: dateFrom,
timeMax: dateTo,
items: calsIds.map((id) => ({ id: id })),
},
},
(err, apires) => {
if (err) {
reject(err);
}
let result: Prisma.PromiseReturnType<CalendarService["getAvailability"]> = [];
if (apires?.data.calendars) {
result = Object.values(apires.data.calendars).reduce((c, i) => {
i.busy?.forEach((busyTime) => {
c.push({
start: busyTime.start || "",
end: busyTime.end || "",
});
});
return c;
}, [] as typeof result);
}
resolve(result);
}
);
})
.catch((err) => {
this.log.error("There was an error contacting google calendar service: ", err);
reject(err);
});
})
);
}
async listCalendars(): Promise<IntegrationCalendar[]> {
return new Promise((resolve, reject) =>
this.auth.getToken().then((myGoogleAuth) => {
const calendar = google.calendar({
version: "v3",
auth: myGoogleAuth,
});
calendar.calendarList
.list()
.then((cals) => {
resolve(
cals.data.items?.map((cal) => {
const calendar: IntegrationCalendar = {
externalId: cal.id ?? "No id",
integration: this.integrationName,
name: cal.summary ?? "No name",
primary: cal.primary ?? false,
};
return calendar;
}) || []
);
})
.catch((err: Error) => {
this.log.error("There was an error contacting google calendar service: ", err);
reject(err);
});
})
);
}
}
class MyGoogleAuth extends google.auth.OAuth2 {
constructor(client_id: string, client_secret: string, redirect_uri: string) {
super(client_id, client_secret, redirect_uri);
}
isTokenExpiring() {
return super.isTokenExpiring();
}
async refreshToken(token: string | null | undefined) {
return super.refreshToken(token);
}
}
@@ -1,252 +0,0 @@
import { Calendar as OfficeCalendar } from "@microsoft/microsoft-graph-types-beta";
import { Credential } from "@prisma/client";
import { handleErrorsJson, handleErrorsRaw } from "@calcom/lib/errors";
import { getLocation, getRichDescription } from "@lib/CalEventParser";
import { CALENDAR_INTEGRATIONS_TYPES } from "@lib/integrations/calendar/constants/generals";
import logger from "@lib/logger";
import prisma from "@lib/prisma";
import { BatchResponse, EventBusyDate, NewCalendarEventType } from "../constants/types";
import { Calendar, CalendarEvent, IntegrationCalendar } from "../interfaces/Calendar";
import { BufferedBusyTime, O365AuthCredentials } from "../interfaces/Office365Calendar";
const MS_GRAPH_CLIENT_ID = process.env.MS_GRAPH_CLIENT_ID || "";
const MS_GRAPH_CLIENT_SECRET = process.env.MS_GRAPH_CLIENT_SECRET || "";
export default class Office365CalendarService implements Calendar {
private url = "";
private integrationName = "";
private log: typeof logger;
auth: { getToken: () => Promise<string> };
constructor(credential: Credential) {
this.integrationName = CALENDAR_INTEGRATIONS_TYPES.office365;
this.auth = this.o365Auth(credential);
this.log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
}
async createEvent(event: CalendarEvent): Promise<NewCalendarEventType> {
try {
const accessToken = await this.auth.getToken();
const calendarId = event.destinationCalendar?.externalId
? `${event.destinationCalendar.externalId}/`
: "";
const response = await fetch(`https://graph.microsoft.com/v1.0/me/calendar/events`, {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(this.translateEvent(event)),
});
return handleErrorsJson(response);
} catch (error) {
this.log.error(error);
throw error;
}
}
async updateEvent(uid: string, event: CalendarEvent): Promise<any> {
try {
const accessToken = await this.auth.getToken();
const response = await fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
method: "PATCH",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify(this.translateEvent(event)),
});
return handleErrorsRaw(response);
} catch (error) {
this.log.error(error);
throw error;
}
}
async deleteEvent(uid: string): Promise<void> {
try {
const accessToken = await this.auth.getToken();
const response = await fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
method: "DELETE",
headers: {
Authorization: "Bearer " + accessToken,
},
});
handleErrorsRaw(response);
} catch (error) {
this.log.error(error);
throw error;
}
}
async getAvailability(
dateFrom: string,
dateTo: string,
selectedCalendars: IntegrationCalendar[]
): Promise<EventBusyDate[]> {
const dateFromParsed = new Date(dateFrom);
const dateToParsed = new Date(dateTo);
const filter = `?startdatetime=${encodeURIComponent(
dateFromParsed.toISOString()
)}&enddatetime=${encodeURIComponent(dateToParsed.toISOString())}`;
return this.auth
.getToken()
.then((accessToken) => {
const selectedCalendarIds = selectedCalendars
.filter((e) => e.integration === this.integrationName)
.map((e) => e.externalId)
.filter(Boolean);
if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
// Only calendars of other integrations selected
return Promise.resolve([]);
}
return (
selectedCalendarIds.length === 0
? this.listCalendars().then((cals) => cals.map((e) => e.externalId).filter(Boolean) || [])
: Promise.resolve(selectedCalendarIds)
).then((ids) => {
const requests = ids.map((calendarId, id) => ({
id,
method: "GET",
url: `/me/calendars/${calendarId}/calendarView${filter}`,
}));
return fetch("https://graph.microsoft.com/v1.0/$batch", {
method: "POST",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify({ requests }),
})
.then(handleErrorsJson)
.then((responseBody: BatchResponse) =>
responseBody.responses.reduce(
(acc: BufferedBusyTime[], subResponse) =>
acc.concat(
subResponse.body.value.map((evt) => {
return {
start: evt.start.dateTime + "Z",
end: evt.end.dateTime + "Z",
};
})
),
[]
)
);
});
})
.catch((err) => {
console.log(err);
return Promise.reject([]);
});
}
async listCalendars(): Promise<IntegrationCalendar[]> {
return this.auth.getToken().then((accessToken) =>
fetch("https://graph.microsoft.com/v1.0/me/calendars", {
method: "get",
headers: {
Authorization: "Bearer " + accessToken,
"Content-Type": "application/json",
},
})
.then(handleErrorsJson)
.then((responseBody: { value: OfficeCalendar[] }) => {
return responseBody.value.map((cal) => {
const calendar: IntegrationCalendar = {
externalId: cal.id ?? "No Id",
integration: this.integrationName,
name: cal.name ?? "No calendar name",
primary: cal.isDefaultCalendar ?? false,
};
return calendar;
});
})
);
}
private o365Auth = (credential: Credential) => {
const isExpired = (expiryDate: number) => expiryDate < Math.round(+new Date() / 1000);
const o365AuthCredentials = credential.key as O365AuthCredentials;
const refreshAccessToken = (refreshToken: string) => {
return fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
scope: "User.Read Calendars.Read Calendars.ReadWrite",
client_id: MS_GRAPH_CLIENT_ID,
refresh_token: refreshToken,
grant_type: "refresh_token",
client_secret: MS_GRAPH_CLIENT_SECRET,
}),
})
.then(handleErrorsJson)
.then((responseBody) => {
o365AuthCredentials.access_token = responseBody.access_token;
o365AuthCredentials.expiry_date = Math.round(+new Date() / 1000 + responseBody.expires_in);
return prisma.credential
.update({
where: {
id: credential.id,
},
data: {
key: o365AuthCredentials,
},
})
.then(() => o365AuthCredentials.access_token);
});
};
return {
getToken: () =>
!isExpired(o365AuthCredentials.expiry_date)
? Promise.resolve(o365AuthCredentials.access_token)
: refreshAccessToken(o365AuthCredentials.refresh_token),
};
};
private translateEvent = (event: CalendarEvent) => {
return {
subject: event.title,
body: {
contentType: "HTML",
content: getRichDescription(event),
},
start: {
dateTime: event.startTime,
timeZone: event.organizer.timeZone,
},
end: {
dateTime: event.endTime,
timeZone: event.organizer.timeZone,
},
attendees: event.attendees.map((attendee) => ({
emailAddress: {
address: attendee.email,
name: attendee.name,
},
type: "required",
})),
location: event.location ? { displayName: getLocation(event) } : undefined,
};
};
}
@@ -1,16 +0,0 @@
import dayjs from "dayjs";
import { Attendee, DateArray, DurationObject, Person } from "ics";
export const convertDate = (date: string): DateArray =>
dayjs(date)
.utc()
.toArray()
.slice(0, 6)
.map((v, i) => (i === 1 ? v + 1 : v)) as DateArray;
export const getDuration = (start: string, end: string): DurationObject => ({
minutes: dayjs(end).diff(dayjs(start), "minute"),
});
export const getAttendees = (attendees: Person[]): Attendee[] =>
attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
@@ -1,164 +0,0 @@
import { Prisma } from "@prisma/client";
import _ from "lodash";
import { validJson } from "@lib/jsonUtils";
const credentialData = Prisma.validator<Prisma.CredentialArgs>()({
select: { id: true, type: true },
});
type CredentialData = Prisma.CredentialGetPayload<typeof credentialData>;
export type Integration = {
installed: boolean;
type:
| "google_calendar"
| "office365_calendar"
| "zoom_video"
| "daily_video"
| "tandem_video"
| "caldav_calendar"
| "apple_calendar"
| "stripe_payment"
| "jitsi_video"
| "huddle01_video"
| "metamask_web3";
title: string;
imageSrc: string;
description: string;
variant: "calendar" | "conferencing" | "payment" | "web3";
};
export const ALL_INTEGRATIONS = [
{
installed: !!(process.env.GOOGLE_API_CREDENTIALS && validJson(process.env.GOOGLE_API_CREDENTIALS)),
type: "google_calendar",
title: "Google Calendar",
imageSrc: "integrations/google-calendar.svg",
description: "For personal and business calendars",
variant: "calendar",
},
{
installed: !!(process.env.MS_GRAPH_CLIENT_ID && process.env.MS_GRAPH_CLIENT_SECRET),
type: "office365_calendar",
title: "Office 365 / Outlook.com Calendar",
imageSrc: "integrations/outlook.svg",
description: "For personal and business calendars",
variant: "calendar",
},
{
installed: !!(process.env.ZOOM_CLIENT_ID && process.env.ZOOM_CLIENT_SECRET),
type: "zoom_video",
title: "Zoom",
imageSrc: "integrations/zoom.svg",
description: "Video Conferencing",
variant: "conferencing",
},
{
installed: !!process.env.DAILY_API_KEY,
type: "daily_video",
title: "Daily.co Video",
imageSrc: "integrations/daily.svg",
description: "Video Conferencing",
variant: "conferencing",
},
{
installed: true,
type: "jitsi_video",
title: "Jitsi Meet",
imageSrc: "integrations/jitsi.svg",
description: "Video Conferencing",
variant: "conferencing",
},
{
installed: true,
type: "huddle01_video",
title: "Huddle01",
imageSrc: "integrations/huddle.svg",
description: "Video Conferencing",
variant: "conferencing",
},
{
installed: !!(process.env.TANDEM_CLIENT_ID && process.env.TANDEM_CLIENT_SECRET),
type: "tandem_video",
title: "Tandem Video",
imageSrc: "integrations/tandem.svg",
description: "Virtual Office | Video Conferencing",
variant: "conferencing",
},
{
installed: true,
type: "caldav_calendar",
title: "CalDav Server",
imageSrc: "integrations/caldav.svg",
description: "For personal and business calendars",
variant: "calendar",
},
{
installed: true,
type: "apple_calendar",
title: "Apple Calendar",
imageSrc: "integrations/apple-calendar.svg",
description: "For personal and business calendars",
variant: "calendar",
},
{
installed: !!(
process.env.STRIPE_CLIENT_ID &&
process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY &&
process.env.STRIPE_PRIVATE_KEY
),
type: "stripe_payment",
title: "Stripe",
imageSrc: "integrations/stripe.svg",
description: "Collect payments",
variant: "payment",
},
{
installed: true,
type: "metamask_web3",
title: "Metamask",
imageSrc: "integrations/apple-calendar.svg",
description: "For personal and business calendars",
variant: "web3",
},
] as Integration[];
function getIntegrations(userCredentials: CredentialData[]) {
const integrations = ALL_INTEGRATIONS.map((integration) => {
const credentials = userCredentials
.filter((credential) => credential.type === integration.type)
.map((credential) => _.pick(credential, ["id", "type"])); // ensure we don't leak `key` to frontend
const credential: typeof credentials[number] | null = credentials[0] || null;
return {
...integration,
/**
* @deprecated use `credentials`
*/
credential,
credentials,
};
});
return integrations;
}
export type IntegrationMeta = ReturnType<typeof getIntegrations>;
export function hasIntegration(integrations: IntegrationMeta, type: string): boolean {
return !!integrations.find(
(i) =>
i.type === type &&
!!i.installed &&
(type === "daily_video" ||
type === "jitsi_video" ||
type === "huddle01_video" ||
i.credentials.length > 0)
);
}
export function hasIntegrationInstalled(type: Integration["type"]): boolean {
return ALL_INTEGRATIONS.some((i) => i.type === type && !!i.installed);
}
export default getIntegrations;
-11
View File
@@ -1,11 +0,0 @@
export const validJson = (jsonString: string) => {
try {
const o = JSON.parse(jsonString);
if (o && typeof o === "object") {
return o;
}
} catch (e) {
console.log("Invalid JSON:", e);
}
return false;
};
-20
View File
@@ -1,20 +0,0 @@
import { Logger } from "tslog";
import { IS_PRODUCTION } from "@lib/config/constants";
const logger = new Logger({
dateTimePattern: "hour:minute:second.millisecond timeZoneName",
displayFunctionName: false,
displayFilePath: "hidden",
dateTimeTimezone: IS_PRODUCTION ? "utc" : Intl.DateTimeFormat().resolvedOptions().timeZone,
prettyInspectHighlightStyles: {
name: "yellow",
number: "blue",
bigint: "blue",
boolean: "blue",
},
maskValuesOfKeys: ["password", "passwordConfirmation", "credentials", "credential"],
exposeErrorCodeFrame: !IS_PRODUCTION,
});
export default logger;
-3
View File
@@ -1,3 +0,0 @@
const notEmpty = <T>(value: T): value is NonNullable<typeof value> => !!value;
export default notEmpty;
+2 -4
View File
@@ -1,10 +1,10 @@
// import { getBusyVideoTimes } from "@lib/videoClient";
import { Prisma } from "@prisma/client";
import dayjs from "dayjs";
import { getBusyCalendarTimes } from "@calcom/core/CalendarManager";
import { asStringOrNull } from "@lib/asStringOrNull";
import { getWorkingHours } from "@lib/availability";
import { getBusyCalendarTimes } from "@lib/integrations/calendar/CalendarManager";
import prisma from "@lib/prisma";
export async function getUserAvailability(query: {
@@ -67,8 +67,6 @@ export async function getUserAvailability(query: {
selectedCalendars
);
// busyTimes.push(...await getBusyVideoTimes(currentUser.credentials, dateFrom.format(), dateTo.format()));
const bufferedBusyTimes = busyTimes.map((a) => ({
start: dayjs(a.start).subtract(currentUser.bufferTime, "minute").toString(),
end: dayjs(a.end).add(currentUser.bufferTime, "minute").toString(),
+2 -9
View File
@@ -1,9 +1,2 @@
export const randomString = function (length = 12) {
let result = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
// TODO: Remove this file once everything is imported from `@calcom/lib`
export * from "@calcom/lib/random";
+1 -1
View File
@@ -6,7 +6,7 @@
*/
export const isBrowserLocale24h = () => {
let locale = "en-US";
if (process.browser && navigator) locale = navigator?.language;
if (typeof window !== "undefined" && navigator) locale = navigator?.language;
return !new Intl.DateTimeFormat(locale, { hour: "numeric" }).format(0).match(/AM/);
};
export const detectBrowserTimeFormat = isBrowserLocale24h() ? "H:mm" : "h:mma";
-7
View File
@@ -1,7 +0,0 @@
/** Makes selected props from a record non optional */
export type Ensure<T, K extends keyof T> = Omit<T, K> & {
[EK in K]-?: NonNullable<T[EK]>;
};
/** Makes selected props from a record optional */
export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
-148
View File
@@ -1,148 +0,0 @@
import { Credential } from "@prisma/client";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
import { getUid } from "@lib/CalEventParser";
import { EventResult } from "@lib/events/EventManager";
import { PartialReference } from "@lib/events/EventManager";
import Huddle01VideoApiAdapter from "@lib/integrations/Huddle01/Huddle01VideoApiAdapter";
import JitsiVideoApiAdapter from "@lib/integrations/Jitsi/JitsiVideoApiAdapter";
import logger from "@lib/logger";
import DailyVideoApiAdapter from "./integrations/Daily/DailyVideoApiAdapter";
import TandemVideoApiAdapter from "./integrations/Tandem/TandemVideoApiAdapter";
import ZoomVideoApiAdapter from "./integrations/Zoom/ZoomVideoApiAdapter";
import { CalendarEvent } from "./integrations/calendar/interfaces/Calendar";
const log = logger.getChildLogger({ prefix: ["[lib] videoClient"] });
const translator = short();
export interface VideoCallData {
type: string;
id: string;
password: string;
url: string;
}
type EventBusyDate = Record<"start" | "end", Date>;
export interface VideoApiAdapter {
createMeeting(event: CalendarEvent): Promise<VideoCallData>;
updateMeeting(bookingRef: PartialReference, event: CalendarEvent): Promise<VideoCallData>;
deleteMeeting(uid: string): Promise<unknown>;
getAvailability(dateFrom?: string, dateTo?: string): Promise<EventBusyDate[]>;
}
// factory
const getVideoAdapters = (withCredentials: Credential[]): VideoApiAdapter[] =>
withCredentials.reduce<VideoApiAdapter[]>((acc, cred) => {
switch (cred.type) {
case "zoom_video":
acc.push(ZoomVideoApiAdapter(cred));
break;
case "daily_video":
acc.push(DailyVideoApiAdapter(cred));
break;
case "jitsi_video":
acc.push(JitsiVideoApiAdapter());
break;
case "huddle01_video":
acc.push(Huddle01VideoApiAdapter());
break;
case "tandem_video":
acc.push(TandemVideoApiAdapter(cred));
break;
default:
break;
}
return acc;
}, []);
const getBusyVideoTimes = (withCredentials: Credential[]) =>
Promise.all(getVideoAdapters(withCredentials).map((c) => c.getAvailability())).then((results) =>
results.reduce((acc, availability) => acc.concat(availability), [])
);
const createMeeting = async (credential: Credential, calEvent: CalendarEvent): Promise<EventResult> => {
const uid: string = getUid(calEvent);
if (!credential) {
throw new Error(
"Credentials must be set! Video platforms are optional, so this method shouldn't even be called when no video credentials are set."
);
}
const videoAdapters = getVideoAdapters([credential]);
const [firstVideoAdapter] = videoAdapters;
const createdMeeting = await firstVideoAdapter.createMeeting(calEvent).catch((e) => {
log.error("createMeeting failed", e, calEvent);
});
if (!createdMeeting) {
return {
type: credential.type,
success: false,
uid,
originalEvent: calEvent,
};
}
return {
type: credential.type,
success: true,
uid,
createdEvent: createdMeeting,
originalEvent: calEvent,
};
};
const updateMeeting = async (
credential: Credential,
calEvent: CalendarEvent,
bookingRef: PartialReference | null
): Promise<EventResult> => {
const uid = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
let success = true;
const [firstVideoAdapter] = getVideoAdapters([credential]);
const updatedMeeting =
credential && bookingRef
? await firstVideoAdapter.updateMeeting(bookingRef, calEvent).catch((e) => {
log.error("updateMeeting failed", e, calEvent);
success = false;
return undefined;
})
: undefined;
if (!updatedMeeting) {
return {
type: credential.type,
success,
uid,
originalEvent: calEvent,
};
}
return {
type: credential.type,
success,
uid,
updatedEvent: updatedMeeting,
originalEvent: calEvent,
};
};
const deleteMeeting = (credential: Credential, uid: string): Promise<unknown> => {
if (credential) {
return getVideoAdapters([credential])[0].deleteMeeting(uid);
}
return Promise.resolve({});
};
export { getBusyVideoTimes, createMeeting, updateMeeting, deleteMeeting };
+1 -1
View File
@@ -1,6 +1,6 @@
import { compile } from "handlebars";
import { CalendarEvent } from "@lib/integrations/calendar/interfaces/Calendar";
import type { CalendarEvent } from "@calcom/types/Calendar";
type ContentType = "application/json" | "application/x-www-form-urlencoded";