add select primary calendar (#1133)
* add primary * fix * refactor eventmanager to take `CalendarDestination` * `DestinationCalendar` * fix * wip * wip * Minor fixes (#1156) * Followup for #1242 * Updates schema * Renames fields to destinationCalendar * Migration fixes * Updates user destination calendar * Abstracts convertDate to BaseCalendarApiAdapter * Type fixes * Uses abstracted convertDate method * Abstracts getDuration and getAttendees * Fixes circular dependecy issue * Adds notEmpty util * Reverts empty location string * Fixes property name * Removes deprecated code * WIP * AppleCal is basically CalDav * Fixes missing destinationCalendar * Type fixes * Select primary calendar on Office and gCal * Adds pretty basic instructions for destination calendar * Cleanup * Type fix * Test fixes * Updates test snapshot * Local test fixes * Type fixes Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Omar López <[email protected]> Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
26 files changed
+745
-917
No files matched your search
@@ -0,0 +1,349 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import ICAL from "ical.js";
|
||||
import { Attendee, createEvent, DateArray, DurationObject } from "ics";
|
||||
import {
|
||||
createAccount,
|
||||
createCalendarObject,
|
||||
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 logger from "@lib/logger";
|
||||
|
||||
import { CalendarEvent, IntegrationCalendar } from "./calendarClient";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
export type Person = { name: string; email: string; timeZone: string };
|
||||
|
||||
export class BaseCalendarApiAdapter {
|
||||
private url: string;
|
||||
private credentials: Record<string, string>;
|
||||
private headers: Record<string, string>;
|
||||
private integrationName = "";
|
||||
|
||||
constructor(credential: Credential, integrationName: string, url?: string) {
|
||||
const decryptedCredential = JSON.parse(
|
||||
symmetricDecrypt(credential.key as string, process.env.CALENDSO_ENCRYPTION_KEY!)
|
||||
);
|
||||
const username = decryptedCredential.username;
|
||||
const password = decryptedCredential.password;
|
||||
this.url = url || decryptedCredential.url;
|
||||
this.integrationName = integrationName;
|
||||
this.credentials = { username, password };
|
||||
this.headers = getBasicAuthHeaders({ username, password });
|
||||
}
|
||||
|
||||
log = logger.getChildLogger({ prefix: [`[[lib] ${this.integrationName}`] });
|
||||
|
||||
convertDate(date: string): DateArray {
|
||||
return dayjs(date)
|
||||
.utc()
|
||||
.toArray()
|
||||
.slice(0, 6)
|
||||
.map((v, i) => (i === 1 ? v + 1 : v)) as DateArray;
|
||||
}
|
||||
|
||||
getDuration(start: string, end: string): DurationObject {
|
||||
return {
|
||||
minutes: dayjs(end).diff(dayjs(start), "minute"),
|
||||
};
|
||||
}
|
||||
|
||||
getAttendees(attendees: Person[]): Attendee[] {
|
||||
return attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
|
||||
}
|
||||
|
||||
async createEvent(event: CalendarEvent) {
|
||||
try {
|
||||
const calendars = await this.listCalendars(event);
|
||||
const uid = uuidv4();
|
||||
/** We create local ICS files */
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) throw new Error("Error creating iCalString");
|
||||
|
||||
if (!iCalString) throw new Error("Error creating iCalString");
|
||||
|
||||
/** We create the event directly on iCal */
|
||||
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`,
|
||||
iCalString,
|
||||
headers: this.headers,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
return {
|
||||
uid,
|
||||
id: uid,
|
||||
type: this.integrationName,
|
||||
password: "",
|
||||
url: "",
|
||||
};
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent) {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
this.log.debug("Error creating iCalString");
|
||||
return {};
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
return await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return updateCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
data: iCalString,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string): Promise<void> {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return deleteCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailability(dateFrom: string, dateTo: string, selectedCalendars: IntegrationCalendar[]) {
|
||||
try {
|
||||
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
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
selectedCalendarIds.length === 0
|
||||
? this.listCalendars().then((calendars) => calendars.map((calendar) => calendar.externalId))
|
||||
: Promise.resolve(selectedCalendarIds)
|
||||
).then(async (ids: string[]) => {
|
||||
if (ids.length === 0) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
ids.map(async (calId) => {
|
||||
return (await this.getEvents(calId, dateFrom, dateTo)).map((event) => {
|
||||
return {
|
||||
start: event.startDate.toISOString(),
|
||||
end: event.endDate.toISOString(),
|
||||
};
|
||||
});
|
||||
})
|
||||
)
|
||||
).flatMap((event) => event);
|
||||
});
|
||||
} catch (reason) {
|
||||
this.log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
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("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
end: dayjs(dateTo).utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
}
|
||||
: 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(event.startDate.toJSDate()).tz(calendarTimezone)
|
||||
: new Date(event.startDate.toUnixTime() * 1000);
|
||||
const endDate = calendarTimezone
|
||||
? dayjs(event.endDate.toJSDate()).tz(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 getAccount() {
|
||||
const account = await createAccount({
|
||||
account: {
|
||||
serverUrl: this.url,
|
||||
accountType: "caldav",
|
||||
credentials: this.credentials,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export const getLocation = (calEvent: CalendarEvent) => {
|
||||
return calEvent.additionInformation.hangoutLink;
|
||||
}
|
||||
|
||||
return providerName || calEvent.location;
|
||||
return providerName || calEvent.location || "";
|
||||
};
|
||||
|
||||
export const getManageLink = (calEvent: CalendarEvent) => {
|
||||
|
||||
+33
-89
@@ -1,5 +1,4 @@
|
||||
/* eslint-disable @typescript-eslint/ban-ts-comment */
|
||||
import { Credential, SelectedCalendar } from "@prisma/client";
|
||||
import { Credential, DestinationCalendar, SelectedCalendar } from "@prisma/client";
|
||||
import { TFunction } from "next-i18next";
|
||||
|
||||
import { PaymentInfo } from "@ee/lib/stripe/server";
|
||||
@@ -9,16 +8,14 @@ import { Event, EventResult } from "@lib/events/EventManager";
|
||||
import { AppleCalendar } from "@lib/integrations/Apple/AppleCalendarAdapter";
|
||||
import { CalDavCalendar } from "@lib/integrations/CalDav/CalDavCalendarAdapter";
|
||||
import {
|
||||
GoogleCalendarApiAdapter,
|
||||
ConferenceData,
|
||||
GoogleCalendarApiAdapter,
|
||||
} from "@lib/integrations/GoogleCalendar/GoogleCalendarApiAdapter";
|
||||
import {
|
||||
Office365CalendarApiAdapter,
|
||||
BufferedBusyTime,
|
||||
} from "@lib/integrations/Office365Calendar/Office365CalendarApiAdapter";
|
||||
import { Office365CalendarApiAdapter } from "@lib/integrations/Office365Calendar/Office365CalendarApiAdapter";
|
||||
import logger from "@lib/logger";
|
||||
import { VideoCallData } from "@lib/videoClient";
|
||||
|
||||
import notEmpty from "./notEmpty";
|
||||
import { Ensure } from "./types/utils";
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[lib] calendarClient"] });
|
||||
@@ -61,6 +58,7 @@ export interface CalendarEvent {
|
||||
uid?: string | null;
|
||||
videoCallData?: VideoCallData;
|
||||
paymentInfo?: PaymentInfo | null;
|
||||
destinationCalendar?: DestinationCalendar | null;
|
||||
}
|
||||
|
||||
export interface IntegrationCalendar extends Ensure<Partial<SelectedCalendar>, "externalId"> {
|
||||
@@ -68,6 +66,8 @@ export interface IntegrationCalendar extends Ensure<Partial<SelectedCalendar>, "
|
||||
name?: string;
|
||||
}
|
||||
|
||||
type EventBusyDate = Record<"start" | "end", Date | string>;
|
||||
|
||||
export interface CalendarApiAdapter {
|
||||
createEvent(event: CalendarEvent): Promise<Event>;
|
||||
|
||||
@@ -79,7 +79,7 @@ export interface CalendarApiAdapter {
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: IntegrationCalendar[]
|
||||
): Promise<BufferedBusyTime[]>;
|
||||
): Promise<EventBusyDate[]>;
|
||||
|
||||
listCalendars(): Promise<IntegrationCalendar[]>;
|
||||
}
|
||||
@@ -98,72 +98,32 @@ function getCalendarAdapterOrNull(credential: Credential): CalendarApiAdapter |
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
const calendars = (withCredentials: Credential[]): CalendarApiAdapter[] =>
|
||||
withCredentials
|
||||
.map((cred) => {
|
||||
switch (cred.type) {
|
||||
case "google_calendar":
|
||||
return GoogleCalendarApiAdapter(cred);
|
||||
case "office365_calendar":
|
||||
return Office365CalendarApiAdapter(cred);
|
||||
case "caldav_calendar":
|
||||
return new CalDavCalendar(cred);
|
||||
case "apple_calendar":
|
||||
return new AppleCalendar(cred);
|
||||
default:
|
||||
return; // unknown credential, could be legacy? In any case, ignore
|
||||
}
|
||||
})
|
||||
.flatMap((item) => (item ? [item as CalendarApiAdapter] : []));
|
||||
|
||||
const getBusyCalendarTimes = (
|
||||
const getBusyCalendarTimes = async (
|
||||
withCredentials: Credential[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[]
|
||||
) =>
|
||||
Promise.all(
|
||||
calendars(withCredentials).map((c) => c.getAvailability(dateFrom, dateTo, selectedCalendars))
|
||||
).then((results) => {
|
||||
return results.reduce((acc, availability) => acc.concat(availability), []);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
* @param withCredentials
|
||||
* @deprecated
|
||||
*/
|
||||
const listCalendars = (withCredentials: Credential[]) =>
|
||||
Promise.all(calendars(withCredentials).map((c) => c.listCalendars())).then((results) =>
|
||||
results.reduce((acc, calendars) => acc.concat(calendars), []).filter((c) => c != null)
|
||||
) => {
|
||||
const adapters = withCredentials.map(getCalendarAdapterOrNull).filter(notEmpty);
|
||||
const results = await Promise.all(
|
||||
adapters.map((c) => c.getAvailability(dateFrom, dateTo, selectedCalendars))
|
||||
);
|
||||
return results.reduce((acc, availability) => acc.concat(availability), []);
|
||||
};
|
||||
|
||||
const createEvent = async (credential: Credential, calEvent: CalendarEvent): Promise<EventResult> => {
|
||||
const uid: string = getUid(calEvent);
|
||||
const adapter = getCalendarAdapterOrNull(credential);
|
||||
let success = true;
|
||||
|
||||
const creationResult = credential
|
||||
? await calendars([credential])[0]
|
||||
.createEvent(calEvent)
|
||||
.catch((e) => {
|
||||
log.error("createEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
const creationResult = adapter
|
||||
? await adapter.createEvent(calEvent).catch((e) => {
|
||||
log.error("createEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (!creationResult) {
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
@@ -179,28 +139,18 @@ const updateEvent = async (
|
||||
bookingRefUid: string | null
|
||||
): Promise<EventResult> => {
|
||||
const uid = getUid(calEvent);
|
||||
const adapter = getCalendarAdapterOrNull(credential);
|
||||
let success = true;
|
||||
|
||||
const updatedResult =
|
||||
credential && bookingRefUid
|
||||
? await calendars([credential])[0]
|
||||
.updateEvent(bookingRefUid, calEvent)
|
||||
.catch((e) => {
|
||||
log.error("updateEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
adapter && bookingRefUid
|
||||
? await adapter.updateEvent(bookingRefUid, calEvent).catch((e) => {
|
||||
log.error("updateEvent failed", e, calEvent);
|
||||
success = false;
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (!updatedResult) {
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
originalEvent: calEvent,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: credential.type,
|
||||
success,
|
||||
@@ -211,18 +161,12 @@ const updateEvent = async (
|
||||
};
|
||||
|
||||
const deleteEvent = (credential: Credential, uid: string): Promise<unknown> => {
|
||||
if (credential) {
|
||||
return calendars([credential])[0].deleteEvent(uid);
|
||||
const adapter = getCalendarAdapterOrNull(credential);
|
||||
if (adapter) {
|
||||
return adapter.deleteEvent(uid);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
export {
|
||||
getBusyCalendarTimes,
|
||||
createEvent,
|
||||
updateEvent,
|
||||
deleteEvent,
|
||||
listCalendars,
|
||||
getCalendarAdapterOrNull,
|
||||
};
|
||||
export { getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, getCalendarAdapterOrNull };
|
||||
+24
-10
@@ -1,4 +1,4 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import { Credential, DestinationCalendar } from "@prisma/client";
|
||||
import async from "async";
|
||||
import merge from "lodash/merge";
|
||||
import { v5 as uuidv5 } from "uuid";
|
||||
@@ -86,18 +86,22 @@ export const processLocation = (event: CalendarEvent): CalendarEvent => {
|
||||
return event;
|
||||
};
|
||||
|
||||
type EventManagerUser = {
|
||||
credentials: Credential[];
|
||||
destinationCalendar: DestinationCalendar | null;
|
||||
};
|
||||
export default class EventManager {
|
||||
calendarCredentials: Array<Credential>;
|
||||
videoCredentials: Array<Credential>;
|
||||
calendarCredentials: Credential[];
|
||||
videoCredentials: Credential[];
|
||||
|
||||
/**
|
||||
* Takes an array of credentials and initializes a new instance of the EventManager.
|
||||
*
|
||||
* @param credentials
|
||||
*/
|
||||
constructor(credentials: Array<Credential>) {
|
||||
this.calendarCredentials = credentials.filter((cred) => cred.type.endsWith("_calendar"));
|
||||
this.videoCredentials = credentials.filter((cred) => cred.type.endsWith("_video"));
|
||||
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;
|
||||
@@ -180,6 +184,7 @@ export default class EventManager {
|
||||
meetingUrl: true,
|
||||
},
|
||||
},
|
||||
destinationCalendar: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -194,6 +199,7 @@ export default class EventManager {
|
||||
const result = await this.updateVideoEvent(evt, booking);
|
||||
if (result.updatedEvent) {
|
||||
evt.videoCallData = result.updatedEvent;
|
||||
evt.location = result.updatedEvent.url;
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
@@ -240,13 +246,21 @@ export default class EventManager {
|
||||
* @param noMail
|
||||
* @private
|
||||
*/
|
||||
|
||||
private async createAllCalendarEvents(event: CalendarEvent): Promise<Array<EventResult>> {
|
||||
const [firstCalendar] = this.calendarCredentials;
|
||||
if (!firstCalendar) {
|
||||
/** 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)));
|
||||
}
|
||||
|
||||
const [credential] = this.calendarCredentials;
|
||||
if (!credential) {
|
||||
return [];
|
||||
}
|
||||
return [await createEvent(firstCalendar, event)];
|
||||
return [await createEvent(credential, event)];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,346 +1,10 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import ICAL from "ical.js";
|
||||
import { createEvent, DurationObject, Attendee, Person } from "ics";
|
||||
import {
|
||||
createAccount,
|
||||
fetchCalendars,
|
||||
fetchCalendarObjects,
|
||||
getBasicAuthHeaders,
|
||||
createCalendarObject,
|
||||
updateCalendarObject,
|
||||
deleteCalendarObject,
|
||||
} from "tsdav";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { getLocation, getRichDescription } from "@lib/CalEventParser";
|
||||
import { symmetricDecrypt } from "@lib/crypto";
|
||||
import logger from "@lib/logger";
|
||||
|
||||
import { IntegrationCalendar, CalendarApiAdapter, CalendarEvent } from "../../calendarClient";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[[lib] apple calendar"] });
|
||||
|
||||
export class AppleCalendar implements CalendarApiAdapter {
|
||||
private url: string;
|
||||
private credentials: Record<string, string>;
|
||||
private headers: Record<string, string>;
|
||||
private readonly integrationName: string = "apple_calendar";
|
||||
import { BaseCalendarApiAdapter } from "@lib/BaseCalendarApiAdapter";
|
||||
import { CalendarApiAdapter } from "@lib/calendarClient";
|
||||
|
||||
export class AppleCalendar extends BaseCalendarApiAdapter implements CalendarApiAdapter {
|
||||
constructor(credential: Credential) {
|
||||
const decryptedCredential = JSON.parse(
|
||||
symmetricDecrypt(credential.key as string, process.env.CALENDSO_ENCRYPTION_KEY!)
|
||||
);
|
||||
const username = decryptedCredential.username;
|
||||
const password = decryptedCredential.password;
|
||||
|
||||
this.url = "https://caldav.icloud.com";
|
||||
|
||||
this.credentials = {
|
||||
username,
|
||||
password,
|
||||
};
|
||||
|
||||
this.headers = getBasicAuthHeaders({
|
||||
username,
|
||||
password,
|
||||
});
|
||||
}
|
||||
|
||||
convertDate(date: string): [number, number, number] {
|
||||
return dayjs(date)
|
||||
.utc()
|
||||
.toArray()
|
||||
.slice(0, 6)
|
||||
.map((v, i) => (i === 1 ? v + 1 : v)) as [number, number, number];
|
||||
}
|
||||
|
||||
getDuration(start: string, end: string): DurationObject {
|
||||
return {
|
||||
minutes: dayjs(end).diff(dayjs(start), "minute"),
|
||||
};
|
||||
}
|
||||
|
||||
getAttendees(attendees: Person[]): Attendee[] {
|
||||
return attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
|
||||
}
|
||||
|
||||
async createEvent(event: CalendarEvent) {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const uid = uuidv4();
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) throw new Error("Error creating iCalString");
|
||||
|
||||
if (!iCalString) throw new Error("Error creating iCalString");
|
||||
|
||||
await Promise.all(
|
||||
calendars.map((calendar) => {
|
||||
return createCalendarObject({
|
||||
calendar: {
|
||||
url: calendar.externalId,
|
||||
},
|
||||
filename: `${uid}.ics`,
|
||||
iCalString: iCalString,
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
uid,
|
||||
id: uid,
|
||||
type: "apple_calendar",
|
||||
password: "",
|
||||
url: "",
|
||||
};
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent): Promise<unknown> {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
log.debug("Error creating iCalString");
|
||||
return {};
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
return await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return updateCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
data: iCalString,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string): Promise<void> {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return deleteCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailability(dateFrom: string, dateTo: string, selectedCalendars: IntegrationCalendar[]) {
|
||||
try {
|
||||
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
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
selectedCalendarIds.length === 0
|
||||
? this.listCalendars().then((calendars) => calendars.map((calendar) => calendar.externalId))
|
||||
: Promise.resolve(selectedCalendarIds)
|
||||
).then(async (ids: string[]) => {
|
||||
if (ids.length === 0) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
ids.map(async (calId) => {
|
||||
return (await this.getEvents(calId, dateFrom, dateTo)).map((event) => {
|
||||
return {
|
||||
start: event.startDate.toISOString(),
|
||||
end: event.endDate.toISOString(),
|
||||
};
|
||||
});
|
||||
})
|
||||
)
|
||||
).flatMap((event) => event);
|
||||
});
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async listCalendars(): Promise<IntegrationCalendar[]> {
|
||||
try {
|
||||
const account = await this.getAccount();
|
||||
const calendars = await fetchCalendars({
|
||||
account,
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return calendars
|
||||
.filter((calendar) => {
|
||||
return calendar.components?.includes("VEVENT");
|
||||
})
|
||||
.map((calendar, index) => ({
|
||||
externalId: calendar.url,
|
||||
name: calendar.displayName ?? "",
|
||||
// FIXME Find a better way to set the primary calendar
|
||||
primary: index === 0,
|
||||
integration: this.integrationName,
|
||||
}));
|
||||
} catch (reason) {
|
||||
console.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
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("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
end: dayjs(dateTo).utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
}
|
||||
: 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(event.startDate.toJSDate()).tz(calendarTimezone)
|
||||
: new Date(event.startDate.toUnixTime() * 1000);
|
||||
const endDate = calendarTimezone
|
||||
? dayjs(event.endDate.toJSDate()).tz(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 getAccount() {
|
||||
const account = await createAccount({
|
||||
account: {
|
||||
serverUrl: this.url,
|
||||
accountType: "caldav",
|
||||
credentials: this.credentials,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return account;
|
||||
super(credential, "apple_calendar", "https://caldav.icloud.com");
|
||||
}
|
||||
}
|
||||
@@ -1,347 +1,10 @@
|
||||
import { Credential } from "@prisma/client";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import ICAL from "ical.js";
|
||||
import { Attendee, createEvent, DurationObject, Person } from "ics";
|
||||
import {
|
||||
createAccount,
|
||||
createCalendarObject,
|
||||
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 logger from "@lib/logger";
|
||||
|
||||
import { CalendarApiAdapter, CalendarEvent, IntegrationCalendar } from "../../calendarClient";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
const log = logger.getChildLogger({ prefix: ["[lib] caldav"] });
|
||||
|
||||
export class CalDavCalendar implements CalendarApiAdapter {
|
||||
private url: string;
|
||||
private credentials: Record<string, string>;
|
||||
private headers: Record<string, string>;
|
||||
private readonly integrationName: string = "caldav_calendar";
|
||||
import { BaseCalendarApiAdapter } from "@lib/BaseCalendarApiAdapter";
|
||||
import { CalendarApiAdapter } from "@lib/calendarClient";
|
||||
|
||||
export class CalDavCalendar extends BaseCalendarApiAdapter implements CalendarApiAdapter {
|
||||
constructor(credential: Credential) {
|
||||
const decryptedCredential = JSON.parse(
|
||||
symmetricDecrypt(credential.key as string, process.env.CALENDSO_ENCRYPTION_KEY!)
|
||||
);
|
||||
const username = decryptedCredential.username;
|
||||
const url = decryptedCredential.url;
|
||||
const password = decryptedCredential.password;
|
||||
|
||||
this.url = url;
|
||||
|
||||
this.credentials = {
|
||||
username,
|
||||
password,
|
||||
};
|
||||
|
||||
this.headers = getBasicAuthHeaders({
|
||||
username,
|
||||
password,
|
||||
});
|
||||
}
|
||||
|
||||
convertDate(date: string): [number, number, number] {
|
||||
return dayjs(date)
|
||||
.utc()
|
||||
.toArray()
|
||||
.slice(0, 6)
|
||||
.map((v, i) => (i === 1 ? v + 1 : v)) as [number, number, number];
|
||||
}
|
||||
|
||||
getDuration(start: string, end: string): DurationObject {
|
||||
return {
|
||||
minutes: dayjs(end).diff(dayjs(start), "minute"),
|
||||
};
|
||||
}
|
||||
|
||||
getAttendees(attendees: Person[]): Attendee[] {
|
||||
return attendees.map(({ email, name }) => ({ name, email, partstat: "NEEDS-ACTION" }));
|
||||
}
|
||||
|
||||
async createEvent(event: CalendarEvent) {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const uid = uuidv4();
|
||||
|
||||
const { error, value: iCalString } = createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) throw new Error("Error creating iCalString");
|
||||
|
||||
if (!iCalString) throw new Error("Error creating iCalString");
|
||||
|
||||
await Promise.all(
|
||||
calendars.map((calendar) => {
|
||||
return createCalendarObject({
|
||||
calendar: {
|
||||
url: calendar.externalId,
|
||||
},
|
||||
filename: `${uid}.ics`,
|
||||
iCalString: iCalString,
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
uid,
|
||||
id: uid,
|
||||
type: "caldav_calendar",
|
||||
password: "",
|
||||
url: "",
|
||||
};
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async updateEvent(uid: string, event: CalendarEvent): Promise<unknown> {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
for (const cal of calendars) {
|
||||
const calEvents = await this.getEvents(cal.externalId, null, null);
|
||||
|
||||
for (const ev of calEvents) {
|
||||
events.push(ev);
|
||||
}
|
||||
}
|
||||
|
||||
const { error, value: iCalString } = await createEvent({
|
||||
uid,
|
||||
startInputType: "utc",
|
||||
start: this.convertDate(event.startTime),
|
||||
duration: this.getDuration(event.startTime, event.endTime),
|
||||
title: event.title,
|
||||
description: getRichDescription(event),
|
||||
location: getLocation(event),
|
||||
organizer: { email: event.organizer.email, name: event.organizer.name },
|
||||
attendees: this.getAttendees(event.attendees),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
log.debug("Error creating iCalString");
|
||||
return {};
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
return await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return updateCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
data: iCalString,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteEvent(uid: string): Promise<void> {
|
||||
try {
|
||||
const calendars = await this.listCalendars();
|
||||
const events = [];
|
||||
|
||||
for (const cal of calendars) {
|
||||
const calEvents = await this.getEvents(cal.externalId, null, null);
|
||||
|
||||
for (const ev of calEvents) {
|
||||
events.push(ev);
|
||||
}
|
||||
}
|
||||
|
||||
const eventsToUpdate = events.filter((event) => event.uid === uid);
|
||||
|
||||
await Promise.all(
|
||||
eventsToUpdate.map((event) => {
|
||||
return deleteCalendarObject({
|
||||
calendarObject: {
|
||||
url: event.url,
|
||||
etag: event?.etag,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
})
|
||||
);
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async getAvailability(dateFrom: string, dateTo: string, selectedCalendars: IntegrationCalendar[]) {
|
||||
try {
|
||||
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
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
selectedCalendarIds.length === 0
|
||||
? this.listCalendars().then((calendars) => calendars.map((calendar) => calendar.externalId))
|
||||
: Promise.resolve(selectedCalendarIds)
|
||||
).then(async (ids: string[]) => {
|
||||
if (ids.length === 0) {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
return (
|
||||
await Promise.all(
|
||||
ids.map(async (calId) => {
|
||||
return (await this.getEvents(calId, dateFrom, dateTo)).map((event) => {
|
||||
return {
|
||||
start: event.startDate.toISOString(),
|
||||
end: event.endDate.toISOString(),
|
||||
};
|
||||
});
|
||||
})
|
||||
)
|
||||
).flatMap((event) => event);
|
||||
});
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async listCalendars(): Promise<IntegrationCalendar[]> {
|
||||
try {
|
||||
const account = await this.getAccount();
|
||||
const calendars = await fetchCalendars({
|
||||
account,
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return calendars
|
||||
.filter((calendar) => {
|
||||
return calendar.components?.includes("VEVENT");
|
||||
})
|
||||
.map((calendar, index) => ({
|
||||
externalId: calendar.url,
|
||||
name: calendar.displayName ?? "",
|
||||
// FIXME Find a better way to set the primary calendar
|
||||
primary: index === 0,
|
||||
integration: this.integrationName,
|
||||
}));
|
||||
} catch (reason) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
async getEvents(calId: string, dateFrom: string | null, dateTo: string | null) {
|
||||
try {
|
||||
const objects = await fetchCalendarObjects({
|
||||
calendar: {
|
||||
url: calId,
|
||||
},
|
||||
timeRange:
|
||||
dateFrom && dateTo
|
||||
? {
|
||||
start: dayjs(dateFrom).utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
end: dayjs(dateTo).utc().format("YYYY-MM-DDTHH:mm:ss[Z]"),
|
||||
}
|
||||
: undefined,
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
if (!objects || objects?.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
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(event.startDate.toJSDate()).tz(calendarTimezone)
|
||||
: new Date(event.startDate.toUnixTime() * 1000);
|
||||
const endDate = calendarTimezone
|
||||
? dayjs(event.endDate.toJSDate()).tz(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) {
|
||||
log.error(reason);
|
||||
throw reason;
|
||||
}
|
||||
}
|
||||
|
||||
private async getAccount() {
|
||||
const account = await createAccount({
|
||||
account: {
|
||||
serverUrl: `${this.url}`,
|
||||
accountType: "caldav",
|
||||
credentials: this.credentials,
|
||||
},
|
||||
headers: this.headers,
|
||||
});
|
||||
|
||||
return account;
|
||||
super(credential, "caldav_calendar");
|
||||
}
|
||||
}
|
||||
@@ -10,18 +10,30 @@ export interface ConferenceData {
|
||||
createRequest?: calendar_v3.Schema$CreateConferenceRequest;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const googleAuth = (credential: Credential) => {
|
||||
const { client_secret, client_id, redirect_uris } = JSON.parse(process.env.GOOGLE_API_CREDENTIALS!).web;
|
||||
const myGoogleAuth = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
||||
const myGoogleAuth = new MyGoogleAuth(client_id, client_secret, redirect_uris[0]);
|
||||
const googleCredentials = credential.key as Auth.Credentials;
|
||||
myGoogleAuth.setCredentials(googleCredentials);
|
||||
|
||||
// FIXME - type errors IDK Why this is a protected method ¯\_(ツ)_/¯
|
||||
const isExpired = () => myGoogleAuth.isTokenExpiring();
|
||||
|
||||
const refreshAccessToken = () =>
|
||||
myGoogleAuth
|
||||
// FIXME - type errors IDK Why this is a protected method ¯\_(ツ)_/¯
|
||||
.refreshToken(googleCredentials.refresh_token)
|
||||
.then((res: GetTokenResponse) => {
|
||||
const token = res.res?.data;
|
||||
@@ -149,7 +161,9 @@ export const GoogleCalendarApiAdapter = (credential: Credential): CalendarApiAda
|
||||
calendar.events.insert(
|
||||
{
|
||||
auth: myGoogleAuth,
|
||||
calendarId: "primary",
|
||||
calendarId: event.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId
|
||||
: "primary",
|
||||
requestBody: payload,
|
||||
conferenceDataVersion: 1,
|
||||
},
|
||||
@@ -201,7 +215,9 @@ export const GoogleCalendarApiAdapter = (credential: Credential): CalendarApiAda
|
||||
calendar.events.update(
|
||||
{
|
||||
auth: myGoogleAuth,
|
||||
calendarId: "primary",
|
||||
calendarId: event.destinationCalendar?.externalId
|
||||
? event.destinationCalendar.externalId
|
||||
: "primary",
|
||||
eventId: uid,
|
||||
sendNotifications: true,
|
||||
sendUpdates: "all",
|
||||
|
||||
@@ -182,16 +182,19 @@ export const Office365CalendarApiAdapter = (credential: Credential): CalendarApi
|
||||
});
|
||||
},
|
||||
createEvent: (event: CalendarEvent) =>
|
||||
auth.getToken().then((accessToken) =>
|
||||
fetch("https://graph.microsoft.com/v1.0/me/calendar/events", {
|
||||
auth.getToken().then((accessToken) => {
|
||||
const calendarId = event.destinationCalendar?.externalId
|
||||
? `${event.destinationCalendar.externalId}/`
|
||||
: "";
|
||||
return fetch(`https://graph.microsoft.com/v1.0/me/calendar/${calendarId}events`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + accessToken,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(translateEvent(event)),
|
||||
}).then(handleErrorsJson)
|
||||
),
|
||||
}).then(handleErrorsJson);
|
||||
}),
|
||||
deleteEvent: (uid: string) =>
|
||||
auth.getToken().then((accessToken) =>
|
||||
fetch("https://graph.microsoft.com/v1.0/me/calendar/events/" + uid, {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
const notEmpty = <T>(value: T): value is NonNullable<typeof value> => !!value;
|
||||
|
||||
export default notEmpty;
|
||||
+1
-1
@@ -51,7 +51,7 @@ const getVideoAdapters = (withCredentials: Credential[]): VideoApiAdapter[] =>
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const getBusyVideoTimes: (withCredentials: Credential[]) => Promise<unknown[]> = (withCredentials) =>
|
||||
const getBusyVideoTimes = (withCredentials: Credential[]) =>
|
||||
Promise.all(getVideoAdapters(withCredentials).map((c) => c.getAvailability())).then((results) =>
|
||||
results.reduce((acc, availability) => acc.concat(availability), [])
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user