@@ -129,3 +129,72 @@ function parseDate(string) {
129129 return new Date ( parts . join ( ' ' ) ) ;
130130}
131131// [END listNext10Events]
132+
133+ // [START logSyncedEvents]
134+
135+ /**
136+ * Retrieve and log events from the given calendar that have been modified
137+ * since the last sync. If the sync token is missing or invalid, log all
138+ * events from up to a month ago (a full sync).
139+ *
140+ * @param calendarId The ID of the calender to retrieve events from.
141+ * @param fullSync If true, throw out any existing sync token and perform a full sync;
142+ * if false, use the existing sync token if possible.
143+ */
144+ function logSyncedEvents ( calendarId , fullSync ) {
145+ var properties = PropertiesService . getUserProperties ( ) ;
146+ var pageToken ;
147+ var options = {
148+ maxResults : 100
149+ } ;
150+ var syncToken = properties . getProperty ( 'syncToken' ) ;
151+ if ( syncToken && ! fullSync ) {
152+ options [ 'syncToken' ] = syncToken ;
153+ } else {
154+ // Sync events up to thirty days in the past.
155+ options [ 'timeMin' ] = getRelativeDate ( - 30 , 0 ) . toISOString ( ) ;
156+ }
157+
158+ // Retrieve events, one page at a time.
159+ var events ;
160+ do {
161+ try {
162+ options [ 'pageToken' ] = pageToken ;
163+ events = Calendar . Events . list ( calendarId , options ) ;
164+ } catch ( e ) {
165+ // Check to see if the sync token was invalidated by the server;
166+ // if so, perform a full sync instead.
167+ if ( e . message === "Sync token is no longer valid, a full sync is required." ) {
168+ properties . deleteProperty ( 'syncToken' ) ;
169+ logSyncedEvents ( calendarId , true ) ;
170+ return ;
171+ } else {
172+ throw e . message ;
173+ }
174+ }
175+
176+ if ( events . items && events . items . length > 0 ) {
177+ for ( var i = 0 ; i < events . items . length ; i ++ ) {
178+ var event = events . items [ i ] ;
179+ if ( event . status === 'cancelled' ) {
180+ console . log ( 'Event id %s was cancelled.' , event . id ) ;
181+ } else if ( event . start . date ) {
182+ // All-day event.
183+ var start = parseDate ( event . start . date ) ;
184+ console . log ( '%s (%s)' , event . summary , start . toLocaleDateString ( ) ) ;
185+ } else {
186+ var start = parseDate ( event . start . dateTime ) ;
187+ console . log ( '%s (%s)' , event . summary , start . toLocaleString ( ) ) ;
188+ }
189+ }
190+ } else {
191+ console . log ( 'No events found.' ) ;
192+ }
193+
194+ pageToken = events . nextPageToken ;
195+ } while ( pageToken ) ;
196+
197+ properties . setProperty ( 'syncToken' , events . nextSyncToken ) ;
198+ }
199+
200+ // [END logSyncedEvents]
0 commit comments