2022-10-31 22:06:03 +00:00
|
|
|
import { SelectedCalendar } from "@prisma/client";
|
2022-06-19 15:02:00 +00:00
|
|
|
import { createHash } from "crypto";
|
2022-01-06 17:28:31 +00:00
|
|
|
import _ from "lodash";
|
2022-06-19 15:02:00 +00:00
|
|
|
import cache from "memory-cache";
|
2022-01-06 17:28:31 +00:00
|
|
|
|
2022-03-23 22:00:30 +00:00
|
|
|
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
|
|
|
import getApps from "@calcom/app-store/utils";
|
|
|
|
import { getUid } from "@calcom/lib/CalEventParser";
|
|
|
|
import logger from "@calcom/lib/logger";
|
2022-08-12 18:18:13 +00:00
|
|
|
import { performance } from "@calcom/lib/server/perfObserver";
|
2022-06-17 18:34:41 +00:00
|
|
|
import type { CalendarEvent, EventBusyDate, NewCalendarEventType } from "@calcom/types/Calendar";
|
2022-10-31 22:06:03 +00:00
|
|
|
import { CredentialPayload, CredentialWithAppName } from "@calcom/types/Credential";
|
2022-03-23 22:00:30 +00:00
|
|
|
import type { EventResult } from "@calcom/types/EventManager";
|
2022-01-06 17:28:31 +00:00
|
|
|
|
|
|
|
const log = logger.getChildLogger({ prefix: ["CalendarManager"] });
|
|
|
|
|
2022-10-31 22:06:03 +00:00
|
|
|
export const getCalendarCredentials = (credentials: Array<CredentialPayload>) => {
|
2022-03-23 22:00:30 +00:00
|
|
|
const calendarCredentials = getApps(credentials)
|
|
|
|
.filter((app) => app.type.endsWith("_calendar"))
|
|
|
|
.flatMap((app) => {
|
|
|
|
const credentials = app.credentials.flatMap((credential) => {
|
|
|
|
const calendar = getCalendar(credential);
|
2022-09-29 12:58:53 +00:00
|
|
|
return app.variant === "calendar" ? [{ integration: app, credential, calendar }] : [];
|
2022-01-06 17:28:31 +00:00
|
|
|
});
|
2022-03-23 22:00:30 +00:00
|
|
|
return credentials.length ? credentials : [];
|
2022-01-06 17:28:31 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return calendarCredentials;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const getConnectedCalendars = async (
|
|
|
|
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
|
|
|
|
selectedCalendars: { externalId: string }[]
|
|
|
|
) => {
|
|
|
|
const connectedCalendars = await Promise.all(
|
|
|
|
calendarCredentials.map(async (item) => {
|
2022-10-04 14:56:38 +00:00
|
|
|
try {
|
|
|
|
const { calendar, integration, credential } = item;
|
|
|
|
|
|
|
|
// Don't leak credentials to the client
|
|
|
|
const credentialId = credential.id;
|
|
|
|
if (!calendar) {
|
|
|
|
return {
|
|
|
|
integration,
|
|
|
|
credentialId,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
const cals = await calendar.listCalendars();
|
|
|
|
const calendars = _(cals)
|
|
|
|
.map((cal) => ({
|
|
|
|
...cal,
|
|
|
|
readOnly: cal.readOnly || false,
|
|
|
|
primary: cal.primary || null,
|
|
|
|
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
|
|
|
|
credentialId,
|
|
|
|
}))
|
|
|
|
.sortBy(["primary"])
|
|
|
|
.value();
|
|
|
|
const primary = calendars.find((item) => item.primary) ?? calendars.find((cal) => cal !== undefined);
|
|
|
|
if (!primary) {
|
|
|
|
return {
|
|
|
|
integration,
|
|
|
|
credentialId,
|
|
|
|
error: {
|
|
|
|
message: "No primary calendar found",
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-01-06 17:28:31 +00:00
|
|
|
return {
|
2022-10-04 14:56:38 +00:00
|
|
|
integration: cleanIntegrationKeys(integration),
|
2022-01-06 17:28:31 +00:00
|
|
|
credentialId,
|
2022-10-04 14:56:38 +00:00
|
|
|
primary,
|
|
|
|
calendars,
|
2022-01-06 17:28:31 +00:00
|
|
|
};
|
2022-10-04 14:56:38 +00:00
|
|
|
} catch (error) {
|
|
|
|
let errorMessage = "Could not get connected calendars";
|
|
|
|
|
|
|
|
// Here you can expect for specific errors
|
|
|
|
if (error instanceof Error) {
|
|
|
|
if (error.message === "invalid_grant") {
|
|
|
|
errorMessage = "Access token expired or revoked";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-29 12:58:53 +00:00
|
|
|
return {
|
2022-10-04 14:56:38 +00:00
|
|
|
integration: cleanIntegrationKeys(item.integration),
|
|
|
|
credentialId: item.credential.id,
|
2022-09-29 12:58:53 +00:00
|
|
|
error: {
|
2022-10-04 14:56:38 +00:00
|
|
|
message: errorMessage,
|
2022-09-29 12:58:53 +00:00
|
|
|
},
|
|
|
|
};
|
2022-01-06 17:28:31 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
return connectedCalendars;
|
|
|
|
};
|
|
|
|
|
2022-10-04 14:56:38 +00:00
|
|
|
/**
|
|
|
|
* Important function to prevent leaking credentials to the client
|
|
|
|
* @param appIntegration
|
|
|
|
* @returns App
|
|
|
|
*/
|
|
|
|
const cleanIntegrationKeys = (
|
|
|
|
appIntegration: ReturnType<typeof getCalendarCredentials>[number]["integration"] & {
|
2022-10-31 22:06:03 +00:00
|
|
|
credentials?: Array<CredentialPayload>;
|
|
|
|
credential: CredentialPayload;
|
2022-10-04 14:56:38 +00:00
|
|
|
}
|
|
|
|
) => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
|
|
const { credentials, credential, ...rest } = appIntegration;
|
|
|
|
return rest;
|
|
|
|
};
|
|
|
|
|
2022-06-19 15:02:00 +00:00
|
|
|
const CACHING_TIME = 30_000; // 30 seconds
|
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
const getCachedResults = async (
|
2022-10-31 22:06:03 +00:00
|
|
|
withCredentials: CredentialPayload[],
|
2022-01-06 17:28:31 +00:00
|
|
|
dateFrom: string,
|
|
|
|
dateTo: string,
|
|
|
|
selectedCalendars: SelectedCalendar[]
|
|
|
|
) => {
|
2022-06-19 15:02:00 +00:00
|
|
|
const calendarCredentials = withCredentials.filter((credential) => credential.type.endsWith("_calendar"));
|
|
|
|
const calendars = calendarCredentials.map((credential) => getCalendar(credential));
|
2022-07-07 15:26:22 +00:00
|
|
|
|
|
|
|
const startGetBusyCalendarTimes = performance.now();
|
2022-06-19 15:02:00 +00:00
|
|
|
const results = calendars.map(async (c, i) => {
|
|
|
|
/** Filter out nulls */
|
|
|
|
if (!c) return [];
|
|
|
|
/** We rely on the index so we can match credentials with calendars */
|
2022-09-07 19:28:43 +00:00
|
|
|
const { id, type, appId } = calendarCredentials[i];
|
2022-06-19 15:02:00 +00:00
|
|
|
/** We just pass the calendars that matched the credential type,
|
|
|
|
* TODO: Migrate credential type or appId
|
|
|
|
*/
|
|
|
|
const passedSelectedCalendars = selectedCalendars.filter((sc) => sc.integration === type);
|
|
|
|
/** We extract external Ids so we don't cache too much */
|
|
|
|
const selectedCalendarIds = passedSelectedCalendars.map((sc) => sc.externalId);
|
2022-07-27 19:12:42 +00:00
|
|
|
/** We create a unique hash key based on the input data */
|
2022-07-21 16:44:23 +00:00
|
|
|
const cacheKey = JSON.stringify({ id, selectedCalendarIds, dateFrom, dateTo });
|
|
|
|
const cacheHashedKey = createHash("md5").update(cacheKey).digest("hex");
|
2022-06-19 15:02:00 +00:00
|
|
|
/** Check if we already have cached data and return */
|
2022-07-21 16:44:23 +00:00
|
|
|
const cachedAvailability = cache.get(cacheHashedKey);
|
2022-07-27 19:12:42 +00:00
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
if (cachedAvailability) {
|
2022-07-21 16:44:23 +00:00
|
|
|
log.debug(`Cache HIT: Calendar Availability for key: ${cacheKey}`);
|
2022-07-07 15:26:22 +00:00
|
|
|
return cachedAvailability;
|
|
|
|
}
|
2022-07-21 16:44:23 +00:00
|
|
|
log.debug(`Cache MISS: Calendar Availability for key ${cacheKey}`);
|
2022-06-19 15:02:00 +00:00
|
|
|
/** If we don't then we actually fetch external calendars (which can be very slow) */
|
2022-09-07 19:28:43 +00:00
|
|
|
const availability = (await c.getAvailability(dateFrom, dateTo, passedSelectedCalendars)).map((a) => ({
|
|
|
|
...a,
|
|
|
|
source: `${appId}`,
|
|
|
|
}));
|
2022-06-19 15:02:00 +00:00
|
|
|
/** We save the availability to a few seconds so recurrent calls are nearly instant */
|
2022-07-27 19:12:42 +00:00
|
|
|
|
2022-07-21 16:44:23 +00:00
|
|
|
cache.put(cacheHashedKey, availability, CACHING_TIME);
|
2022-06-19 15:02:00 +00:00
|
|
|
return availability;
|
|
|
|
});
|
2022-07-07 15:26:22 +00:00
|
|
|
const awaitedResults = await Promise.all(results);
|
|
|
|
const endGetBusyCalendarTimes = performance.now();
|
2022-01-06 17:28:31 +00:00
|
|
|
|
2022-07-07 15:26:22 +00:00
|
|
|
log.debug(
|
|
|
|
`getBusyCalendarTimes took ${
|
|
|
|
endGetBusyCalendarTimes - startGetBusyCalendarTimes
|
|
|
|
}ms for creds ${calendarCredentials.map((cred) => cred.id)}`
|
|
|
|
);
|
|
|
|
return awaitedResults;
|
2022-06-19 15:02:00 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const getBusyCalendarTimes = async (
|
2022-10-31 22:06:03 +00:00
|
|
|
withCredentials: CredentialPayload[],
|
2022-06-19 15:02:00 +00:00
|
|
|
dateFrom: string,
|
|
|
|
dateTo: string,
|
|
|
|
selectedCalendars: SelectedCalendar[]
|
|
|
|
) => {
|
2022-01-06 22:06:31 +00:00
|
|
|
let results: EventBusyDate[][] = [];
|
|
|
|
try {
|
2022-06-19 15:02:00 +00:00
|
|
|
results = await getCachedResults(withCredentials, dateFrom, dateTo, selectedCalendars);
|
2022-01-06 22:06:31 +00:00
|
|
|
} catch (error) {
|
|
|
|
log.warn(error);
|
|
|
|
}
|
2022-01-06 17:28:31 +00:00
|
|
|
return results.reduce((acc, availability) => acc.concat(availability), []);
|
|
|
|
};
|
|
|
|
|
2022-06-17 18:34:41 +00:00
|
|
|
export const createEvent = async (
|
2022-10-31 22:06:03 +00:00
|
|
|
credential: CredentialWithAppName,
|
2022-06-17 18:34:41 +00:00
|
|
|
calEvent: CalendarEvent
|
|
|
|
): Promise<EventResult<NewCalendarEventType>> => {
|
2022-01-06 17:28:31 +00:00
|
|
|
const uid: string = getUid(calEvent);
|
|
|
|
const calendar = getCalendar(credential);
|
|
|
|
let success = true;
|
2022-11-22 20:44:08 +00:00
|
|
|
let calError: string | undefined = undefined;
|
2022-01-06 17:28:31 +00:00
|
|
|
|
2022-03-28 18:07:13 +00:00
|
|
|
// Check if the disabledNotes flag is set to true
|
|
|
|
if (calEvent.hideCalendarNotes) {
|
2022-04-07 18:22:11 +00:00
|
|
|
calEvent.additionalNotes = "Notes have been hidden by the organiser"; // TODO: i18n this string?
|
2022-03-28 18:07:13 +00:00
|
|
|
}
|
|
|
|
|
2022-04-16 02:23:38 +00:00
|
|
|
// TODO: Surfice success/error messages coming from apps to improve end user visibility
|
2022-01-06 17:28:31 +00:00
|
|
|
const creationResult = calendar
|
2022-08-02 18:07:45 +00:00
|
|
|
? await calendar.createEvent(calEvent).catch(async (error) => {
|
2022-04-02 23:43:28 +00:00
|
|
|
success = false;
|
2022-08-02 18:07:45 +00:00
|
|
|
/**
|
|
|
|
* There is a time when selectedCalendar externalId doesn't match witch certain credential
|
|
|
|
* so google returns 404.
|
|
|
|
* */
|
|
|
|
if (error?.code === 404) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2022-11-22 20:44:08 +00:00
|
|
|
if (error?.calError) {
|
|
|
|
calError = error.calError;
|
|
|
|
}
|
2022-08-02 18:07:45 +00:00
|
|
|
log.error("createEvent failed", error, calEvent);
|
2022-08-26 18:12:47 +00:00
|
|
|
// @TODO: This code will be off till we can investigate an error with it
|
|
|
|
//https://github.com/calcom/cal.com/issues/3949
|
|
|
|
// await sendBrokenIntegrationEmail(calEvent, "calendar");
|
2022-04-02 23:43:28 +00:00
|
|
|
return undefined;
|
|
|
|
})
|
2022-01-06 17:28:31 +00:00
|
|
|
: undefined;
|
|
|
|
|
|
|
|
return {
|
2022-10-19 16:11:50 +00:00
|
|
|
appName: credential.appName,
|
2022-01-06 17:28:31 +00:00
|
|
|
type: credential.type,
|
|
|
|
success,
|
|
|
|
uid,
|
|
|
|
createdEvent: creationResult,
|
|
|
|
originalEvent: calEvent,
|
2022-11-22 20:44:08 +00:00
|
|
|
calError,
|
|
|
|
calWarnings: creationResult?.additionalInfo.calWarnings,
|
2022-01-06 17:28:31 +00:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export const updateEvent = async (
|
2022-10-31 22:06:03 +00:00
|
|
|
credential: CredentialWithAppName,
|
2022-01-06 17:28:31 +00:00
|
|
|
calEvent: CalendarEvent,
|
2022-05-16 20:20:09 +00:00
|
|
|
bookingRefUid: string | null,
|
|
|
|
externalCalendarId: string | null
|
2022-06-17 18:34:41 +00:00
|
|
|
): Promise<EventResult<NewCalendarEventType>> => {
|
2022-01-06 17:28:31 +00:00
|
|
|
const uid = getUid(calEvent);
|
|
|
|
const calendar = getCalendar(credential);
|
2022-05-12 09:33:15 +00:00
|
|
|
let success = false;
|
2022-11-22 20:44:08 +00:00
|
|
|
let calError: string | undefined = undefined;
|
|
|
|
let calWarnings: string[] | undefined = [];
|
|
|
|
|
2022-05-12 09:33:15 +00:00
|
|
|
if (bookingRefUid === "") {
|
|
|
|
log.error("updateEvent failed", "bookingRefUid is empty", calEvent, credential);
|
|
|
|
}
|
2022-01-06 17:28:31 +00:00
|
|
|
const updatedResult =
|
|
|
|
calendar && bookingRefUid
|
2022-05-12 09:33:15 +00:00
|
|
|
? await calendar
|
2022-05-16 20:20:09 +00:00
|
|
|
.updateEvent(bookingRefUid, calEvent, externalCalendarId)
|
2022-06-17 18:34:41 +00:00
|
|
|
.then((event) => {
|
|
|
|
success = true;
|
|
|
|
return event;
|
|
|
|
})
|
2022-06-25 05:16:20 +00:00
|
|
|
.catch(async (e) => {
|
2022-08-26 18:12:47 +00:00
|
|
|
// @TODO: This code will be off till we can investigate an error with it
|
|
|
|
// @see https://github.com/calcom/cal.com/issues/3949
|
|
|
|
// await sendBrokenIntegrationEmail(calEvent, "calendar");
|
2022-05-12 09:33:15 +00:00
|
|
|
log.error("updateEvent failed", e, calEvent);
|
2022-11-22 20:44:08 +00:00
|
|
|
if (e?.calError) {
|
|
|
|
calError = e.calError;
|
|
|
|
}
|
2022-05-12 09:33:15 +00:00
|
|
|
return undefined;
|
|
|
|
})
|
2022-01-06 17:28:31 +00:00
|
|
|
: undefined;
|
|
|
|
|
2022-11-22 20:44:08 +00:00
|
|
|
if (Array.isArray(updatedResult)) {
|
|
|
|
calWarnings = updatedResult.flatMap((res) => res.additionalInfo.calWarnings ?? []);
|
|
|
|
} else {
|
|
|
|
calWarnings = updatedResult?.additionalInfo.calWarnings;
|
|
|
|
}
|
|
|
|
|
2022-01-06 17:28:31 +00:00
|
|
|
return {
|
2022-10-19 16:11:50 +00:00
|
|
|
appName: credential.appName,
|
2022-01-06 17:28:31 +00:00
|
|
|
type: credential.type,
|
|
|
|
success,
|
|
|
|
uid,
|
|
|
|
updatedEvent: updatedResult,
|
|
|
|
originalEvent: calEvent,
|
2022-11-22 20:44:08 +00:00
|
|
|
calError,
|
|
|
|
calWarnings,
|
2022-01-06 17:28:31 +00:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-10-31 22:06:03 +00:00
|
|
|
export const deleteEvent = (
|
|
|
|
credential: CredentialPayload,
|
|
|
|
uid: string,
|
|
|
|
event: CalendarEvent
|
|
|
|
): Promise<unknown> => {
|
2022-01-06 17:28:31 +00:00
|
|
|
const calendar = getCalendar(credential);
|
|
|
|
if (calendar) {
|
2022-01-13 19:47:15 +00:00
|
|
|
return calendar.deleteEvent(uid, event);
|
2022-01-06 17:28:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return Promise.resolve({});
|
|
|
|
};
|