refactor: circular deps between app store and lib [6] (#23971)
* move delegation credential repository to features * mv credential repository to features * update imports * mv * fix * fix * fix * fix * fix * update imports * update imports * update eslint rule * fix * fix * mv getConnectedDestinationCalendars * fix import errors * mv getCalendarsEvents * remove getUsersCredentials * wip * revert eslint rule change for now * fix type checks * fix * format * cleanup * fix * fix * fix * fix * fix tests * migrate getUserAvailability * migrate * fix tests * fix type checks * fix * fix * migrate crmManager * update imports * migrate raqbUtils to appstore * migrate getLuckyUser to features * migrate findTeamMembersMatchingAttributeLogic to appstore * update imports * fix * fix * fix test * fix unit tests * fix * fix * add eslint config
This commit is contained in:
1 parent
445b307972
commit
bb68cd73ef
114 files changed
+263
-245
No files matched your search
@@ -5,14 +5,15 @@ import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { MeetLocationType } from "@calcom/app-store/locations";
|
||||
import getApps from "@calcom/app-store/utils";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import getCalendarsEvents, {
|
||||
getCalendarsEventsWithTimezones,
|
||||
} from "@calcom/features/calendars/lib/getCalendarsEvents";
|
||||
import { getUid } from "@calcom/lib/CalEventParser";
|
||||
import { getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
|
||||
import { ORGANIZER_EMAIL_EXEMPT_DOMAINS } from "@calcom/lib/constants";
|
||||
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential";
|
||||
import { formatCalEvent } from "@calcom/lib/formatCalendarEvent";
|
||||
import getCalendarsEvents from "@calcom/lib/getCalendarsEvents";
|
||||
import { getCalendarsEventsWithTimezones } from "@calcom/lib/getCalendarsEvents";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
|
||||
@@ -0,0 +1,786 @@
|
||||
import "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
|
||||
import OfficeCalendarService from "@calcom/app-store/office365calendar/lib/CalendarService";
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { SelectedCalendar } from "@calcom/prisma/client";
|
||||
import type { EventBusyDate } from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import getCalendarsEvents, {
|
||||
getCalendarsEventsWithTimezones,
|
||||
filterSelectedCalendarsForCredential,
|
||||
} from "./getCalendarsEvents";
|
||||
|
||||
vi.mock("@calcom/lib/crypto", () => ({
|
||||
symmetricDecrypt: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedSymmetricDecrypt = vi.mocked(symmetricDecrypt);
|
||||
|
||||
vi.mock("@calcom/app-store/calendar.services.generated", () => {
|
||||
class MockGoogleCalendarService {
|
||||
constructor(credential: any) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
getCredentialId() {
|
||||
return this.credential.id;
|
||||
}
|
||||
|
||||
async createEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async updateEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async deleteEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async getAvailability() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getAvailabilityWithTimeZones() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async listCalendars() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class MockOfficeCalendarService {
|
||||
constructor(credential: any) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
getCredentialId() {
|
||||
return this.credential.id;
|
||||
}
|
||||
|
||||
async createEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async updateEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async deleteEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async getAvailability() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getAvailabilityWithTimeZones() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async listCalendars() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
CalendarServiceMap: {
|
||||
googlecalendar: vi.importActual("@calcom/app-store/googlecalendar/lib/CalendarService"),
|
||||
office365calendar: vi.importActual("@calcom/app-store/office365calendar/lib/CalendarService"),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
function buildDelegationCredential(credential: CredentialPayload): CredentialForCalendarService {
|
||||
return {
|
||||
...credential,
|
||||
id: -1,
|
||||
delegatedTo: {
|
||||
serviceAccountKey: {
|
||||
client_email: "client_email",
|
||||
tenant_id: "tenant_id",
|
||||
client_id: "client_id",
|
||||
private_key: "private_key",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildRegularCredential(credential: CredentialPayload): CredentialForCalendarService {
|
||||
return {
|
||||
...credential,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildSelectedCalendar(credential: {
|
||||
credentialId: number;
|
||||
externalId: string;
|
||||
integration: string;
|
||||
userId: number;
|
||||
id: string;
|
||||
}): SelectedCalendar {
|
||||
return {
|
||||
googleChannelId: null,
|
||||
googleChannelKind: null,
|
||||
googleChannelResourceId: null,
|
||||
eventTypeId: null,
|
||||
googleChannelResourceUri: null,
|
||||
googleChannelExpiration: null,
|
||||
delegationCredentialId: null,
|
||||
domainWideDelegationCredentialId: null,
|
||||
error: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastErrorAt: null,
|
||||
watchAttempts: 0,
|
||||
unwatchAttempts: 0,
|
||||
maxAttempts: 3,
|
||||
...credential,
|
||||
};
|
||||
}
|
||||
|
||||
describe("getCalendarsEvents", () => {
|
||||
let credential: CredentialPayload;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(logger.constructor.prototype, "debug");
|
||||
|
||||
credential = {
|
||||
id: 303,
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
scope: "example scope",
|
||||
token_type: "Bearer",
|
||||
expiry_date: Date.now() + 84000,
|
||||
access_token: "access token",
|
||||
refresh_token: "refresh token",
|
||||
},
|
||||
userId: 808,
|
||||
teamId: null,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
},
|
||||
appId: "exampleApp",
|
||||
invalid: false,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("Regular Credentials", () => {
|
||||
it("should return empty array if no calendar credentials", async () => {
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "totally_unrelated",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unknown calendars as empty", async () => {
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "unknown_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return unmatched calendars as empty", async () => {
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return availability from selected calendar", async () => {
|
||||
const availability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
},
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
},
|
||||
];
|
||||
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(availability));
|
||||
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(getAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
availability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return availability from multiple calendars", async () => {
|
||||
const googleAvailability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
},
|
||||
];
|
||||
const officeAvailability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
},
|
||||
];
|
||||
|
||||
const getGoogleAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(googleAvailability));
|
||||
const getOfficeAvailabilitySpy = vi
|
||||
.spyOn(OfficeCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(officeAvailability));
|
||||
|
||||
const selectedGoogleCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const selectedOfficeCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "office365_calendar",
|
||||
key: {
|
||||
access_token: "access",
|
||||
refresh_token: "refresh",
|
||||
expires_in: Date.now() + 86400,
|
||||
},
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedGoogleCalendar, selectedOfficeCalendar]
|
||||
);
|
||||
|
||||
expect(getGoogleAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedGoogleCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(getOfficeAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedOfficeCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
googleAvailability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
officeAvailability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should not call getAvailability if selectedCalendars is empty", async () => {
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEvents(
|
||||
[buildRegularCredential(credential)],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(getAvailabilitySpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delegation Credentials", () => {
|
||||
it("should allow getAvailability call even without any selected calendars with allowFallbackToPrimary=true", async () => {
|
||||
const startDate = "2010-12-01";
|
||||
const endDate = "2010-12-02";
|
||||
const delegationCredential: CredentialForCalendarService = buildDelegationCredential(credential);
|
||||
const credentials = [delegationCredential];
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEvents(credentials, startDate, endDate, []);
|
||||
|
||||
expect(getAvailabilitySpy).toHaveBeenCalledWith(startDate, endDate, [], undefined, true);
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCalendarsEventsWithTimezones", () => {
|
||||
let credential: CredentialPayload;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(logger.constructor.prototype, "debug");
|
||||
|
||||
credential = {
|
||||
id: 303,
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
scope: "example scope",
|
||||
token_type: "Bearer",
|
||||
expiry_date: Date.now() + 84000,
|
||||
access_token: "access token",
|
||||
refresh_token: "refresh token",
|
||||
},
|
||||
userId: 808,
|
||||
teamId: null,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
},
|
||||
appId: "exampleApp",
|
||||
invalid: false,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("Regular Credentials", () => {
|
||||
it("should return empty array if no calendar credentials", async () => {
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "totally_unrelated",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unknown calendars as empty", async () => {
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "unknown_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unmatched calendars as empty", async () => {
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return availability from selected calendar", async () => {
|
||||
const availability = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
timeZone: "America/New_York",
|
||||
},
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
timeZone: "America/New_York",
|
||||
},
|
||||
];
|
||||
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve(availability));
|
||||
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar],
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
availability.map((av) => ({
|
||||
...av,
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should not call getAvailabilityWithTimezones if selectedCalendars is empty", async () => {
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[buildRegularCredential(credential)],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delegation Credentials", () => {
|
||||
it("should allow getAvailabilityWithTimezones call even without any selected calendars with allowFallbackToPrimary=true", async () => {
|
||||
const startDate = "2010-12-01";
|
||||
const endDate = "2010-12-02";
|
||||
const delegationCredential: CredentialForCalendarService = buildDelegationCredential(credential);
|
||||
const credentials = [delegationCredential];
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEventsWithTimezones(credentials, startDate, endDate, []);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).toHaveBeenCalledWith(startDate, endDate, [], true);
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// CalDAV Credential Leak Prevention Tests
|
||||
describe("CalDAV credential leak prevention", () => {
|
||||
function buildCalDAVCredential(data: {
|
||||
id: number;
|
||||
key: string;
|
||||
userId?: number;
|
||||
}): CredentialForCalendarService {
|
||||
return {
|
||||
id: data.id,
|
||||
type: "caldav_calendar",
|
||||
key: data.key,
|
||||
userId: data.userId || 1,
|
||||
user: { email: "[email protected]" },
|
||||
teamId: null,
|
||||
appId: "caldav-calendar",
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildCalDAVSelectedCalendar(data: {
|
||||
id: string;
|
||||
externalId: string;
|
||||
credentialId?: number;
|
||||
}): SelectedCalendar {
|
||||
return {
|
||||
id: data.id,
|
||||
userId: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: data.externalId,
|
||||
credentialId: data.credentialId || null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
googleChannelId: null,
|
||||
googleChannelKind: null,
|
||||
googleChannelResourceId: null,
|
||||
googleChannelResourceUri: null,
|
||||
googleChannelExpiration: null,
|
||||
delegationCredentialId: null,
|
||||
domainWideDelegationCredentialId: null,
|
||||
error: null,
|
||||
lastErrorAt: null,
|
||||
watchAttempts: 0,
|
||||
unwatchAttempts: 0,
|
||||
maxAttempts: 3,
|
||||
eventTypeId: null,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("filterSelectedCalendarsForCredential", () => {
|
||||
it("prevents CalDAV credential leak by matching server URLs", () => {
|
||||
// Setup: Two CalDAV servers with different URLs
|
||||
const serverACredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_server_a_key",
|
||||
});
|
||||
|
||||
const serverBCredential = buildCalDAVCredential({
|
||||
id: 2,
|
||||
key: "encrypted_server_b_key",
|
||||
});
|
||||
|
||||
// Mock encrypted credential data for different servers
|
||||
mockedSymmetricDecrypt
|
||||
.mockReturnValueOnce(
|
||||
JSON.stringify({
|
||||
username: "user_a",
|
||||
password: "pass_a",
|
||||
url: "https://server-a.example.com/dav/calendars/user/",
|
||||
})
|
||||
)
|
||||
.mockReturnValueOnce(
|
||||
JSON.stringify({
|
||||
username: "user_b",
|
||||
password: "pass_b",
|
||||
url: "https://server-b.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
// Selected calendars from both servers
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
credentialId: 1,
|
||||
}),
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "https://server-b.example.com/dav/calendars/user/calendar2/",
|
||||
credentialId: 2,
|
||||
}),
|
||||
];
|
||||
|
||||
// Test Server A credential - should only return Server A calendars
|
||||
const serverACalendars = filterSelectedCalendarsForCredential(selectedCalendars, serverACredential);
|
||||
expect(serverACalendars).toHaveLength(1);
|
||||
expect(serverACalendars[0].externalId).toBe(
|
||||
"https://server-a.example.com/dav/calendars/user/calendar1/"
|
||||
);
|
||||
|
||||
// Test Server B credential - should only return Server B calendars
|
||||
const serverBCalendars = filterSelectedCalendarsForCredential(selectedCalendars, serverBCredential);
|
||||
expect(serverBCalendars).toHaveLength(1);
|
||||
expect(serverBCalendars[0].externalId).toBe(
|
||||
"https://server-b.example.com/dav/calendars/user/calendar2/"
|
||||
);
|
||||
});
|
||||
|
||||
it("demonstrates the credential leak that existed before the fix", () => {
|
||||
// This test shows what WOULD happen with naive filtering (integration type only)
|
||||
const serverACredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_server_a_key",
|
||||
});
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
credentialId: 1,
|
||||
}),
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "https://server-b.example.com/dav/calendars/user/calendar2/",
|
||||
credentialId: 2,
|
||||
}),
|
||||
];
|
||||
|
||||
// Legacy filtering (type-only) would return ALL CalDAV calendars
|
||||
const legacyFiltering = selectedCalendars.filter((sc) => sc.integration === "caldav_calendar");
|
||||
expect(legacyFiltering).toHaveLength(2); // This demonstrates the leak - both calendars returned
|
||||
|
||||
// Our new filtering prevents this
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user_a",
|
||||
password: "pass_a",
|
||||
url: "https://server-a.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const secureFiltering = filterSelectedCalendarsForCredential(selectedCalendars, serverACredential);
|
||||
expect(secureFiltering).toHaveLength(1); // Only calendars from matching server
|
||||
expect(secureFiltering[0].externalId).toContain("server-a.example.com");
|
||||
});
|
||||
|
||||
it("handles non-CalDAV calendars normally", () => {
|
||||
const googleCredential: CredentialForCalendarService = {
|
||||
id: 1,
|
||||
type: "google_calendar",
|
||||
key: "google_key",
|
||||
userId: 1,
|
||||
user: { email: "[email protected]" },
|
||||
teamId: null,
|
||||
appId: "google-calendar",
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
}),
|
||||
{
|
||||
...buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "primary",
|
||||
}),
|
||||
integration: "google_calendar",
|
||||
},
|
||||
];
|
||||
|
||||
const googleCalendars = filterSelectedCalendarsForCredential(selectedCalendars, googleCredential);
|
||||
expect(googleCalendars).toHaveLength(1);
|
||||
expect(googleCalendars[0].integration).toBe("google_calendar");
|
||||
});
|
||||
|
||||
it("handles invalid CalDAV credential URLs gracefully", () => {
|
||||
const invalidCredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_invalid_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "invalid-url-format",
|
||||
})
|
||||
);
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
}),
|
||||
];
|
||||
|
||||
const result = filterSelectedCalendarsForCredential(selectedCalendars, invalidCredential);
|
||||
expect(result).toHaveLength(0); // Should return empty array for safety
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getPiiFreeSelectedCalendar, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
import type { EventBusyDate, SelectedCalendar } from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getCalendarsEvents"] });
|
||||
|
||||
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
|
||||
// only for Google Calendar for now
|
||||
export const getCalendarsEventsWithTimezones = async (
|
||||
withCredentials: CredentialForCalendarService[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[]
|
||||
): Promise<(EventBusyDate & { timeZone: string })[][]> => {
|
||||
const calendarCredentials = withCredentials
|
||||
.filter((credential) => credential.type === "google_calendar")
|
||||
// filter out invalid credentials - these won't work.
|
||||
.filter((credential) => !credential.invalid);
|
||||
|
||||
const calendarAndCredentialPairs = await Promise.all(
|
||||
calendarCredentials.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
return [calendar, credential] as const;
|
||||
})
|
||||
);
|
||||
|
||||
const calendars = calendarAndCredentialPairs.map(([calendar]) => calendar);
|
||||
const calendarToCredentialMap = new Map(calendarAndCredentialPairs);
|
||||
|
||||
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 */
|
||||
const { type } = calendarCredentials[i];
|
||||
const credential = calendarToCredentialMap.get(c);
|
||||
/** We just pass the calendars that matched the credential type,
|
||||
* TODO: Migrate credential type or appId
|
||||
*/
|
||||
const passedSelectedCalendars = credential
|
||||
? filterSelectedCalendarsForCredential(selectedCalendars, credential)
|
||||
: selectedCalendars
|
||||
.filter((sc) => sc.integration === type)
|
||||
// Needed to ensure cache keys are consistent
|
||||
.sort((a, b) => (a.externalId < b.externalId ? -1 : a.externalId > b.externalId ? 1 : 0));
|
||||
const isADelegationCredential = credential && isDelegationCredential({ credentialId: credential.id });
|
||||
// We want to fallback to primary calendar when no selectedCalendars are passed
|
||||
// Default behaviour for Google Calendar is to use all available calendars, which isn't good default.
|
||||
const allowFallbackToPrimary = isADelegationCredential;
|
||||
if (!passedSelectedCalendars.length) {
|
||||
if (!isADelegationCredential) {
|
||||
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
|
||||
// https://github.com/calcom/cal.com/issues/8929
|
||||
log.error(
|
||||
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
|
||||
// This is also, similar to how Google Calendar connect flow(through /googlecalendar/api/callback) sets the primary calendar as the selected calendar automatically.
|
||||
log.info("Allowing getAvailability even without any selected calendars for Delegation Credential");
|
||||
}
|
||||
/** We extract external Ids so we don't cache too much */
|
||||
const eventBusyDates =
|
||||
(await c.getAvailabilityWithTimeZones?.(
|
||||
dateFrom,
|
||||
dateTo,
|
||||
passedSelectedCalendars,
|
||||
allowFallbackToPrimary
|
||||
)) || [];
|
||||
|
||||
return eventBusyDates;
|
||||
});
|
||||
const awaitedResults = await Promise.all(results);
|
||||
return awaitedResults;
|
||||
};
|
||||
|
||||
const getCalendarsEvents = async (
|
||||
withCredentials: CredentialForCalendarService[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[],
|
||||
shouldServeCache?: boolean
|
||||
): Promise<EventBusyDate[][]> => {
|
||||
const calendarCredentials = withCredentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
// filter out invalid credentials - these won't work.
|
||||
.filter((credential) => !credential.invalid);
|
||||
|
||||
const calendarAndCredentialPairs = await Promise.all(
|
||||
calendarCredentials.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
return [calendar, credential] as const;
|
||||
})
|
||||
);
|
||||
|
||||
const calendars = calendarAndCredentialPairs.map(([calendar]) => calendar);
|
||||
const calendarToCredentialMap = new Map(calendarAndCredentialPairs);
|
||||
performance.mark("getBusyCalendarTimesStart");
|
||||
const results = calendars.map(async (calendarService, i) => {
|
||||
/** Filter out nulls */
|
||||
if (!calendarService) return [];
|
||||
/** We rely on the index so we can match credentials with calendars */
|
||||
const { type, appId } = calendarCredentials[i];
|
||||
const credential = calendarToCredentialMap.get(calendarService);
|
||||
/** We just pass the calendars that matched the credential type,
|
||||
* TODO: Migrate credential type or appId
|
||||
*/
|
||||
// Important to have them unique so that
|
||||
const passedSelectedCalendars = credential
|
||||
? filterSelectedCalendarsForCredential(selectedCalendars, credential)
|
||||
: selectedCalendars
|
||||
.filter((sc) => sc.integration === type)
|
||||
// Needed to ensure cache keys are consistent
|
||||
.sort((a, b) => (a.externalId < b.externalId ? -1 : a.externalId > b.externalId ? 1 : 0));
|
||||
const isADelegationCredential = credential && isDelegationCredential({ credentialId: credential.id });
|
||||
// We want to fallback to primary calendar when no selectedCalendars are passed
|
||||
// Default behaviour for Google Calendar is to use all available calendars, which isn't good default.
|
||||
const allowFallbackToPrimary = isADelegationCredential;
|
||||
if (!passedSelectedCalendars.length) {
|
||||
if (!isADelegationCredential) {
|
||||
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
|
||||
// https://github.com/calcom/cal.com/issues/8929
|
||||
log.error(
|
||||
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
|
||||
// This is also, similar to how Google Calendar connect flow(through /googlecalendar/api/callback) sets the primary calendar as the selected calendar automatically.
|
||||
log.info("Allowing getAvailability even without any selected calendars for Delegation Credential");
|
||||
}
|
||||
/** We extract external Ids so we don't cache too much */
|
||||
|
||||
const selectedCalendarIds = passedSelectedCalendars.map((sc) => sc.externalId);
|
||||
/** If we don't then we actually fetch external calendars (which can be very slow) */
|
||||
performance.mark("eventBusyDatesStart");
|
||||
log.debug(
|
||||
`Getting availability for`,
|
||||
safeStringify({
|
||||
calendarService: calendarService.constructor.name,
|
||||
selectedCalendars: passedSelectedCalendars.map(getPiiFreeSelectedCalendar),
|
||||
})
|
||||
);
|
||||
const eventBusyDates = await calendarService.getAvailability(
|
||||
dateFrom,
|
||||
dateTo,
|
||||
passedSelectedCalendars,
|
||||
shouldServeCache,
|
||||
allowFallbackToPrimary
|
||||
);
|
||||
performance.mark("eventBusyDatesEnd");
|
||||
performance.measure(
|
||||
`[getAvailability for ${selectedCalendarIds.join(", ")}][$1]'`,
|
||||
"eventBusyDatesStart",
|
||||
"eventBusyDatesEnd"
|
||||
);
|
||||
|
||||
return eventBusyDates.map((a) => ({
|
||||
...a,
|
||||
source: `${appId}`,
|
||||
}));
|
||||
});
|
||||
const awaitedResults = await Promise.all(results);
|
||||
performance.mark("getBusyCalendarTimesEnd");
|
||||
performance.measure(
|
||||
`getBusyCalendarTimes took $1 for creds ${calendarCredentials.map((cred) => cred.id)}`,
|
||||
"getBusyCalendarTimesStart",
|
||||
"getBusyCalendarTimesEnd"
|
||||
);
|
||||
log.debug(
|
||||
"Result",
|
||||
safeStringify({
|
||||
calendarCredentials: calendarCredentials.map(getPiiFreeCredential),
|
||||
selectedCalendars: selectedCalendars.map(getPiiFreeSelectedCalendar),
|
||||
calendarEvents: awaitedResults,
|
||||
})
|
||||
);
|
||||
return awaitedResults;
|
||||
};
|
||||
|
||||
export default getCalendarsEvents;
|
||||
|
||||
/**
|
||||
* Extract server URL from CalDAV calendar externalId
|
||||
*/
|
||||
function getServerUrlFromCalendarExternalId(externalId: string): string | null {
|
||||
try {
|
||||
const url = new URL(externalId);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract server URL from CalDAV credential
|
||||
*/
|
||||
function getServerUrlFromCredential(credential: CredentialForCalendarService): string | null {
|
||||
try {
|
||||
if (credential.type !== "caldav_calendar") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const decryptedData = JSON.parse(symmetricDecrypt(credential.key as string, CALENDSO_ENCRYPTION_KEY));
|
||||
|
||||
if (!decryptedData.url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(decryptedData.url);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter selected calendars for the specific credential, handling CalDAV server URL matching
|
||||
*/
|
||||
export function filterSelectedCalendarsForCredential(
|
||||
selectedCalendars: SelectedCalendar[],
|
||||
credential: CredentialForCalendarService
|
||||
): SelectedCalendar[] {
|
||||
const { type } = credential;
|
||||
|
||||
// For all other calendar types, use the existing logic
|
||||
if (type !== "caldav_calendar") {
|
||||
return selectedCalendars.filter((sc) => sc.integration === type);
|
||||
}
|
||||
|
||||
const credentialServerUrl = getServerUrlFromCredential(credential);
|
||||
|
||||
if (!credentialServerUrl) {
|
||||
log.warn("Could not extract server URL from CalDAV credential", {
|
||||
credentialId: credential.id,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
return selectedCalendars.filter((sc) => {
|
||||
if (sc.integration !== type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const calendarServerUrl = getServerUrlFromCalendarExternalId(sc.externalId);
|
||||
|
||||
if (!calendarServerUrl) {
|
||||
log.warn("Could not extract server URL from calendar externalId", {
|
||||
externalId: sc.externalId,
|
||||
integration: sc.integration,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const matches = credentialServerUrl === calendarServerUrl;
|
||||
|
||||
if (!matches) {
|
||||
log.debug("CalDAV calendar server URL does not match credential server URL", {
|
||||
credentialId: credential.id,
|
||||
credentialServerUrl,
|
||||
calendarServerUrl,
|
||||
calendarExternalId: sc.externalId,
|
||||
});
|
||||
}
|
||||
|
||||
return matches;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/app-store/delegationCredential";
|
||||
import {
|
||||
getCalendarCredentials,
|
||||
getConnectedCalendars,
|
||||
} from "@calcom/features/calendars/lib/CalendarManager";
|
||||
import { isDelegationCredential } from "@calcom/lib/delegationCredential";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { DestinationCalendarRepository } from "@calcom/lib/server/repository/destinationCalendar";
|
||||
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
|
||||
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { DestinationCalendar, SelectedCalendar, User } from "@calcom/prisma/client";
|
||||
import { AppCategories } from "@calcom/prisma/enums";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getConnectedDestinationCalendarsAndEnsureDefaultsInDb"] });
|
||||
|
||||
type ReturnTypeGetConnectedCalendars = Awaited<ReturnType<typeof getConnectedCalendars>>;
|
||||
type ConnectedCalendarsFromGetConnectedCalendars = ReturnTypeGetConnectedCalendars["connectedCalendars"];
|
||||
|
||||
export type UserWithCalendars = Pick<User, "id" | "email"> & {
|
||||
allSelectedCalendars: Pick<
|
||||
SelectedCalendar,
|
||||
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
|
||||
>[];
|
||||
userLevelSelectedCalendars: Pick<
|
||||
SelectedCalendar,
|
||||
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
|
||||
>[];
|
||||
destinationCalendar: DestinationCalendar | null;
|
||||
};
|
||||
|
||||
export type ConnectedDestinationCalendars = Awaited<
|
||||
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Ensures that when DelegationCredential is enabled and there is already a calendar connected for the corresponding domain, we only allow the DelegationCredential calendar to be returned
|
||||
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DelegationCredential connection to be shown because we don't want users to be able to work with individual calendars
|
||||
*/
|
||||
const _ensureNoConflictingNonDelegatedConnectedCalendar = <
|
||||
T extends {
|
||||
integration: { slug: string };
|
||||
primary?: { email?: string | null | undefined } | undefined;
|
||||
delegationCredentialId?: string | null | undefined;
|
||||
}
|
||||
>({
|
||||
connectedCalendars,
|
||||
loggedInUser,
|
||||
}: {
|
||||
connectedCalendars: T[];
|
||||
loggedInUser: { email: string };
|
||||
}) => {
|
||||
return connectedCalendars.filter((connectedCalendar, index, array) => {
|
||||
const allCalendarsWithSameAppSlug = array.filter(
|
||||
(cal) => cal.integration.slug === connectedCalendar.integration.slug
|
||||
);
|
||||
|
||||
// If no other calendar with this slug, keep it
|
||||
if (allCalendarsWithSameAppSlug.length === 1) return true;
|
||||
|
||||
const delegatedCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
|
||||
(cal) => cal.delegationCredentialId
|
||||
);
|
||||
if (!delegatedCalendarsWithSameAppSlug.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (connectedCalendar.delegationCredentialId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// DelegationCredential Credential is always of the loggedInUser
|
||||
if (!connectedCalendar.primary?.email || connectedCalendar.primary.email !== loggedInUser.email) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
async function handleNoConnectedCalendars(user: UserWithCalendars) {
|
||||
log.debug(`No connected calendars, deleting destination calendar if it exists for user ${user.id}`);
|
||||
|
||||
if (!user.destinationCalendar) return user;
|
||||
await prisma.destinationCalendar.delete({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
return {
|
||||
...user,
|
||||
destinationCalendar: null,
|
||||
};
|
||||
}
|
||||
|
||||
type ToggledCalendarDetails = {
|
||||
externalId: string;
|
||||
integration: string;
|
||||
};
|
||||
|
||||
async function handleNoDestinationCalendar({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
onboarding: boolean;
|
||||
}) {
|
||||
if (!connectedCalendars.length) {
|
||||
throw new Error("No connected calendars");
|
||||
}
|
||||
|
||||
// This is the calendar that we will ensure is enabled for conflict check
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
|
||||
log.debug(
|
||||
`There are connected calendars, but no destination calendar, so create a default destination calendar in DB for user ${user.id}`
|
||||
);
|
||||
/*
|
||||
So create a default destination calendar with the first primary connected calendar
|
||||
*/
|
||||
const {
|
||||
integration = "",
|
||||
externalId = "",
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
email: primaryEmail,
|
||||
} = connectedCalendars[0].primary ?? {};
|
||||
|
||||
// Select the first calendar matching the primary by default since that will also be the destination calendar
|
||||
if (onboarding && externalId) {
|
||||
const calendarIndex = (connectedCalendars[0].calendars || []).findIndex(
|
||||
(item) => item.externalId === externalId && item.integration === integration
|
||||
);
|
||||
if (calendarIndex >= 0 && connectedCalendars[0].calendars) {
|
||||
connectedCalendars[0].calendars[calendarIndex].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId,
|
||||
integration,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
user.destinationCalendar = await DestinationCalendarRepository.createIfNotExistsForUser({
|
||||
userId: user.id,
|
||||
integration,
|
||||
externalId,
|
||||
primaryEmail,
|
||||
...(!isDelegationCredential({ credentialId })
|
||||
? {
|
||||
credentialId,
|
||||
}
|
||||
: {
|
||||
delegationCredentialId,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
user,
|
||||
connectedCalendars,
|
||||
calendarToEnsureIsEnabledForConflictCheck,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleDestinationCalendarNotInConnectedCalendars({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
onboarding: boolean;
|
||||
}) {
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
log.debug(
|
||||
`Destination calendar isn't in connectedCalendars, update it to the first primary connected calendar for user ${user.id}`
|
||||
);
|
||||
const { integration = "", externalId = "", email: primaryEmail } = connectedCalendars[0].primary ?? {};
|
||||
// Select the first calendar matching the primary by default since that will also be the destination calendar
|
||||
if (onboarding && externalId) {
|
||||
const calendarIndex = (connectedCalendars[0].calendars || []).findIndex(
|
||||
(item) => item.externalId === externalId && item.integration === integration
|
||||
);
|
||||
if (calendarIndex >= 0 && connectedCalendars[0].calendars) {
|
||||
connectedCalendars[0].calendars[calendarIndex].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId,
|
||||
integration,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
user.destinationCalendar = await prisma.destinationCalendar.update({
|
||||
where: { userId: user.id },
|
||||
data: {
|
||||
integration,
|
||||
externalId,
|
||||
primaryEmail,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
user,
|
||||
connectedCalendars,
|
||||
calendarToEnsureIsEnabledForConflictCheck,
|
||||
};
|
||||
}
|
||||
|
||||
function findMatchingCalendar({
|
||||
connectedCalendars,
|
||||
calendar,
|
||||
}: {
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
calendar: DestinationCalendar;
|
||||
}) {
|
||||
// Check if destinationCalendar exists in connectedCalendars
|
||||
const allCals = connectedCalendars.map((cal) => cal.calendars ?? []).flat();
|
||||
const matchingCalendar = allCals.find(
|
||||
(cal) => cal.externalId === calendar.externalId && cal.integration === calendar.integration
|
||||
);
|
||||
return matchingCalendar;
|
||||
}
|
||||
|
||||
async function ensureSelectedCalendarIsInDb({
|
||||
user,
|
||||
selectedCalendar,
|
||||
eventTypeId,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
selectedCalendar: {
|
||||
integration: string;
|
||||
externalId: string;
|
||||
};
|
||||
eventTypeId: number | null;
|
||||
}) {
|
||||
console.log(
|
||||
`Upsert the selectedCalendar record to the DB for user ${user.id} with details ${JSON.stringify(
|
||||
selectedCalendar
|
||||
)}`
|
||||
);
|
||||
|
||||
await SelectedCalendarRepository.createIfNotExists({
|
||||
userId: user.id,
|
||||
integration: selectedCalendar.integration,
|
||||
externalId: selectedCalendar.externalId,
|
||||
eventTypeId,
|
||||
});
|
||||
}
|
||||
|
||||
function getSelectedCalendars({
|
||||
user,
|
||||
eventTypeId,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
eventTypeId: number | null;
|
||||
}) {
|
||||
if (eventTypeId) {
|
||||
return EventTypeRepository.getSelectedCalendarsFromUser({
|
||||
user,
|
||||
eventTypeId: eventTypeId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return user.userLevelSelectedCalendars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the calendars for the authenticated user or the event-type if provided
|
||||
* It also takes care of updating the destination calendar in some edge cases
|
||||
*/
|
||||
export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
|
||||
user,
|
||||
onboarding,
|
||||
eventTypeId,
|
||||
prisma,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
onboarding: boolean;
|
||||
eventTypeId?: number | null;
|
||||
prisma: PrismaClient;
|
||||
}) {
|
||||
const userCredentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
app: {
|
||||
categories: { has: AppCategories.calendar },
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
select: credentialForCalendarServiceSelect,
|
||||
});
|
||||
|
||||
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: { id: user.id, email: user.email, credentials: userCredentials },
|
||||
});
|
||||
|
||||
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
|
||||
// get user's credentials + their connected integrations
|
||||
const calendarCredentials = getCalendarCredentials(allCredentials);
|
||||
|
||||
// get all the connected integrations' calendars (from third party)
|
||||
const getConnectedCalendarsResult = await getConnectedCalendars(
|
||||
calendarCredentials,
|
||||
selectedCalendars,
|
||||
user.destinationCalendar?.externalId
|
||||
);
|
||||
|
||||
let connectedCalendars = getConnectedCalendarsResult.connectedCalendars;
|
||||
const destinationCalendar = getConnectedCalendarsResult.destinationCalendar;
|
||||
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
|
||||
if (connectedCalendars.length === 0) {
|
||||
user = await handleNoConnectedCalendars(user);
|
||||
} else if (!user.destinationCalendar) {
|
||||
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
|
||||
await handleNoDestinationCalendar({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}));
|
||||
} else {
|
||||
/* There are connected calendars and a destination calendar */
|
||||
log.debug(
|
||||
`There are connected calendars and a destination calendar, so check if destinationCalendar exists in connectedCalendars for user ${user.id}`
|
||||
);
|
||||
|
||||
const destinationCal = findMatchingCalendar({ connectedCalendars, calendar: user.destinationCalendar });
|
||||
if (!destinationCal) {
|
||||
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
|
||||
await handleDestinationCalendarNotInConnectedCalendars({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}));
|
||||
} else if (onboarding && !destinationCal.isSelected) {
|
||||
log.debug(
|
||||
`Onboarding:Destination calendar is not selected, but in connectedCalendars, so mark it as selected in the calendar list for user ${user.id}`
|
||||
);
|
||||
// Mark the destination calendar as selected in the calendar list
|
||||
// We use every so that we can exit early once we find the matching calendar
|
||||
connectedCalendars.every((cal) => {
|
||||
const index = (cal.calendars || []).findIndex(
|
||||
(calendar) =>
|
||||
calendar.externalId === destinationCal.externalId &&
|
||||
calendar.integration === destinationCal.integration
|
||||
);
|
||||
if (index >= 0 && cal.calendars) {
|
||||
cal.calendars[index].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId: destinationCal.externalId,
|
||||
integration: destinationCal.integration || "",
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Insert the newly toggled record to the DB
|
||||
if (calendarToEnsureIsEnabledForConflictCheck) {
|
||||
await ensureSelectedCalendarIsInDb({
|
||||
user,
|
||||
selectedCalendar: calendarToEnsureIsEnabledForConflictCheck,
|
||||
eventTypeId: eventTypeId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
const noConflictingNonDelegatedConnectedCalendars = _ensureNoConflictingNonDelegatedConnectedCalendar({
|
||||
connectedCalendars,
|
||||
loggedInUser: { email: user.email },
|
||||
});
|
||||
return {
|
||||
connectedCalendars: noConflictingNonDelegatedConnectedCalendars,
|
||||
destinationCalendar: {
|
||||
...(user.destinationCalendar as DestinationCalendar),
|
||||
...destinationCalendar,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy export for @calcom/platform-libraries
|
||||
export const getConnectedDestinationCalendars = getConnectedDestinationCalendarsAndEnsureDefaultsInDb;
|
||||
Reference in new issue
Block a user