-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
executable file
·230 lines (189 loc) · 8.79 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/node
import { calendar_v3, google } from 'googleapis';
import { JWT } from 'google-auth-library/build/src/auth/jwtclient';
import { readFileSync } from 'fs';
import { EventStatus, EventTransparency, SourceEvent, SourceTargetConfiguration } from './models';
import moment = require('moment');
import { parseIcalFile } from './ical-parser';
const calendar: calendar_v3.Calendar = google.calendar('v3');
const key = JSON.parse(readFileSync('google_calendar_key.json', 'utf8'));
const scopes = ['https://www.googleapis.com/auth/calendar'];
const auth: JWT = new google.auth.JWT(key.client_email, undefined, key.private_key, scopes, undefined);
const syncCalendar = async (): Promise<{
createCounter: number,
updateCounter: number,
removeCounter: number,
}> => {
let createCounter = 0;
let updateCounter = 0;
let removeCounter = 0;
const config: SourceTargetConfiguration[] = JSON.parse(readFileSync('config.json', 'utf8'));
for (const configEntry of config) {
try {
const pastDays = configEntry.pastDays || 7;
const futureDays = configEntry.futureDays || 14;
const earliestDate = moment(new Date()).subtract(pastDays, 'days').toDate();
const latestDate = moment(new Date()).add(futureDays, 'days').toDate();
let sourceEvents: SourceEvent[];
if (configEntry.sourceCalendar) {
sourceEvents = await getGoogleCalendarSourceEvents(configEntry);
} else if (configEntry.sourceIcalLink) {
sourceEvents = await parseIcalFile(configEntry.sourceIcalLink);
} else {
console.warn(`Either sourceCalendar or sourceIcalLink has to be present for ConfigEntry`);
continue;
}
// Do not include without title (summary) or description
sourceEvents = sourceEvents.filter(t => t.summary || t.description);
// Do not include events that were before earliest date (because ical might include older events)
sourceEvents = sourceEvents.filter(t => t.start.getTime() > earliestDate.getTime());
// Do not include events that were after lates date (because ical might include newer events)
sourceEvents = sourceEvents.filter(t => t.start.getTime() < latestDate.getTime());
// Do not include events with transparency === transparent as they do not block the time
sourceEvents = sourceEvents.filter(t => !(t.transparency && t.transparency === EventTransparency.TRANSPARENT));
const targetEvents = await getGoogleEventsWithPagination(auth, configEntry.targetCalendar, earliestDate, latestDate);
let eventsToRemove = targetEvents?.filter(t => t.description?.includes(`google-sync-calendar-config-id: ${configEntry.id}`)) || [];
for (const sourceEvent of sourceEvents) {
const sourceEventId = sourceEvent.id;
if (!sourceEventId) {
console.warn(`Skipping event ${sourceEvent.summary} because no id is available`);
continue;
}
if (sourceEvent.status === EventStatus.CANCELLED) {
// Will be removed later, if it was synced before
continue;
}
const targetEvent = targetEvents.filter(t => t.description?.includes(`google-sync-calender-source-id: ${sourceEventId}`))[0];
if (!targetEvent) {
try {
await createEvent(sourceEvent, configEntry);
createCounter++;
} catch (e) {
console.error('Error while creating event', e);
}
continue;
}
// Event still exists -> Should not be removed
eventsToRemove = eventsToRemove.filter(t => t.description !== targetEvent.description);
if (areEventsEqual(sourceEvent, mapGoogleEventToSourceEvent(targetEvent))) {
// Nothing to do
continue;
}
// Something got changed
try {
await updateEvent(sourceEvent, targetEvent, configEntry);
updateCounter++;
} catch (e) {
console.error('Error while updating event', e);
}
}
// Remove events which no longer exist in source
for (const eventToRemove of eventsToRemove) {
try {
await calendar.events.delete({
auth,
calendarId: configEntry.targetCalendar,
eventId: eventToRemove.id || eventToRemove.iCalUID,
});
removeCounter++;
} catch (e) {
console.error('Error while deleting event', e);
}
}
} catch (e) {
console.error(`Error while processing ${configEntry.id}`, e);
}
}
return {
createCounter,
updateCounter,
removeCounter,
};
}
const areEventsEqual = (a: SourceEvent, b: SourceEvent): boolean => {
return (a.start.getTime() === b.start.getTime()) &&
(a.end.getTime() === b.end.getTime());
}
const createEvent = async (sourceEvent: SourceEvent, configEntry: SourceTargetConfiguration): Promise<void> => {
await calendar.events.insert({
auth,
calendarId: configEntry.targetCalendar,
requestBody: getRequestBody(sourceEvent, configEntry),
});
}
const updateEvent = async (sourceEvent: SourceEvent, targetEvent: calendar_v3.Schema$Event, configEntry: SourceTargetConfiguration): Promise<void> => {
await calendar.events.update({
auth,
calendarId: configEntry.targetCalendar,
eventId: targetEvent.id || targetEvent.iCalUID,
requestBody: getRequestBody(sourceEvent, configEntry),
});
}
const getRequestBody = (sourceEvent: SourceEvent, configEntry: SourceTargetConfiguration): calendar_v3.Schema$Event => {
return {
summary: configEntry.label || 'Private event',
description: `This is a private event synced by google-calendar-sync.
Do not update/remove this event manually - changes will be overwritten!
google-sync-calender-source-id: ${sourceEvent.id}
google-sync-calendar-config-id: ${configEntry.id}
`,
start: {dateTime: sourceEvent.start.toISOString()},
end: {dateTime: sourceEvent.end.toISOString()},
}
}
const mapGoogleEventToSourceEvent = (event: calendar_v3.Schema$Event): SourceEvent => {
let status = EventStatus.CONFIRMED;
if (event.status === 'cancelled') {
status = EventStatus.CANCELLED;
} else if (event.status === 'tentative') {
status = EventStatus.TENTATIVE;
}
let transparency: EventTransparency;
if (event.transparency === 'transparent') {
transparency = EventTransparency.TRANSPARENT;
} else if (event.transparency === 'opaque') {
transparency = EventTransparency.OPAQUE;
}
return {
id: event.id || event.iCalUID,
status,
summary: event.summary,
description: event.description,
start: new Date(event.start.dateTime),
end: new Date(event.end.dateTime),
transparency,
}
}
const getGoogleCalendarSourceEvents = async (configEntry: SourceTargetConfiguration): Promise<SourceEvent[]> => {
const pastDays = configEntry.pastDays || 7;
const futureDays = configEntry.futureDays || 14;
const earliestDate = moment(new Date()).subtract(pastDays, 'days').toDate();
const latestDate = moment(new Date()).add(futureDays, 'days').toDate();
const googleEvents = await getGoogleEventsWithPagination(auth, configEntry.sourceCalendar, earliestDate, latestDate);
return googleEvents.map(e => mapGoogleEventToSourceEvent(e));
}
const getGoogleEventsWithPagination = async (auth: JWT, calendarId: string, timeMin: Date, timeMax: Date): Promise<calendar_v3.Schema$Event[]> => {
const result: calendar_v3.Schema$Event[] = [];
let nextPageToken = undefined;
while (true) {
const response = await calendar.events.list({
auth,
calendarId,
timeMin: timeMin.toISOString(),
timeMax: timeMax.toISOString(),
singleEvents: true,
pageToken: nextPageToken
});
result.push(...response.data.items);
if (response.data.nextPageToken) {
nextPageToken = response.data.nextPageToken;
} else {
// All results retrieved
break;
}
}
return result;
}
syncCalendar().then((res) => {
console.log(`Everything synced (${res.createCounter} created, ${res.updateCounter} updated, ${res.removeCounter} removed)`);
});