2021-06-16 21:40:13 +00:00
|
|
|
import EventOwnerMail from "./emails/EventOwnerMail";
|
2021-06-16 22:56:02 +00:00
|
|
|
import EventAttendeeMail from "./emails/EventAttendeeMail";
|
|
|
|
import {v5 as uuidv5} from 'uuid';
|
|
|
|
import short from 'short-uuid';
|
2021-06-17 00:44:13 +00:00
|
|
|
import EventOwnerRescheduledMail from "./emails/EventOwnerRescheduledMail";
|
|
|
|
import EventAttendeeRescheduledMail from "./emails/EventAttendeeRescheduledMail";
|
2021-06-16 22:56:02 +00:00
|
|
|
|
|
|
|
const translator = short();
|
2021-06-16 21:40:13 +00:00
|
|
|
|
2021-04-21 22:10:48 +00:00
|
|
|
const {google} = require('googleapis');
|
|
|
|
|
|
|
|
const googleAuth = () => {
|
2021-06-17 00:44:13 +00:00
|
|
|
const {client_secret, client_id, redirect_uris} = JSON.parse(process.env.GOOGLE_API_CREDENTIALS).web;
|
|
|
|
return new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
|
2021-04-21 22:10:48 +00:00
|
|
|
};
|
|
|
|
|
2021-06-08 00:25:34 +00:00
|
|
|
function handleErrorsJson(response) {
|
2021-06-17 00:44:13 +00:00
|
|
|
if (!response.ok) {
|
|
|
|
response.json().then(console.log);
|
|
|
|
throw Error(response.statusText);
|
|
|
|
}
|
|
|
|
return response.json();
|
2021-04-21 22:10:48 +00:00
|
|
|
}
|
|
|
|
|
2021-06-08 00:25:34 +00:00
|
|
|
function handleErrorsRaw(response) {
|
2021-06-17 00:44:13 +00:00
|
|
|
if (!response.ok) {
|
|
|
|
response.text().then(console.log);
|
|
|
|
throw Error(response.statusText);
|
|
|
|
}
|
|
|
|
return response.text();
|
2021-06-08 00:25:34 +00:00
|
|
|
}
|
2021-04-21 22:10:48 +00:00
|
|
|
|
|
|
|
const o365Auth = (credential) => {
|
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const isExpired = (expiryDate) => expiryDate < +(new Date());
|
|
|
|
|
|
|
|
const refreshAccessToken = (refreshToken) => fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
|
|
|
body: new URLSearchParams({
|
|
|
|
'scope': 'User.Read Calendars.Read Calendars.ReadWrite',
|
|
|
|
'client_id': process.env.MS_GRAPH_CLIENT_ID,
|
|
|
|
'refresh_token': refreshToken,
|
|
|
|
'grant_type': 'refresh_token',
|
|
|
|
'client_secret': process.env.MS_GRAPH_CLIENT_SECRET,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.then(handleErrorsJson)
|
|
|
|
.then((responseBody) => {
|
|
|
|
credential.key.access_token = responseBody.access_token;
|
|
|
|
credential.key.expiry_date = Math.round((+(new Date()) / 1000) + responseBody.expires_in);
|
|
|
|
return credential.key.access_token;
|
2021-04-21 22:10:48 +00:00
|
|
|
})
|
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
return {
|
|
|
|
getToken: () => !isExpired(credential.key.expiry_date) ? Promise.resolve(credential.key.access_token) : refreshAccessToken(credential.key.refresh_token)
|
|
|
|
};
|
2021-04-21 22:10:48 +00:00
|
|
|
};
|
|
|
|
|
2021-06-06 23:10:56 +00:00
|
|
|
interface Person {
|
2021-06-17 00:44:13 +00:00
|
|
|
name?: string,
|
|
|
|
email: string,
|
|
|
|
timeZone: string
|
2021-06-06 23:10:56 +00:00
|
|
|
}
|
|
|
|
|
2021-04-21 22:10:48 +00:00
|
|
|
interface CalendarEvent {
|
2021-06-17 00:44:13 +00:00
|
|
|
type: string;
|
|
|
|
title: string;
|
|
|
|
startTime: string;
|
|
|
|
endTime: string;
|
|
|
|
description?: string;
|
|
|
|
location?: string;
|
|
|
|
organizer: Person;
|
|
|
|
attendees: Person[];
|
2021-04-21 22:10:48 +00:00
|
|
|
};
|
|
|
|
|
2021-05-27 22:10:20 +00:00
|
|
|
interface CalendarApiAdapter {
|
2021-06-17 00:44:13 +00:00
|
|
|
createEvent(event: CalendarEvent): Promise<any>;
|
2021-06-06 23:10:56 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
updateEvent(uid: String, event: CalendarEvent);
|
2021-06-06 23:10:56 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
deleteEvent(uid: String);
|
2021-06-06 23:10:56 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
getAvailability(dateFrom, dateTo): Promise<any>;
|
2021-05-27 22:10:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const MicrosoftOffice365Calendar = (credential): CalendarApiAdapter => {
|
2021-04-21 22:10:48 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const auth = o365Auth(credential);
|
2021-05-08 19:03:47 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const translateEvent = (event: CalendarEvent) => {
|
2021-05-08 19:03:47 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
let optional = {};
|
|
|
|
if (event.location) {
|
|
|
|
optional.location = {displayName: event.location};
|
|
|
|
}
|
2021-04-21 22:10:48 +00:00
|
|
|
|
|
|
|
return {
|
2021-06-17 00:44:13 +00:00
|
|
|
subject: event.title,
|
|
|
|
body: {
|
|
|
|
contentType: 'HTML',
|
|
|
|
content: event.description,
|
|
|
|
},
|
|
|
|
start: {
|
|
|
|
dateTime: event.startTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
end: {
|
|
|
|
dateTime: event.endTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
attendees: event.attendees.map(attendee => ({
|
|
|
|
emailAddress: {
|
|
|
|
address: attendee.email,
|
|
|
|
name: attendee.name
|
2021-04-21 22:10:48 +00:00
|
|
|
},
|
2021-06-17 00:44:13 +00:00
|
|
|
type: "required"
|
|
|
|
})),
|
|
|
|
...optional
|
2021-04-21 22:10:48 +00:00
|
|
|
}
|
2021-06-17 00:44:13 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
getAvailability: (dateFrom, dateTo) => {
|
|
|
|
const payload = {
|
|
|
|
schedules: [credential.key.email],
|
|
|
|
startTime: {
|
|
|
|
dateTime: dateFrom,
|
|
|
|
timeZone: 'UTC',
|
|
|
|
},
|
|
|
|
endTime: {
|
|
|
|
dateTime: dateTo,
|
|
|
|
timeZone: 'UTC',
|
|
|
|
},
|
|
|
|
availabilityViewInterval: 60
|
|
|
|
};
|
|
|
|
|
|
|
|
return auth.getToken().then(
|
|
|
|
(accessToken) => fetch('https://graph.microsoft.com/v1.0/me/calendar/getSchedule', {
|
|
|
|
method: 'post',
|
|
|
|
headers: {
|
|
|
|
'Authorization': 'Bearer ' + accessToken,
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
},
|
|
|
|
body: JSON.stringify(payload)
|
|
|
|
})
|
|
|
|
.then(handleErrorsJson)
|
|
|
|
.then(responseBody => {
|
|
|
|
return responseBody.value[0].scheduleItems.map((evt) => ({
|
|
|
|
start: evt.start.dateTime + 'Z',
|
|
|
|
end: evt.end.dateTime + 'Z'
|
|
|
|
}))
|
|
|
|
})
|
|
|
|
).catch((err) => {
|
|
|
|
console.log(err);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
createEvent: (event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events', {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'Authorization': 'Bearer ' + accessToken,
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
body: JSON.stringify(translateEvent(event))
|
|
|
|
}).then(handleErrorsJson).then((responseBody) => ({
|
|
|
|
...responseBody,
|
|
|
|
disableConfirmationEmail: true,
|
|
|
|
}))),
|
|
|
|
deleteEvent: (uid: String) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
|
|
|
|
method: 'DELETE',
|
|
|
|
headers: {
|
|
|
|
'Authorization': 'Bearer ' + accessToken
|
|
|
|
}
|
|
|
|
}).then(handleErrorsRaw)),
|
|
|
|
updateEvent: (uid: String, event: CalendarEvent) => auth.getToken().then(accessToken => fetch('https://graph.microsoft.com/v1.0/me/calendar/events/' + uid, {
|
|
|
|
method: 'PATCH',
|
|
|
|
headers: {
|
|
|
|
'Authorization': 'Bearer ' + accessToken,
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
},
|
|
|
|
body: JSON.stringify(translateEvent(event))
|
|
|
|
}).then(handleErrorsRaw)),
|
|
|
|
}
|
2021-04-21 22:10:48 +00:00
|
|
|
};
|
|
|
|
|
2021-05-27 22:10:20 +00:00
|
|
|
const GoogleCalendar = (credential): CalendarApiAdapter => {
|
2021-06-17 00:44:13 +00:00
|
|
|
const myGoogleAuth = googleAuth();
|
|
|
|
myGoogleAuth.setCredentials(credential.key);
|
|
|
|
return {
|
|
|
|
getAvailability: (dateFrom, dateTo) => new Promise((resolve, reject) => {
|
|
|
|
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
|
|
|
calendar.calendarList
|
|
|
|
.list()
|
|
|
|
.then(cals => {
|
|
|
|
calendar.freebusy.query({
|
|
|
|
requestBody: {
|
|
|
|
timeMin: dateFrom,
|
|
|
|
timeMax: dateTo,
|
|
|
|
items: cals.data.items
|
2021-05-08 19:03:47 +00:00
|
|
|
}
|
2021-06-17 00:44:13 +00:00
|
|
|
}, (err, apires) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
2021-06-09 20:03:05 +00:00
|
|
|
}
|
2021-06-17 00:44:13 +00:00
|
|
|
resolve(
|
|
|
|
Object.values(apires.data.calendars).flatMap(
|
|
|
|
(item) => item["busy"]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
});
|
2021-04-21 22:10:48 +00:00
|
|
|
})
|
2021-06-17 00:44:13 +00:00
|
|
|
.catch((err) => {
|
|
|
|
reject(err);
|
|
|
|
});
|
|
|
|
|
|
|
|
}),
|
|
|
|
createEvent: (event: CalendarEvent) => new Promise((resolve, reject) => {
|
|
|
|
const payload = {
|
|
|
|
summary: event.title,
|
|
|
|
description: event.description,
|
|
|
|
start: {
|
|
|
|
dateTime: event.startTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
end: {
|
|
|
|
dateTime: event.endTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
attendees: event.attendees,
|
|
|
|
reminders: {
|
|
|
|
useDefault: false,
|
|
|
|
overrides: [
|
|
|
|
{'method': 'email', 'minutes': 60}
|
|
|
|
],
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
if (event.location) {
|
|
|
|
payload['location'] = event.location;
|
|
|
|
}
|
|
|
|
|
|
|
|
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
|
|
|
calendar.events.insert({
|
|
|
|
auth: myGoogleAuth,
|
|
|
|
calendarId: 'primary',
|
|
|
|
resource: payload,
|
|
|
|
}, function (err, event) {
|
|
|
|
if (err) {
|
|
|
|
console.log('There was an error contacting the Calendar service: ' + err);
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
return resolve(event.data);
|
|
|
|
});
|
|
|
|
}),
|
|
|
|
updateEvent: (uid: String, event: CalendarEvent) => new Promise((resolve, reject) => {
|
|
|
|
const payload = {
|
|
|
|
summary: event.title,
|
|
|
|
description: event.description,
|
|
|
|
start: {
|
|
|
|
dateTime: event.startTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
end: {
|
|
|
|
dateTime: event.endTime,
|
|
|
|
timeZone: event.organizer.timeZone,
|
|
|
|
},
|
|
|
|
attendees: event.attendees,
|
|
|
|
reminders: {
|
|
|
|
useDefault: false,
|
|
|
|
overrides: [
|
|
|
|
{'method': 'email', 'minutes': 60}
|
|
|
|
],
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
if (event.location) {
|
|
|
|
payload['location'] = event.location;
|
|
|
|
}
|
|
|
|
|
|
|
|
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
|
|
|
calendar.events.update({
|
|
|
|
auth: myGoogleAuth,
|
|
|
|
calendarId: 'primary',
|
|
|
|
eventId: uid,
|
|
|
|
sendNotifications: true,
|
|
|
|
sendUpdates: 'all',
|
|
|
|
resource: payload
|
|
|
|
}, function (err, event) {
|
|
|
|
if (err) {
|
|
|
|
console.log('There was an error contacting the Calendar service: ' + err);
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
return resolve(event.data);
|
|
|
|
});
|
|
|
|
}),
|
|
|
|
deleteEvent: (uid: String) => new Promise((resolve, reject) => {
|
|
|
|
const calendar = google.calendar({version: 'v3', auth: myGoogleAuth});
|
|
|
|
calendar.events.delete({
|
|
|
|
auth: myGoogleAuth,
|
|
|
|
calendarId: 'primary',
|
|
|
|
eventId: uid,
|
|
|
|
sendNotifications: true,
|
|
|
|
sendUpdates: 'all',
|
|
|
|
}, function (err, event) {
|
|
|
|
if (err) {
|
|
|
|
console.log('There was an error contacting the Calendar service: ' + err);
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
return resolve(event.data);
|
|
|
|
});
|
|
|
|
})
|
|
|
|
};
|
2021-04-21 22:10:48 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// factory
|
2021-06-06 23:10:56 +00:00
|
|
|
const calendars = (withCredentials): CalendarApiAdapter[] => withCredentials.map((cred) => {
|
2021-06-17 00:44:13 +00:00
|
|
|
switch (cred.type) {
|
|
|
|
case 'google_calendar':
|
|
|
|
return GoogleCalendar(cred);
|
|
|
|
case 'office365_calendar':
|
|
|
|
return MicrosoftOffice365Calendar(cred);
|
|
|
|
default:
|
|
|
|
return; // unknown credential, could be legacy? In any case, ignore
|
|
|
|
}
|
2021-04-21 22:10:48 +00:00
|
|
|
}).filter(Boolean);
|
|
|
|
|
|
|
|
|
2021-06-16 23:41:56 +00:00
|
|
|
const getBusyCalendarTimes = (withCredentials, dateFrom, dateTo) => Promise.all(
|
2021-06-17 00:44:13 +00:00
|
|
|
calendars(withCredentials).map(c => c.getAvailability(dateFrom, dateTo))
|
2021-04-21 22:10:48 +00:00
|
|
|
).then(
|
2021-06-17 00:44:13 +00:00
|
|
|
(results) => results.reduce((acc, availability) => acc.concat(availability), [])
|
2021-04-21 22:10:48 +00:00
|
|
|
);
|
|
|
|
|
2021-06-16 22:56:02 +00:00
|
|
|
const createEvent = async (credential, calEvent: CalendarEvent): Promise<any> => {
|
2021-06-17 00:44:13 +00:00
|
|
|
const uid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
2021-06-01 19:16:06 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const creationResult = credential ? await calendars([credential])[0].createEvent(calEvent) : null;
|
2021-06-01 19:16:06 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const ownerMail = new EventOwnerMail(calEvent, uid);
|
|
|
|
const attendeeMail = new EventAttendeeMail(calEvent, uid);
|
|
|
|
await ownerMail.sendEmail();
|
2021-06-16 22:56:02 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
if (!creationResult || !creationResult.disableConfirmationEmail) {
|
|
|
|
await attendeeMail.sendEmail();
|
|
|
|
}
|
2021-06-16 22:56:02 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
return {
|
|
|
|
uid,
|
|
|
|
createdEvent: creationResult
|
|
|
|
};
|
2021-05-27 22:10:20 +00:00
|
|
|
};
|
2021-04-21 22:10:48 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const updateEvent = async (credential, uidToUpdate: String, calEvent: CalendarEvent): Promise<any> => {
|
|
|
|
const newUid: string = translator.fromUUID(uuidv5(JSON.stringify(calEvent), uuidv5.URL));
|
2021-06-06 23:10:56 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
const updateResult = credential ? await calendars([credential])[0].updateEvent(uidToUpdate, calEvent) : null;
|
|
|
|
|
|
|
|
const ownerMail = new EventOwnerRescheduledMail(calEvent, newUid);
|
|
|
|
const attendeeMail = new EventAttendeeRescheduledMail(calEvent, newUid);
|
|
|
|
await ownerMail.sendEmail();
|
|
|
|
|
|
|
|
if (!updateResult || !updateResult.disableConfirmationEmail) {
|
|
|
|
await attendeeMail.sendEmail();
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
uid: newUid,
|
|
|
|
updatedEvent: updateResult
|
|
|
|
};
|
2021-06-06 23:10:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
const deleteEvent = (credential, uid: String): Promise<any> => {
|
2021-06-17 00:44:13 +00:00
|
|
|
if (credential) {
|
|
|
|
return calendars([credential])[0].deleteEvent(uid);
|
|
|
|
}
|
2021-06-06 23:10:56 +00:00
|
|
|
|
2021-06-17 00:44:13 +00:00
|
|
|
return Promise.resolve({});
|
2021-06-06 23:10:56 +00:00
|
|
|
};
|
|
|
|
|
2021-06-16 23:41:56 +00:00
|
|
|
export {getBusyCalendarTimes, createEvent, updateEvent, deleteEvent, CalendarEvent};
|