forked from googleworkspace/apps-script-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalendar.gs
284 lines (274 loc) · 8.93 KB
/
calendar.gs
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
* Copyright Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// [START apps_script_calendar_list_calendars]
/**
* Lists the calendars shown in the user's calendar list.
*/
function listCalendars() {
var calendars;
var pageToken;
do {
calendars = Calendar.CalendarList.list({
maxResults: 100,
pageToken: pageToken
});
if (calendars.items && calendars.items.length > 0) {
for (var i = 0; i < calendars.items.length; i++) {
var calendar = calendars.items[i];
Logger.log('%s (ID: %s)', calendar.summary, calendar.id);
}
} else {
Logger.log('No calendars found.');
}
pageToken = calendars.nextPageToken;
} while (pageToken);
}
// [END apps_script_calendar_list_calendars]
// [START apps_script_calendar_create_event]
/**
* Creates an event in the user's default calendar.
*/
function createEvent() {
var calendarId = 'primary';
var start = getRelativeDate(1, 12);
var end = getRelativeDate(1, 13);
var event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
start: {
dateTime: start.toISOString()
},
end: {
dateTime: end.toISOString()
},
attendees: [
{email: 'alice@example.com'},
{email: 'bob@example.com'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.id);
}
/**
* Helper function to get a new Date object relative to the current date.
* @param {number} daysOffset The number of days in the future for the new date.
* @param {number} hour The hour of the day for the new date, in the time zone
* of the script.
* @return {Date} The new date.
*/
function getRelativeDate(daysOffset, hour) {
var date = new Date();
date.setDate(date.getDate() + daysOffset);
date.setHours(hour);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
// [END apps_script_calendar_create_event]
// [START apps_script_calendar_list_events]
/**
* Lists the next 10 upcoming events in the user's default calendar.
*/
function listNext10Events() {
var calendarId = 'primary';
var now = new Date();
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 10
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
Logger.log('%s (%s)', event.summary, start.toLocaleDateString());
} else {
var start = new Date(event.start.dateTime);
Logger.log('%s (%s)', event.summary, start.toLocaleString());
}
}
} else {
Logger.log('No events found.');
}
}
// [END apps_script_calendar_list_events]
// [START apps_script_calendar_log_synced_events]
/**
* Retrieve and log events from the given calendar that have been modified
* since the last sync. If the sync token is missing or invalid, log all
* events from up to a month ago (a full sync).
*
* @param {string} calendarId The ID of the calender to retrieve events from.
* @param {boolean} fullSync If true, throw out any existing sync token and
* perform a full sync; if false, use the existing sync token if possible.
*/
function logSyncedEvents(calendarId, fullSync) {
var properties = PropertiesService.getUserProperties();
var options = {
maxResults: 100
};
var syncToken = properties.getProperty('syncToken');
if (syncToken && !fullSync) {
options.syncToken = syncToken;
} else {
// Sync events up to thirty days in the past.
options.timeMin = getRelativeDate(-30, 0).toISOString();
}
// Retrieve events one page at a time.
var events;
var pageToken;
do {
try {
options.pageToken = pageToken;
events = Calendar.Events.list(calendarId, options);
} catch (e) {
// Check to see if the sync token was invalidated by the server;
// if so, perform a full sync instead.
if (e.message === 'Sync token is no longer valid, a full sync is required.') {
properties.deleteProperty('syncToken');
logSyncedEvents(calendarId, true);
return;
} else {
throw new Error(e.message);
}
}
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event = events.items[i];
if (event.status === 'cancelled') {
console.log('Event id %s was cancelled.', event.id);
} else if (event.start.date) {
// All-day event.
var start = new Date(event.start.date);
console.log('%s (%s)', event.summary, start.toLocaleDateString());
} else {
// Events that don't last all day; they have defined start times.
var start = new Date(event.start.dateTime);
console.log('%s (%s)', event.summary, start.toLocaleString());
}
}
} else {
console.log('No events found.');
}
pageToken = events.nextPageToken;
} while (pageToken);
properties.setProperty('syncToken', events.nextSyncToken);
}
// [END apps_script_calendar_log_synced_events]
// [START apps_script_calendar_conditional_update]
/**
* Creates an event in the user's default calendar, waits 30 seconds, then
* attempts to update the event's location, on the condition that the event
* has not been changed since it was created. If the event is changed during
* the 30-second wait, then the subsequent update will throw a 'Precondition
* Failed' error.
*
* The conditional update is accomplished by setting the 'If-Match' header
* to the etag of the new event when it was created.
*/
function conditionalUpdate() {
var calendarId = 'primary';
var start = getRelativeDate(1, 12);
var end = getRelativeDate(1, 13);
var event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
start: {
dateTime: start.toISOString()
},
end: {
dateTime: end.toISOString()
},
attendees: [
{email: 'alice@example.com'},
{email: 'bob@example.com'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.getId());
// Wait 30 seconds to see if the event has been updated outside this script.
Utilities.sleep(30 * 1000);
// Try to update the event, on the condition that the event state has not
// changed since the event was created.
event.location = 'The Coffee Shop';
try {
event = Calendar.Events.update(
event,
calendarId,
event.id,
{},
{'If-Match': event.etag}
);
Logger.log('Successfully updated event: ' + event.id);
} catch (e) {
Logger.log('Fetch threw an exception: ' + e);
}
}
// [END apps_script_calendar_conditional_update]
// [START apps_script_calendar_conditional_fetch]
/**
* Creates an event in the user's default calendar, then re-fetches the event
* every second, on the condition that the event has changed since the last
* fetch.
*
* The conditional fetch is accomplished by setting the 'If-None-Match' header
* to the etag of the last known state of the event.
*/
function conditionalFetch() {
var calendarId = 'primary';
var start = getRelativeDate(1, 12);
var end = getRelativeDate(1, 13);
var event = {
summary: 'Lunch Meeting',
location: 'The Deli',
description: 'To discuss our plans for the presentation next week.',
start: {
dateTime: start.toISOString()
},
end: {
dateTime: end.toISOString()
},
attendees: [
{email: 'alice@example.com'},
{email: 'bob@example.com'}
],
// Red background. Use Calendar.Colors.get() for the full list.
colorId: 11
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.getId());
// Re-fetch the event each second, but only get a result if it has changed.
for (var i = 0; i < 30; i++) {
Utilities.sleep(1000);
try {
event = Calendar.Events.get(calendarId, event.id, {}, {'If-None-Match': event.etag});
Logger.log('New event description: ' + event.description);
} catch (e) {
Logger.log('Fetch threw an exception: ' + e);
}
}
}
// [END apps_script_calendar_conditional_fetch]